How to convert a base64 png to pdf using nodejs?

3.7k Views Asked by At

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

Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

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

3
On

I think you are looking for this.

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');
});