如何使用nodejs将base64 png转换为pdf?

问题描述

有没有办法将多个 base64 PNG 文件转换为 PDF?

谢谢

解决方法

我认为您正在寻找这个。

import fs from 'fs';
let base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA';

// Remove header
let base64image = base64String.split(';base64,').pop();

fs.writeFile('filename.pdf',base64image,{encoding: 'base64'},function(err) {
    console.log('File created');
});
,

我能够使用节点画布解决问题

const fs = require('fs');
const {createCanvas,loadImage}= require('canvas');

// get the base64 string
const base64String = require("./base64");

loadImage(Buffer.from(base64String,"base64")).then(async (img) => {
  const canvas = createCanvas(img.width,img.height,'pdf');
  const ctx = canvas.getContext('2d');
  console.log(`w: ${img.width},h: ${img.height}`);

  ctx.drawImage(img,img.width,img.height);
  const base64image = canvas.toBuffer();
  
  // write the file to a pdf file
  fs.writeFile('simple.pdf',function(err) {
      console.log('File created');
  });
});

了解更多信息:https://www.npmjs.com/package/canvas

注意:解决方案不仅适用于 png,也适用于任何图像类型。

然后使用任何 pdf 库来合并 pdf,如 hummus