如何使用 PDFBox 将标准字体嵌入到生成的 PDF 中 [英] How to embed an standard font into generated PDF with PDFBox
问题描述
我需要使用 Java 的 Apache PDFBox 库向 PDF/A 文件添加一些文本.问题是,因为它需要是一个有效的 PDF/A 文件,所以必须将所有使用的字体嵌入其中.我知道我可以使用 PDFBox 嵌入 TTF 字体,但我想避免必须为应用程序提供字体文件,所以我想知道是否有办法嵌入 PDFBox 中可用的标准字体之一,就好像它一样是外部的.
I need to add some text to PDF/A files using the Apache PDFBox library for Java. The problem is that, because it needs to be a valid PDF/A file, all the used fonts must be embedded in it. I know that I can embed a TTF font using PDFBox, but I'd like to avoid having to provide a font file with the application, so I was wondering if there's a way to embed one of the standard fonts available in PDFBox as if it was external.
例如,当我使用其中一种标准字体编写内容时,PDF 验证器会抱怨:
For example, when I write something using one of the standard fonts, the PDF validator complains about this:
我使用以下代码编写文本:
I've used the following code to write the text:
PDFont standardFont = PDType1Font.HELVETICA_BOLD;
PDPage pag = new PDPage();
pag.setResources(new PDResources());
PDPageContentStream contentStream = new PDPageContentStream(pdfFile, pag);
//Begin the Content stream
contentStream.beginText();
//Setting the font to the Content stream
contentStream.setFont(standardFont, 12);
//Setting the position for the line
contentStream.newLineAtOffset(25, 500);
//Adding text in the form of string
contentStream.showText("JUST A SAMPLE STRING");
//Ending the content stream
contentStream.endText();
//Closing the content stream
contentStream.close();
pdfFile.addPage(pag);
pdfFile.save(file);
pdfFile.close();
设置时是否有强制嵌入字体的选项?
Is there any option to force the embed of the font when setting it?
提前致谢,
推荐答案
PDFBox 中只嵌入了一种字体.你可以这样使用它:
There is only one font embedded in PDFBox. You can use it this way:
PDFont font = PDType0Font.load(doc, SomePdfboxClass.class.getResourceAsStream(
"/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"));
这篇关于如何使用 PDFBox 将标准字体嵌入到生成的 PDF 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!