【问题标题】:Can not convert HTML with images to PDF using iText7无法使用 iText7 将带有图像的 HTML 转换为 PDF
【发布时间】:2018-08-13 04:57:51
【问题描述】:

我正在使用 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 看起来像:

<!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>

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

PDF 文件应如下所示:

但结果没有像这样的图像:

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

【问题讨论】:

    标签: java html pdf itext


    【解决方案1】:

    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>
    

    【讨论】:

      猜你喜欢
      • 2018-04-07
      • 2018-05-06
      • 2019-01-01
      • 2015-05-05
      • 1970-01-01
      • 2019-12-08
      • 2011-02-26
      • 2023-01-13
      相关资源
      最近更新 更多