gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:01:18 30 4
gpt4 key购买 nike

我使用 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 文件应如下所示:

enter image description here

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

enter image description here

为什么 url 图片也内联图片从 pdf 文件中消失了?

最佳答案

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>

关于java - 无法使用 iText7 将带有图像的 HTML 转换为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49112130/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com