Apache PDFBox Add Embedded Font to PDF Document
This tutorial demonstrates how to add an embedded font to a PDF document using Apache PDFBox.
Maven Dependencies
We use Apache Maven to manage our project dependencies. Make sure the following dependencies reside on the class-path.
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.8</version>
</dependency>
Apache PDFBox Add Embedded Font to PDF Document
We downloaded the Star Wars Font and placed it in the src/main/resources/
folder. Next, create a PDType0Font
font by loading the font via PDType0Font.load();
method. Finally, you can use the font in your PDF document.
package com.memorynotfound.pdf.pdfbox;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class AddEmbeddedFonts {
public static void main(String[] args) throws Exception{
try (final PDDocument doc = new PDDocument()){
PDPage page = new PDPage(PDRectangle.A4);
doc.addPage(page);
InputStream starWarsFontStream = AddEmbeddedFonts.class.getResourceAsStream("/Starjout.ttf");
PDType0Font font = PDType0Font.load(doc, starWarsFontStream, true);
PDPageContentStream stream = new PDPageContentStream(doc, page);
stream.beginText();
stream.setFont(font, 62);
stream.newLineAtOffset(100, 700);
stream.showText("Star Wars");
stream.newLine();
stream.endText();
stream.close();
doc.save(new File("/tmp/embedded-font.pdf"));
} catch (IOException e){
System.err.println("Exception while trying to create pdf document - " + e);
}
}
}
Demo
When we run the application. The embedded font is embedded in the PDF document.