Search code examples
node.jshummus.js

How to convert a base64 png to pdf using nodejs?


Is there a way to convert multiple base64 PNG files to PDF?

Thanks


Solution

  • I was able to solve the problem using node-canvas

    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, 0, 0, img.width, img.height);
      const base64image = canvas.toBuffer();
      
      // write the file to a pdf file
      fs.writeFile('simple.pdf', base64image, function(err) {
          console.log('File created');
      });
    });
    

    for more info: https://www.npmjs.com/package/canvas

    Note: solution works not only for png but any image type.

    Then use any pdf library to merge the pdfs like hummus