使用 PDFBOX 剪辑图像

Clip an image with PDFBOX

在 PDFBOX 中,我需要渲染带有背景图像的多边形或使用我的多边形裁剪图像,如屏幕截图示例中所示。

我正在尝试了解 PDContentStream.clip() 或 PDContentStream.shadingfill() 的工作原理,但这对我来说并不清楚。

示例:在 JavaFX 中用多边形裁剪图像

您不需要 PDContentStream.shadingfill() 完成此任务。

你只需要

  • 定义剪辑路径
  • 剪辑(和笔触以像您的示例一样沿着剪辑区域画一条线)
  • 绘制图像。

只有一个问题:PDFBox PDContentStream.clip() 方法的实现者显然认为剪辑和描边(或填充)路径的选项是不必要的,剪辑后立即删除了路径定义:

public void clip() throws IOException
{
    if (inTextMode)
    {
        throw new IllegalStateException("Error: clip is not allowed within a text block.");
    }
    writeOperator("W");

    // end path without filling or stroking
    writeOperator("n");
}

因此,如果您确实想使用相同的路径定义进行裁剪和描边,则需要绕过 PDFBox clip 方法。

所以,你可以这样进行

PDDocument doc = new PDDocument();
PDImageXObject pdImage = ...;

int w = pdImage.getWidth();
int h = pdImage.getHeight();

PDPage page = new PDPage();
doc.addPage(page);
PDRectangle cropBox = page.getCropBox();
PDPageContentStream contentStream = new PDPageContentStream(doc, page);

contentStream.setStrokingColor(25, 200, 25);
contentStream.setLineWidth(4);
contentStream.moveTo(cropBox.getLowerLeftX(), cropBox.getLowerLeftY() + h/2);
contentStream.lineTo(cropBox.getLowerLeftX() + w/3, cropBox.getLowerLeftY() + 2*h/3);
contentStream.lineTo(cropBox.getLowerLeftX() + w, cropBox.getLowerLeftY() + h/2);
contentStream.lineTo(cropBox.getLowerLeftX() + w/3, cropBox.getLowerLeftY() + h/3);
contentStream.closePath();
//contentStream.clip();
contentStream.appendRawCommands("W ");
contentStream.stroke();

contentStream.drawImage(pdImage, cropBox.getLowerLeftX(), cropBox.getLowerLeftY(), w, h);

contentStream.close();

doc.save(new File(RESULT_FOLDER, "image-clipped.pdf"));
doc.close();

(AddImage 测试 testImageAddClipped)

我的示例图片结果为