无法使用iText7将带图像的HTML转换为PDF

时间:2018-03-05 13:59:33

标签: java html pdf itext

我使用iText(版本7.1.1)使用HtmlConverter(html2pdf版本2.0.1)将html转换为pdf:

      ConverterProperties props = new ConverterProperties();

    FontProvider fp = new DefaultFontProvider(true, false, false);
    for (String font : FONTS) {
        FontProgram fontProgram = FontProgramFactory.createFont(font);
        fp.addFont(fontProgram);
    }

    props.setFontProvider(fp);

    com.itextpdf.kernel.pdf.PdfWriter writer = new com.itextpdf.kernel.pdf.PdfWriter(outputStream);
    PdfDocument pdf = new PdfDocument(writer);
    Document document = new Document(pdf);

    List<IElement> elements = HtmlConverter.convertToElements(new ByteArrayInputStream(htmlBody.getBytes(StandardCharsets.UTF_8)), props);
    for (IElement element : elements) {
        document.add((IBlockElement)element);
    }

html看起来像:

&#13;
&#13;
<!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 for Java (vers. 2009-12-01), see jtidy.sourceforge.net" />
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h2>img2 url</h2>

<div dir="ltr">hallo  
<div>my image is : </div>
<div><br />
</div>
<div><img src="https://www.w3schools.com/html/img_chania.jpg"
width="460" height="345" /><br />
<br />
salam</div>
</div>
</body>
</html>
&#13;
&#13;
&#13;

结果中的PDF根本没有图像!

PDF文件应如下所示:

enter image description here

但结果却没有像:

enter image description here

为什么url图像也在inLine图像中从pdf文件中消失?

1 个答案:

答案 0 :(得分:0)

itext7支持base64图像。您可以这样做:itext7 example

<html>
    <head><title>Test</title></head>
    <body>
        <h1>Test</h1>
        <p>Hello World</p>
        <img alt="Embedded Image" src="data:image/png;base64,iVBORw0...ErkJggg==" />
    </body>
</html>