使用pdfkit nodejs在pdf中插入图像

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

我真的很感谢这方面的帮助。 我正在尝试将图像添加到我使用 PDFKIT 生成的 pdf 中。我尝试显示的图像来自“profilepicture.picture”,它是一个 URL。我无法将该参数直接传递给 doc.image() 因为它只读取本地保存的图片。

PDFKIT 文档说 “将图像添加到 PDFKit 文档是一项简单的任务。只需将带有 Base64 编码数据的图像路径、缓冲区或数据 uri 以及一些可选参数传递给图像方法即可。PDFKit 支持 JPEG 和 PNG 格式。”

所以我尝试了 AXIOS 和其他方法将图像切换为 base64,但仍然在尝试显示图像时,base64 仍然无法工作...如果我添加本地的图像,那么它可以工作,但不能使用 base64 或来自 profilepicture.picture 的 url。 URL 为 ('https://ibookinfo.s3.amazonaws.com/ibookprofilepicture1694446561681.png')。我不知道还能做什么。请帮忙。这是我的代码。




import PDFDocument from 'pdfkit';
import { promises as fsPromises } from 'fs';
import fs from 'fs'
import axios from 'axios'


function createPDFInvoice(invoice, shipping, secondTotal, infofacturacion, profilepicture,         randomPart, agregarnota, callback) {
let doc = new PDFDocument({ size: "A4", margin: 50 });

generateHeader(doc, infofacturacion, profilepicture);
generateCustomerInformation(doc, invoice, shipping, secondTotal, randomPart);
generateInvoiceTable(doc, invoice, secondTotal);
generateFooter(doc, agregarnota, infofacturacion);

const pdfPath = `invoice_${Date.now()}.pdf`;
    const stream = fs.createWriteStream(pdfPath);
    doc.end();

doc.pipe(stream);

stream.on('finish', () => {
        if (typeof callback === 'function') {
            callback(null, pdfPath); // Notify that the PDF creation is complete
        } else {
            console.error('Callback is not a function');
        }
    });
stream.on('error', (err) => {
        if (typeof callback === 'function') {
            callback(err); // Handle any errors during PDF creation
        } else {
            console.error('Callback is not a function');
        }
    });
}
async function convertImageToBase64(picture) {
  try {
      const imageResponse = await axios.get(picture, { responseType: 'arraybuffer' });
      const imageBuffer = Buffer.from(imageResponse.data);
      return imageBuffer.toString('base64');
  } catch (error) {
      console.error('Error fetching image from URL:', error);
      return null; 
  }
}
async function generateHeader(doc, infofacturacion, profilepicture) {
    const base64Image = await convertImageToBase64(profilepicture.picture);

doc.fillColor('#444444')
        .image(`data:image/png;base64,${base64Image}`, 50, 45, { width: 50 })
        .fontSize(15)
        .text(`${infofacturacion.nombreempresa}`, 200, 60, { align: 'right' })
        .fontSize(10)
        .text(` ${infofacturacion.tipodenegocio}`, 200, 85, { align: 'right' })
        .text(`Cédula Jurídica:  ${infofacturacion.cedulajuridica}`, 200, 98, { align: 'right' })
        .text(` ${infofacturacion.nombreencargado}`, 200, 111, { align: 'right' })
        .text(`${infofacturacion.correoempresa} /  ${infofacturacion.telefonoempresa}`, 200, 124, {   align: 'right' })
        .text(`${infofacturacion.direccionempresa}, ${infofacturacion.paisempresa}`, 200, 137, { align: 'right' })
        .moveDown();
        }


javascript node.js pdfkit
1个回答
0
投票

我认为这是真的

// Scale proprotionally to the specified width
doc.image('images/test.jpeg', 0, 15, {width: 300})
   .text('Proportional to width', 0, 0);

// Fit the image within the dimensions
doc.image('images/test.jpeg', 320, 15, {fit: [100, 100]})
   .rect(320, 15, 100, 100)
   .stroke()
   .text('Fit', 320, 0);

// Stretch the image
doc.image('images/test.jpeg', 320, 145, {width: 200, height: 100})
   .text('Stretch', 320, 130);

// Scale the image
doc.image('images/test.jpeg', 320, 280, {scale: 0.25})
   .text('Scale', 320, 265);

// Fit the image in the dimensions, and center it both horizontally and vertically
doc.image('images/test.jpeg', 430, 15, {fit: [100, 100], align: 'center', valign: 'center'})
   .rect(430, 15, 100, 100).stroke()
   .text('Centered', 430, 0);

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