I need to apply the wordSpacing (Tw)
to the PDF, but it doesn’t work because the PDFBox library encodes the text and the U+0020
symbol does not appear in the PDF.
How can we avoid this behavior and apply the wordSpacing
parameter via PDFBox library?
my code:
try (PDPageContentStream stream = new PDPageContentStream(
pdf,
page,
PDPageContentStream.AppendMode.APPEND,
false,
true)
) {
stream.saveGraphicsState();
stream.setFont(font, fontSize);
stream.setNonStrokingColor(color);
stream.beginText();
stream.newLineAtOffset(100, 100);
stream.setWordSpacing(50);
stream.showText("HELLO WORLD");
stream.endText();
stream.restoreGraphicsState();
}
how it looks in the PDF
BT
78.3975 777.75494 Td
50 Tw
(00+00(00/00/002000300:00200500/00') Tj
ET
3
The issue arises because the stream.showText() method in the PDFBox library automatically applies encoding to the text. This encoding replaces the standard space character (U+0020) with encoded glyphs. Since wordSpacing (Tw) only affects the spacing of the actual U+0020 space character, it has no effect when encoded glyphs are used.
To address this and properly apply wordSpacing, you can manually split the text at spaces and insert them into the content stream separately. This allows the wordSpacing parameter to function as intended.
Here is the corrected version of your code:`try (PDPageContentStream stream = new PDPageContentStream(
pdf,
page,
PDPageContentStream.AppendMode.APPEND,
false,
true)) {
stream.saveGraphicsState();
stream.setFont(font, fontSize);
stream.setNonStrokingColor(color);
stream.beginText();
stream.newLineAtOffset(100, 100);
stream.setWordSpacing(50);
// Split text at spaces and write each part with spacing applied
String text = "HELLO WORLD";
String[] words = text.split(" ");
for (int i = 0; i < words.length; i++) {
stream.showText(words[i]); // Add the word
if (i < words.length - 1) {
stream.showText(" "); // Add a space to let wordSpacing apply
}
}
stream.endText();
stream.restoreGraphicsState();
}
`
Amit Kadlag is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1