Search code examples
javapdfjava-8pdfbox

Overlaying PDF on all Pages at specific location on all Pages using PDFBox 2.X


I'm trying to overlay a PDF on-top of all pages in a PDF, at the top left hand side of each page. The PDFs that will be of different sizes. The PDF overlay is a constant size, which is smaller than all the pages of the PDF.

I can only seem to get PDFBox to put the overlay in the middle of the PDFs.

I would prefer not to convert the PDF overlay to a bitmap (PDImageXObject) and insert it onto the pages. Here is some rough code which I'm playing about with:-

public static void main(String[] args) throws Exception {
    String overlayPath = "C:\\OverlayPdf.pdf";
    String overlayOnMePath = "C:\\ToBeOverlayedOn.pdf";       
    PDDocument overlayOnMe = PDDocument.load(new File(overlayOnMePath)); //Document to write to.
    overlayPath = overlayPath + "Anno.pdf";

    HashMap<Integer, String> overlayGuide = new HashMap<>();
    for (int i = 0; i < overlayOnMe.getNumberOfPages(); i++) {
        overlayGuide.put(i + 1, overlayPath);
    }
    Overlay overlay = new Overlay();
    overlay.setInputPDF(overlayOnMe);
    overlay.setOverlayPosition(Overlay.Position.FOREGROUND);
    overlay.overlay(overlayGuide);

    overlayOnMe.save(new File(overlayOnMePath + "_OVERLAYED.pdf"));
    overlay.close();
}

My gut feeling is its an affine transformation but I couldn't get that working either.


Solution

  • I have created a new issue and it allows to pass a transform, this will be in version 2.0.10 or higher. This will be done in calculateAffineTransform by extending the overlay class. To put the stamp on the top left, the new method would look like this:

    protected AffineTransform calculateAffineTransform(PDPage page, PDRectangle overlayMediaBox)
    {
        AffineTransform at = new AffineTransform();
        PDRectangle pageMediaBox = page.getMediaBox();
        at.translate(0, pageMediaBox.getHeight() - overlayMediaBox.getHeight());
        return at;
    }