简体   繁体   English

在 PDFBox 中设置文本颜色

[英]Setting text color in PDFBox

I am trying to add a text line to a PDF page using PDFBox.我正在尝试使用 PDFBox 向 PDF 页面添加文本行。 I am using the following code我正在使用以下代码

PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, false);
cs.beginText();
cs.setFont(font, fontSize);
cs.newLineAtOffset(posX, posY);
cs.showText(text);
cs.endText();
cs.close();

This works fine on most documents, but I am having a problem with a specific document where the text is being displayed as white(not really sure why is the text being rendered that way) and is not visible due to the page background itself being white, so what I want to do ideally is to set a fixed black colour for this text.这在大多数文档上都可以正常工作,但是我遇到了一个特定文档的问题,其中文本显示为白色(不确定为什么以这种方式呈现文本)并且由于页面背景本身是白色而不可见,所以我想要做的理想是为这个文本设置一个固定的黑色。 How can it be done?怎么做到呢?

As was pointed out by Tilman Hausherr and others in the comments, the issue was with opening a stream in append mode and not setting the resetContext parameter to true can lead to numerous issues with text being rendered, so using正如Tilman Hausherr和其他人在评论中指出的那样,问题在于以追加模式打开流而不将 resetContext 参数设置为 true 会导致呈现文本的许多问题,因此使用

PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, false, true)

instead of代替

PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, false)

solves the issue of text not being rendered properly.解决了无法正确呈现文本的问题。 In addition, if you want to set a custom colour for the text, you need to call另外,如果要为文本设置自定义颜色,则需要调用

cs.setNonStrokingColor(r, g, b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM