如何在nodejs中使用pdfmake实现圆形图像

问题描述 投票:0回答:1

我正在使用 pdfmake 在 node.js 中生成 pdf。

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----

PDF 中的图像采用默认形状(矩形)。 我知道 pdfmake 样式中没有“border-radius”属性。但我需要坚持使用 pdfmake。 但我需要以圆形显示图像。 有没有办法使用任何 npm 包或其他方式将“imageBuffer”转换为循环缓冲区?

需要某人的宝贵帮助。

node.js npm azure-blob-storage pdfmake
1个回答
0
投票

有没有办法使用任何 npm 包或其他方式将“imageBuffer”转换为循环缓冲区?

您可以使用

canvas
模块裁剪图像,并使用
pdfmake
模块创建 PDF。

据我所知,

pdfmake
不支持开箱即用的圆形图像。但是,您可以尝试一些解决方法来实现此效果。

代码:

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

上面的代码使用已裁剪成圆形的图像生成 PDF 文档。它使用

canvas
模块裁剪图像,并使用
pdfmake
模块创建 PDF。

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.