第二张图是正确的。裁剪框定义了页面画布上查看者应显示的框。如果您希望保留可见的页面尺寸,请保持裁剪框不变,并将除内部矩形之外的所有内容都填充为白色。
例如像这样:
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 测试testTrimCengage1)
在你问的评论中
你能把剪下的部分放在页面中间吗?
是的,通过相应地调整裁剪框:
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 测试testTrimAndCenterCengage1)
使用这个辅助方法:
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 辅助方法centerBoxAroundBox)