Reputation: 1973
Is there a way to convert multiple base64 PNG files to PDF?
Thanks
Upvotes: 2
Views: 4211
Reputation: 1973
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
Upvotes: 1
Reputation: 716
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');
});
Upvotes: -1