Search code examples
javapdfbox

PDFBox - overlay content being rotated


I have a pdf (the backing pdf) that has a page that is rotated (rotated to landscape). I have an overlay pdf that has page with dimensions the same as the landscape page but it has no rotation. When the overlay is applied, the overlay is being rendered perpendicular to the rotated page. example showing text rendered perpendicular

I've attempted setting the rotation of the individual overlay pdf pages but it seems to have no effect.

    PDDocument baseDocument = PDDocument.load(new File("examples/test/base.pdf"));;
    PDDocument overlayDocument = PDDocument.load(new File("examples/test/overlay.pdf"));

    Iterator<PDPage> baseDocumentIterator = baseDocument.getPages().iterator();
    Iterator<PDPage> overlayIterator = overlayDocument.getPages().iterator();

    while(baseDocumentIterator.hasNext() && overlayIterator.hasNext()) {
        PDPage backing = baseDocumentIterator.next();
        PDPage foreground = overlayIterator.next();
        if(backing.getRotation()!= foreground.getRotation())
        {
            foreground.setRotation(-backing.getRotation()); //doesn't seem to do antyhing
        }
    }

    PDAcroForm acroForm = baseDocument.getDocumentCatalog().getAcroForm();
    if (acroForm != null) {
        acroForm.flatten();
    }
    Overlay overlay = new Overlay();
    overlay.setOverlayPosition(Overlay.Position.FOREGROUND);
    overlay.setInputPDF(baseDocument);
    overlay.setAllPagesOverlayPDF(overlayDocument);

    Map<Integer, String> ovmap = new HashMap<Integer, String>();
    overlay.overlay(ovmap);

    AccessPermission ap = new AccessPermission();
    ap.setCanExtractContent(false);
    ap.setCanFillInForm(false);
    ap.setCanModify(false);
    ap.setReadOnly();
    ap.setCanModifyAnnotations(false);
    StandardProtectionPolicy standardPP = new StandardProtectionPolicy("", "", ap);
    standardPP.setEncryptionKeyLength(128);
    baseDocument.protect(standardPP);
    baseDocument.save("examples/test/output.pdf");
    baseDocument.close();
    overlayDocument.close();

Sample pdfs

Is there any way to handle this case with pdfbox? Thanks


Solution

  • you are probably using a pdfbox version before 2.0.17 as in this version a bug that causes the described behavior was fixed:

    [PDFBOX-4596] - Overlays with /Rotate value appear rotated in result file
    

    with 2.0.17 and later your code generates:

    enter image description here