Flip PDF with pdfbox

I've been trying to figure out how to flip a pdf for a while, but haven't figured out yet. I've only found how to flip image using Graphics2D:

// Flip the image vertically
AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
tx.translate(0, -image.getHeight(null));
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = op.filter(image, null);

Could you please help me to get it with PDFbox?

Thanks!!

1 answer

  • answered 2018-07-12 07:49 Tilman Hausherr

    With PDFBox 2.*, you need to prepend it to the page content stream. Optionally save and restore graphics state, useful for further modifications. (All based on this answer)

    PDPage page = doc.getPage(0);
    try (PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.PREPEND, true))
    {
        cs.saveGraphicsState();
        cs.transform(Matrix.getScaleInstance(1, -1));
        cs.transform(Matrix.getTranslateInstance(0, -page.getCropBox().getHeight()));
        cs.saveGraphicsState();
    }
    try (PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true))
    {
        cs.restoreGraphicsState();
        cs.restoreGraphicsState();
    }