1

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?

2 Answers 2

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.