小程序云开发中如何生成pdf?

实践证明用方案1才是好的我要生成的pdf有点复杂,使用方案2太卡了。云函数受不了。体验很差。


// 云函数 图片 转 pdf 
const cloud = require('wx-server-sdk');
const { PDFDocument, StandardFonts, rgb } = require('pdf-lib');

cloud.init();

// 云函数入口函数
exports.main = async (event, context) => {
 let width = event.width;
 let height = event.height;
 let srcFileID  =event.srcFileID;

  const doc = await PDFDocument.create();

  let page = doc.addPage();
  page.setWidth(width);
  page.setHeight(height);

//图片
const lenderSignSign = await cloud.downloadFile({
  fileID:srcFileID
});
let img = await doc.embedPng(lenderSignSign.fileContent);
page.drawImage(img,{
  x: 0,
  y: 0
  ,width:width
  ,height:height
});

  const docBase64 = await doc.saveAsBase64()
  const docBuffer = Buffer.from(docBase64, 'base64');
  let fileName = 'tmp/' + parseInt(new Date().getTime() / 1000) + '.pdf';

  let result = await cloud.uploadFile({ cloudPath: fileName, fileContent: docBuffer });
  let fileID = result.fileID;
  //转http访问
  const fileList = await cloud.getTempFileURL({
    fileList: [fileID],
  });
  let pdf = fileList.fileList[0].tempFileURL;
  return { code: 1, msg: '', data: { fileID: fileID, pdf: pdf } }

}

pdf-lib介绍

参考

参考2

方案1

canvas先生成图片。云函数中再转成pdf
,使用pdf-lib 转成pdf

方案2

使用 pdf-lib 库生成。

1.新建云函数 testPdf 并安装 pdf-lib

npm install --save pdf-lib

2.testPdf内容

// 云函数入口文件
const cloud = require('wx-server-sdk')
const { PDFDocument, StandardFonts, rgb } = require('pdf-lib');
//const fontkit = require('@pdf-lib/fontkit’');

cloud.init();

// 云函数入口函数
exports.main = async (event, context) => {

  const doc = await PDFDocument.create();

 let page = doc.addPage();
 page.setWidth(800)
 page.setHeight(500)
 let helloWorld ='helloWorld';
 page.drawText(
  helloWorld,
  {
  x: 10,
  y: 450,
  size: 20,
  lineHeight: 20,
  },
  )
  const docBase64 = await doc.saveAsBase64()
  const docBuffer = Buffer.from(docBase64,'base64');
  let fileName = 'tmp/' + parseInt(new Date().getTime() / 1000) + '.pdf';

  //返回 fileID,https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/storage/uploadFile/server.uploadFile.html

  //如果需要https访问地址。可使用getTempFileURL方法转 
 return await cloud.uploadFile({ cloudPath: fileName, fileContent: docBuffer });



}
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值