identify a Rectangular area at the bottom of PDF files in javascript

25 Views Asked by At

Our client wants the insertion of images to the end of existing PDFs. I want to detect an empty rectangular area (preferably of a certain size) at the bottom of a PDF file. To that area I would like to insert an image such as company logo etc. How can I accomplish the identification of a rectangular area at the end of an existing PDF in Javascript ?

1

There are 1 best solutions below

0
PanduDcau On

Using Node.js and the pdf-lib library, you can add a picture to the last page of a PDF. This example skips the step of finding empty space at the bottom of the page.

First Ensure you installed 'pdf-lib'

npm install pdf-lib

This script lets you add a picture to the end of the last page of a 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');

Changing the values of imgWidth, imgHeight, and yPosition whenever your requirement.

for more clarification i think this link will helps you:- https://pdf-lib.js.org/docs/api/classes/pdfimage