Fel
Fel

Reputation: 4818

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. 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.

For example, when I write something using one of the standard fonts, the PDF validator complains about this:

enter image description here

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,

Upvotes: 2

Views: 4510

Answers (1)

Tilman Hausherr
Tilman Hausherr

Reputation: 18851

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"));

Upvotes: 1

Related Questions