如何在 Apache PDFBox 中渲染彩色文本

stu*_*fel 3 java pdf text pdfbox

是的,这似乎是一个奇怪的问题,但我无法在 PDFBox 中渲染彩色文本。

通常生成文本的代码如下所示:

//create some document and page...
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);

//defined some font
PDFont helveticaRegular = PDType1Font.HELVETICA;

//content stream for writing the text
PDPageContentStream contentStream = new PDPageContentStream(document, page);

contentStream.beginText();
contentStream.setFont(helveticaRegular, 16);
contentStream.setStrokingColor(1f,0.5f,0.2f);
contentStream.newLineAtOffset(64, page.getMediaBox().getUpperRightY() - 64);
contentStream.showText("The hopefully colored text");
contentStream.endText();

//closing the stream
contentStream.close();

[...] //code for saving and closing the document. Nothing special
Run Code Online (Sandbox Code Playgroud)

有趣的是,这setStrokingColor是接受流上颜色的唯一方法。所以我认为这就是在 PDFBox 中给某些东西着色的方法。

但是:我没有给文本添加任何颜色。所以我想这是其他类型内容的一种方法。

有人知道如何在 PDFBox 中实现彩色文本吗?

mkl*_*mkl 9

你用

contentStream.setStrokingColor(1f,0.5f,0.2f);
Run Code Online (Sandbox Code Playgroud)

但在 PDF 中,文本默认不是通过描边路径绘制的,而是通过填充路径绘制的。因此,你应该尝试

contentStream.setNonStrokingColor(1f,0.5f,0.2f);
Run Code Online (Sandbox Code Playgroud)

反而。