I am using PDFBox to build a document from an existing PDF template, so it opens the file, adds text to it, and saves it. It works well, except when trying to use external TTF fonts. I have tried different things and searched for 2 days for solutions, but there's not much out there on PDFBox.
Here's some code, using the font "Tardy Kid" because it can't be mistaken for anything else, and is not likely to be part of any standard library .
The code executes fine, displays "TardyKid" from the println (showing that the font is loaded and the name is gettable), and displays the text -- but it's in Helvetica. More sophisticated parts of the code that use getStringWidth()
to calculate width seem to indicate successful loading of the width tables too. It just doesn't display correctly.
The code runs in the context of a larger program that opens an existing PDF document (a template) and adds text to it. It all seems to work fine except for
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();
}
}
}