how to achieve circular shape image using pdfmake in nodejs

178 Views Asked by At

I am using pdfmake to generate pdf's in node.js.

const imageBuffer = await imageToBase64('image path'); //image from azure blob storage
const pdfData = {
    content: [
        {
          image: `data:image/jpeg;base64,${imageBuffer}`,
          width: 100,
          height: 100,
        }
    ]
};

----rest of the pdf logic goes here----

Image is coming in default shape (rectangle) in the pdf. I know that there is no 'border-radius' property in pdfmake styles. But I need to stick with pdfmake. But I need to show the image in a round (circular) shape. Is there any way to convert the "imageBuffer" into circular one using any npm package or someother way?

Need someone's valuable help.

1

There are 1 best solutions below

1
Venkatesan On

Is there any way to convert the "imageBuffer" into a circular one using any npm package or some other way?

You can use the canvas module to crop the image and the pdfmake module to create the PDF.

AFAIK, the pdfmake does not support rounded images out of the box. However, there are a few workarounds you can try to achieve this effect.

Code:

const fs = require('fs');
const pdfMake = require('pdfmake');
const { createCanvas, loadImage } = require('canvas');

async function processImage(image_url) {
  const img = await loadImage(image_url);
  const canvas = createCanvas(img.width, img.height);
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);

  ctx.fillStyle = 'black';
  ctx.globalCompositeOperation = 'destination-in';
  ctx.beginPath();
  ctx.arc(canvas.width / 2, canvas.height / 2, canvas.width / 2, 0, 2 * Math.PI);
  ctx.fill();
  const buffer = canvas.toBuffer('image/png');
  return buffer.toString('base64');
}

async function generatePDF() {
  const image_url = "your-storage-account-blob-url";
  const imageBuffer = await processImage(image_url);
  const fonts = {
  Roboto: {
    normal: 'path/to/Roboto-Regular.ttf',
    bold: 'path/to/Roboto-Bold.ttf',
    italics: 'path/to/Roboto-Italic.ttf',
    bolditalics: 'path/to/Roboto-BoldItalic.ttf'
  }
};
const docDefinition = {
    content: [
      {
        image: `data:image/png;base64,${imageBuffer}`,
        width: 100,
        height: 100,
      },
    ],
    defaultStyle: {
    font: 'Roboto'
  },
  fonts: fonts
};

// Create a PDF document
const printer = new pdfMake();
const pdfDoc = printer.createPdfKitDocument(docDefinition);

// Save the PDF document to a local file
pdfDoc.pipe(fs.createWriteStream('sample.pdf'));
pdfDoc.end();
}

generatePDF(); 

The above code generates a PDF document using an image that has been cropped into a circle shape. It uses the canvas module to crop the image and the pdfmake module to create the PDF.

Output:

enter image description here