【问题标题】:Apache POI docx: HTML as an altChunkApache POI docx:HTML 作为 altChunk
【发布时间】:2021-08-06 08:43:21
【问题描述】:

早安
我想使用 Apache POI 将 HTML 作为 altChunk 添加到 DOCX 文件中。为此,我遵循了这个 stackoverflow 答案

How to add an altChunk element to a XWPFDocument using Apache POI

除了我的语言(意大利语)的特殊字符出现问题外,一切都完美无缺。
我的情况如下:我有一个外部 html 文件。要导入,我使用以下代码

byte[] inputBytes = Files.readAllBytes(Paths.get("testo.html"));
String xhtml = new String(inputBytes, StandardCharsets.UTF_8);

然后我使用 stackoverflow 答案中提供的代码生成 docx。
如果我解压缩“word”文件夹下的 .docx,则我有正确的文件“chunk1.html”。
如果我打开它,则会正确报告特殊字符,例如

L'attività in oggetto è:

但是当我在 Word 中打开文档时,我看到了这个

L'attività in oggetto è: 

是否有我错过的相同 Microsoft 配置?
创建块时是否需要指定字符集?

【问题讨论】:

  • HTML文件中文字的编码是什么?

标签: ms-word apache-poi


【解决方案1】:

Microsoft 似乎将ANSI 作为WordHTML 块的默认字符编码。这很烦人,因为现在整个其他世界都将 Unicode (UTF-8) 作为默认设置。

所以我们需要为HTML 明确设置字符集。在chunk的HTML的模板中做:

...
  private MyXWPFHtmlDocument(PackagePart part, String id) throws Exception {
   super(part);
   this.html = "<!DOCTYPE html><html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"><style></style><title>HTML import</title></head><body></body>";
   this.id = id;
  }
...

我会推荐这个而不是使用 ANSI 编码来编码 HTML 块。

我也在How to add an altChunk element to a XWPFDocument using Apache POI 中将其编辑到我的答案中。

【讨论】:

  • 非常感谢。你很善良。效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多