Search code examples
javapdfpdf-generationpdfbox

Setting character spacing with PDFBox


I'm currently using Java and the PDFBox library to create some PDFs on the fly.

I need to be able to set the character spacing/tracking of some text but can't seem to figure it out.

It looks as there is a method to do so : http://ci.apache.org/projects/pdfbox/javadoc/index.html?org/apache/pdfbox/util/operator/SetCharSpacing.html

But I'm not quite sure how to apply this in the situation.

cs.beginText();
cs.setFont( font, fontSize );
cs.setNonStrokingColor(color);
cs.moveTextPositionByAmount(position[0], position[1]);
cs.drawString(text);
cs.endText();

Any help would be appreciated! Thanks.


Solution

  • You need to do it the hard way, because the "Tc" operator isn't supported by the PDPageContentStream class:

    cs.appendRawCommands("0.25 Tc\n");
    

    The SetCharSpacing method you mentioned is for parsing existing PDFs.

    PS: don't forget to call close after finishing writing to the content stream!

    PPS: setCharacterSpacing() is available in version 2.0.4 and higher.