Home > OS >  Setting text color in PDFBox
Setting text color in PDFBox

Time:11-18

I am trying to add a text line to a PDF page using PDFBox. 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?

CodePudding user response:

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

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);
  • Related