简体   繁体   English

如何使用PDFBox将标准字体嵌入到生成的PDF中

[英]How to embed an standard font into generated PDF with PDFBox

I need to add some text to PDF/A files using the Apache PDFBox library for Java. 我需要使用适用于Java的Apache PDFBox库向PDF / A文件中添加一些文本。 The problem is that, because it needs to be a valid PDF/A file, all the used fonts must be embedded in it. 问题在于,因为它必须是有效的PDF / A文件,所以所有使用的字体都必须嵌入其中。 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. 我知道我可以使用PDFBox嵌入TTF字体,但是我想避免在应用程序中提供字体文件,所以我想知道是否有一种方法可以在PDFBox中嵌入一种可用的标准字体,就好像它是外部的。

For example, when I write something using one of the standard fonts, the PDF validator complains about this: 例如,当我使用一种标准字体写东西时,PDF验证器会抱怨:

在此处输入图片说明

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? 设置字体时是否有任何选项可以强制嵌入字体?

Thanks in advance, 提前致谢,

There is only one font embedded in PDFBox. PDFBox中仅嵌入一种字体。 You can use it this way: 您可以通过以下方式使用它:

PDFont font = PDType0Font.load(doc, SomePdfboxClass.class.getResourceAsStream(
                   "/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM