I use PDFBox to create a document from an existing PDF template, so it opens the file, adds text to it and saves it. It works well, except when using external TTF fonts. I tried different things and looked for 2 days for solutions, but there are not many on PDFBox there.
Here is some code using the "Tardy Kid" font, because it cannot be mistaken for anything else, and it is unlikely to be part of any standard library.
The code executes perfectly, displays the "TardyKid" from println (indicating that the font is loaded and the name succeeds), and displays the text - but this is in Helvetica. The more complex parts of the code that use getStringWidth() to calculate the width also indicate that the width tables have loaded successfully. It just does not display correctly.
The code runs in the context of a larger program that opens an existing PDF document (template) and adds text to it. Everything seems to work fine except
public void setText ( PDDocument document, String text ) throws IOException { int lastPage = document.getNumberOfPages() - 1; PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(lastPage); PDPageContentStream contentStream = null; try { contentStream = new PDPageContentStream(document,page,true,true,false); File fontFile = new File(m_fontDir, "Tardy_Kid.ttf"); PDFont font = PDTrueTypeFont.loadTTF(document, fontFile); Color color = new Color(196, 18, 47); float x = 100f, y = 700f; System.out.println(font.getBaseFont()); contentStream.setFont(font, 32); contentStream.setNonStrokingColor(color); contentStream.beginText(); contentStream.moveTextPositionByAmount(x,y); contentStream.drawString(text); contentStream.endText(); } finally { if (contentStream != null) { contentStream.close(); } } }
source share