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)