我们的客户希望将图像插入到现有 PDF 的末尾。 我想检测 PDF 文件底部的空白矩形区域(最好具有一定大小)。 我想在该区域插入图像,例如公司徽标等。 如何在 Javascript 中完成现有 PDF 末尾矩形区域的识别?
使用 Node.js 和 pdf-lib 库,您可以将图片添加到 PDF 的最后一页。此示例跳过在页面底部查找空白区域的步骤。
首先确保您安装了“pdf-lib”
npm install pdf-lib
此脚本可让您将图片添加到 PDF 最后一页的末尾。
const fs = require('fs');
const { PDFDocument } = require('pdf-lib');
async function addImageToPDF(pdfPath, imagePath, outputPath) {
// Load the existing PDF
const pdfBytes = fs.readFileSync(pdfPath);
const pdfDoc = await PDFDocument.load(pdfBytes);
// Load the image
const imageBytes = fs.readFileSync(imagePath);
const image = await pdfDoc.embedPng(imageBytes); // Use embedJpg for JPEG images
// Get the last page
const pages = pdfDoc.getPages();
const lastPage = pages[pages.length - 1];
// Image dimensions and position (adjust as needed)
const imgWidth = 100; // Set the image width
const imgHeight = 100; // Set the image height
const { width, height } = lastPage.getSize();
const xPosition = width / 2 - imgWidth / 2; // Center horizontally
const yPosition = 10; // Position from the bottom
// Add the image to the last page
lastPage.drawImage(image, {
x: xPosition,
y: yPosition,
width: imgWidth,
height: imgHeight,
});
// Save the PDF with the image added
const modifiedPdfBytes = await pdfDoc.save();
fs.writeFileSync(outputPath, modifiedPdfBytes);
}
// Usage example (replace paths with your actual file paths)
addImageToPDF('path/to/original.pdf', 'path/to/image.png', 'path/to/output.pdf');
根据需要更改 imgWidth、imgHeight 和 yPosition 的值。
为了获得更多说明,我认为此链接会对您有所帮助:- https://pdf-lib.js.org/docs/api/classes/pdfimage