Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render part of a PDF file as an image using PDFBox?

PDFBox offer functions to render a entire page, but no way to render only a specific rectangle of the page.

This code is working for me. But as mentioned above it renders the whole page and I need a method to render a little area of the pdf file:

    File file = new File("package.pdf"); 
    PDDocument document = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(document);
    BufferedImage image = renderer.renderImageWithDPI(0, 400);
    ImageIO.write(image, "PNG", new File("C:/package1.png"));
    document.close();

I would be very happy about a solution, since I have not found a solution for hours

like image 894
Fatih Gee Avatar asked Oct 29 '25 13:10

Fatih Gee


1 Answers

I have found a soulution by myself. CropBox was the deciding keyword i did not know about.

    File file = new File("package.pdf"); 
    PDDocument document = PDDocument.load(file);
    PDPage page = document.getPage(0);
    page.setCropBox(new PDRectangle(133f, 150f, 100f, 100f)); // Here you draw a rectangle around the area you want to specify
    PDFRenderer renderer = new PDFRenderer(document);
    BufferedImage image = renderer.renderImageWithDPI(0, 400);
    ImageIO.write(image, "PNG", new File("C:/fatihabi.png"));
    document.close();
like image 178
Fatih Gee Avatar answered Nov 01 '25 04:11

Fatih Gee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!