Search code examples
csspdffontsflying-saucer

Flying saucer does not load font from googleapis font css in PDF


I don't want to download fonts in my project directory.

For the website I'm loading fonts from googleapis, which works all good.

Now, when I generate PDF, I added the font-face in style and it's not loading them.

Here is my code:

@font-face {
  font-family: 'Hind Siliguri';
  src: url(https://fonts.gstatic.com/s/hindsiliguri/v4/ijwTs5juQtsyLLR5jN4cxBEoTI7ax8s3JimW3w.woff2);
  -fs-pdf-font-embed: embed;
  -fs-pdf-font-encoding: Identity-H;
}

My first question: Is flying saucer supports just .ttf format fonts?

How can I manage the css with my current fonts?

Does it require to add fontResolver.addFont() in JAVA code?

TIA!


Solution

  • Flying saucer is based on an obsolete version of iText (actually, a version that should no longer be used in commercial applications). It goes without saying that the authors of iText don't endorse Flying Saucer.

    The old version of iText used by Flying Saucer doesn't support Web Open Font Format (WOFF) fonts. Support for such fonts was only introduced in iText 7. iText 7 comes with an add-on called pdfHTML that can be used to convert HTML to PDF; see the HTML to PDF tutorial for more info. If you go to chapter 6 of this tutorial, you will find some examples involving WOFF fonts.

    For instance, if you have this in your CSS file:

    @font-face {
        font-family: "SourceSerifPro-Regular";
        src: url("fonts/SourceSerifPro-Regular.otf.woff") format("woff");
    }
    .regular {
        font-family: "SourceSerifPro-Regular";
    }
    

    You can have the following HTML:

    <td class="regular">quick brown fox jumps over the lazy dog</td>
    

    It's then just a matter of using this code:

    public void createPdf(String src, String dest) throws IOException {
        HtmlConverter.convertToPdf(new File(src), new File(dest));
    }
    

    And the proper fonts will be downloaded. Please take into account that your HTML to PDF conversion process risks being slow when using this approach. The fonts are downloaded over a network, and that typically slows things down.