使用 PDFBox 裁剪页面并用白色填充矩形外部

Crop page with PDFBox and fill outside of rectangle with white

我正在开发一个自定义工具并使用此代码裁剪页面。

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();

我在工具里trim是这样的

但是当我打开 pdf 时它看起来不一样,我希望它看起来像第一张图片一样居中并且有边缘

第二张图片正确。裁剪框定义页面 canvas 上查看器应显示的框。如果您希望保留可见页面尺寸,请保持裁剪框不变,并用白色填充除内部矩形以外的所有区域。

例如像这样:

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)


在您提问的评论中

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

是的,相应地调整裁剪框:

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)