Flying Saucer - html entities are not rendered

2019-08-07 10:48发布

问题:

I'm generating pdf using flying-saucer lib. But I have problem with some html entities.

I've already was searching for solution I found many tips in this forum, and in other places but still there is the problem.

I've tried this approach :

http://sdtidbits.blogspot.com/2008/11/flying-saucer-xhtml-rendering-and-local.html

but without any success

My code look like this:

os = new FileOutputStream(pdf);

ITextRenderer renderer = new ITextRenderer();
ChainingReplacedElementFactory chainingReplacedElementFactory = new ChainingReplacedElementFactory();
chainingReplacedElementFactory.addReplacedElementFactory(new B64ImgReplacedElementFactory(renderer.getSharedContext()));

renderer.getSharedContext().setReplacedElementFactory(chainingReplacedElementFactory);
renderer.setDocument(url); 
renderer.layout();
renderer.createPDF(os);

where pdf is the name of new pdf to create and url is

        File f = new File(url);
        if (f.exists()) {
            url = f.toURI().toURL().toString();
        }

my html file look like this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content="HTML Tidy, see www.w3.org" />
<style type="text/css">
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, caption, tbody, tfoot, thead, tr, th
{
    color: #444;
    font-family: Arial;
    font-size: 14px;
    line-height: 25px;
    border: none;
}

table, td {border: solid 1px #CCC;}

img {page-break-inside: avoid;}
</style>

<title></title>
</head>
<body>
<h1>Test</h1>

<p>Html etites to test</p>
<p>&#8592;</p>

<p>&larr;</p>

<p>&uarr;</p>
<p>&#8593;</p>
<p>&#8595;</p>
<p></p>

</body>
</html>

Everything works fine beside those entities. There is nothing rendered only blank spots where should by arrows. Does anyone has solution for that ?

回答1:

The issue is that the font used by iText by default doesn't support the caracters you want to print.

The solution is to embed another font which can display this character, for example DejaVu.

In the java file, declare the font to the renderer:

ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont("font/DEJAVUSANS.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

renderer.setDocument(url); 
renderer.layout();
renderer.createPDF(os);

And change the font-family declaration in the HTML:

body
{
font-family: DejaVu Sans;
}