【问题标题】:java:convert HTML to PDF failed to process <strong> and <em> whth itextjava:convert HTML to PDF failed to process <strong> and <em> whth itext
【发布时间】: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 解决了这个问题。

【问题讨论】:

标签: java html itext


【解决方案1】:

MyFontProvider 中,如果第一次尝试加载字体成功(可能成功),则忽略style 参数。

【讨论】:

  • 谢谢,但我想根据html文件选择样式,而不是为pdf文件设置默认样式。
  • 是的,如果你使用 style 参数,那就是你要做的。抱歉,我不是 iText 方面的专家,所以我不知道该怎么做。
  • 亚洲字体系列通常由单一常规字体组成,没有粗体、斜体或粗斜体字体。如果您需要西方字体系列,您可以提供不同的字体(例如 Arial、Arial Bold、Arial Italic 等)以适应不同的风格。对于亚洲字体,iText 需要模仿粗体和斜体。我认为你需要 iText 7 来做到这一点。
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 2022-06-15
  • 2017-08-02
  • 2012-01-12
  • 2017-09-13
  • 2015-07-17
  • 2021-07-06
  • 2016-04-19
相关资源
最近更新 更多