【发布时间】:2018-04-28 07:29:01
【问题描述】:
我想在我的 java 代码中使用 itext 将 html 转换为 pdf,但似乎 strong 标记和 em 标记不起作用。我尝试搜索网络中的解决方案并跟踪我的代码以找出原因,但失败了。下面是我的 java 代码、我的 html 文件和生成的 pdf 快照。
public static boolean html2pdf(String htmlContent, String path) {
try (FileOutputStream fos = new FileOutputStream(path);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(htmlContent.getBytes())) {
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, fos);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, byteArrayInputStream,
Charset.forName("UTF-8"), new MyFontProvider());
document.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
static class MyFontProvider extends XMLWorkerFontProvider {
@Override
public Font getFont(String fontname, String encoding, float size, int style) {
Font cnFont = null;
try {
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
cnFont = new Font(baseFont);
} catch (Exception e) {
e.printStackTrace();
}
if (cnFont == null) {
cnFont = super.getFont(fontname, encoding, size, style);
}
return cnFont;
}
}
和我的依赖:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<p >
<strong>overstrike</strong>
</p>
<p>
<em>incline</em>
</p>
</body>
</html>
已解决
我通过使用 itext7 解决了这个问题。
【问题讨论】:
-
您为什么使用旧 iText 版本的 维护 版本而不是最新版本?我倾向于将这个问题作为stackoverflow.com/questions/47895935 的副本来结束