Adding fonts to Apache Pdfbox?

K.Niemczyk picture K.Niemczyk · Apr 16, 2014 · Viewed 16.2k times · Source

Is there a way to add additional font styles into Apache Pdfbox?

We're currently trying to work around printing PDFs in our system (currently being done with PDF-Renderer.) I have been looking at various alternatives (pdfbox, jpedal, jPDFPrint)

Our hope is for a free GPL compatible library to use, and as such we're leaning towards pdfbox. I have been able to write some sample code to print out the pdf which 'works'. See below:

PDDocument doc;
try {
        doc = PDDocument.load("test.pdf");
        doc.print();
    } catch (Exception e) {
        // Come up with better thing to do on fail.
        e.printStackTrace();
    }

As I mentioned, this works but the problem I'm running into is that PdfBox doesn't seem to be recognizing the fonts used in the pdf, and as such changes the font being used. As a result the document looks very odd (spacing and character size are different and look bizarre). I routinely see the following log message, or things like it:

Apr 16, 2014 2:56:21 PM org.apache.pdfbox.pdmodel.font.PDSimpleFont drawString WARNING: Changing font on < > from < NimbusMono > to the default font

Does anyone know of a way (or a reference) on how to approach adding a new fonttype into pdfbox? Or barring that, how to change the default font type?

From what I can tell, pdfbox supports 14 standard fonts. Unfortunately NimbusMono is not one of them. Any guidance would be appreciated.

Answer

Tilman Hausherr picture Tilman Hausherr · Apr 17, 2014

The unreleased 2.0 version supports the rendering of embedded fonts. You can get it as a snapshot https://repository.apache.org/content/groups/snapshots/org/apache/pdfbox/ or through "svn checkout http://svn.apache.org/repos/asf/pdfbox/trunk/". The API is slightly different from the 1.8.x versions and might change, the best is to look at the code examples. A quick test to see whether your file will be rendered properly is to download the "pdfbox-app" https://repository.apache.org/content/groups/snapshots/org/apache/pdfbox/pdfbox-app/2.0.0-SNAPSHOT/ and then run the viewer: java -jar pdfbox-app-2.0.0-20140416.173452-273.jar PDFReader your-file-name.pdf There's also a print feature.

Good luck!

Update 2016: 2.0 release is out, download it here. If you have used the 1.8 version, read the migration guide.