Crop page with PDFBox and fill outside of rectangle with white

Viewed 275

i'm developing a custom tool and cutting out the pages with this code.

PDPage page = document.getPage(i-1);
PDRectangle cropBox = new PDRectangle();
cropBox.setLowerLeftX(llx);
cropBox.setLowerLeftY(lly);
cropBox.setUpperRightX(urx);
cropBox.setUpperRightY(ury);
page.setCropBox(cropBox);

PDPageContentStream contentStream = new PDPageContentStream(document,page, true, false, false);
contentStream.close();

In the tool when I trim it looks like this.

enter image description here

but when I open the pdf it looks different, I would like it to look centered and with the edges as in the first image

enter image description here

1 Answers

The second image is correct. The crop box defines the box on the page canvas which viewers shall display. If you want the visible page dimensions to remain, leave the crop box as is and fill all of it except the inner rectangle with white.

E.g. like this:

PDDocument document = ... the document to manipulate ...;
PDRectangle box = ... the rectangle to remain visible ...;

for (PDPage page : document.getPages()) {
    PDRectangle cropBox = page.getCropBox();
    try (PDPageContentStream canvas = new PDPageContentStream(document, page, AppendMode.APPEND, false, true)) {
        canvas.setNonStrokingColor(1);
        canvas.addRect(cropBox.getLowerLeftX(), cropBox.getLowerLeftY(), cropBox.getWidth(), cropBox.getHeight());
        canvas.addRect(box.getLowerLeftX(), box.getLowerLeftY(), box.getWidth(), box.getHeight());
        canvas.fillEvenOdd();
    }
}

(TrimContent test testTrimCengage1)


In a comment you asked

Could you take the trimmed piece and center it in the middle of the page?

Yes, by adapting the crop box accordingly:

for (PDPage page : document.getPages()) {
    PDRectangle cropBox = page.getCropBox();
    cropBox = centerBoxAroundBox(box, cropBox.getWidth(), cropBox.getHeight());
    try (PDPageContentStream canvas = new PDPageContentStream(document, page, AppendMode.APPEND, false, true)) {
        canvas.setNonStrokingColor(1);
        canvas.addRect(cropBox.getLowerLeftX(), cropBox.getLowerLeftY(), cropBox.getWidth(), cropBox.getHeight());
        canvas.addRect(box.getLowerLeftX(), box.getLowerLeftY(), box.getWidth(), box.getHeight());
        canvas.fillEvenOdd();
    }
    page.setMediaBox(cropBox);
    page.setCropBox(cropBox);
}

(TrimContent test testTrimAndCenterCengage1)

using this helper method:

PDRectangle centerBoxAroundBox(PDRectangle box, float width, float height) {
    float horitontalMargins = (width - box.getWidth()) / 2;
    float verticalMargins = (height - box.getHeight()) / 2;
    return new PDRectangle(box.getLowerLeftX() - horitontalMargins, box.getLowerLeftY() - verticalMargins, width, height);
}

(TrimContent helper method centerBoxAroundBox)

Related