我正在使用PDFBox从现有的PDF模板构建文档,因此它会打开文件,向其中添加文本并保存.除了尝试使用外部TTF字体外,它运行良好.我尝试了不同的东西,并搜索了2天的解决方案,但在PDFBox上没有太多.
这是一些代码,使用字体"Tardy Kid",因为它不能被误认为是其他任何东西,并且不太可能是任何标准库的一部分.
代码执行正常,从println显示"TardyKid"(显示字体已加载且名称可获取),并显示文本 - 但它在Helvetica中.getStringWidth()用于计算宽度的代码的更复杂部分似乎也表示宽度表的成功加载.它只是没有正确显示.
代码在较大程序的上下文中运行,该程序打开现有PDF文档(模板)并向其添加文本.这一切似乎都很好,除了
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 { …Run Code Online (Sandbox Code Playgroud)