Luiz Jr
Luiz Jr

Reputation: 61

Convert Image Buffer to PDF Buffer on NodeJs

Im working with playwright and i get the image from screenshot:

const image = await elementHandle.screenshot({ 
      fullPage : true,
      clip: {
        width: 1200,
        height: 1500,
      }
    });

It returns me the buffer of an image. So i need to convert the image buffer to pdf buffer.

Already used some plugins but it saves the pdf, and i need just the buffer of it (without saving it).

Like this plugin:

 const pages = [
      image
   ]
imgToPDF(pages, 'A4').pipe(fs.createWriteStream('temp.pdf'));

Any ideas?

Upvotes: 0

Views: 1920

Answers (2)

youllbehaunted
youllbehaunted

Reputation: 649

This should work!

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const { Blob } = require('buffer');
const { jsPDF } = require('jspdf'); // will automatically load the node version

//A BLANK IMAGE
const getBuffer = async () => {
    //insert some image url here
  const response = await axios.get('https://i.ibb.co/K92Pbs0/duck.jpg', { responseType: 'arraybuffer' });
  const buffer = Buffer.from(response.data, 'utf-8');
  return buffer;
};

const requestNCReviewPhotoUpload = async () => {
  const file = {
    buffer: await getBuffer(),
    size: 638,
    fieldname: 'files',
    originalname: 'small.png',
    encoding: '7bit',
    mimetype: 'image/png',
  };

  const base64 = file.buffer.toString('base64');
  const doc = new jsPDF();
  doc.addImage(base64, 'PNG', 15, 30, 180, 180);

  const pdfBuffer = Buffer.from(doc.output('arraybuffer'), 'base64');

  console.log('pdf buffer hurray 😎', pdfBuffer)

 
};
requestNCReviewPhotoUpload();

Upvotes: 1

Sergei Reutov
Sergei Reutov

Reputation: 26

I've made it with help of the 'canvas' package: https://www.npmjs.com/package/canvas

import Canvas from 'canvas';

function imageToPdf(imageBuffer) {
  const img = new Canvas.Image();
  img.src = imageBuffer;
  const canvas = Canvas.createCanvas(img.width, img.height, 'pdf');
  const context = canvas.getContext('2d');
  context.drawImage(img, 0, 0, img.width, img.height);
  return canvas.toBuffer();
}

Upvotes: 1

Related Questions