【问题标题】:Render simple HTML into docx using docxtpl使用 docxtpl 将简单的 HTML 渲染成 docx
【发布时间】:2021-04-01 09:14:28
【问题描述】:

我正在使用 python 模块 docxtpl 在用 jinja2 编写的 docx 模板中打印数据。 到目前为止效果很好,但我需要在 docx 中呈现一些像这样的简单 HTML:

<h2>Some title</h2>
<h4>Lorem&nbsp;ipsum <strong>dolor sit amet</strong>, consectetur adipisicing elit. Possimus, aliquam,
    minima fugiat placeat provident optio nam reiciendis eius beatae quibusdam!</h4>
<p style="font-size: 18px;">The text is derived from Cicero's De Finibus Bonorum et Malorum (On the Ends of Goods
    and Evils, or alternatively [About] The Purposes of Good and Evil). The original passage began: Neque porro
    quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit (Translation: "Neither is
    there <del>anyone</del> who loves grief itself since it is grief and thus wants to obtain it").</p>
<table class="table">
    <tbody>
        <tr>
            <td>Test</td>
            <td>Test1</td>
            <td>Test2</td>
            <td>Test3</td>
        </tr>
        <tr>
            <td>Lorem</td>
            <td>Lorem1</td>
            <td>Lorem2</td>
            <td>Lorem3</td>
        </tr>
        <tr>
            <td>Ipsum</td>
            <td>Ipsum1</td>
            <td>Ipsum2</td>
            <td>Ipsum3</td>
        </tr>
    </tbody>
</table>

很遗憾,我无法使用 docxtpl 中的 RichText() 来呈现表格和其他 html 内容。

我试图想出一些解决方案,但我想了解除此之外是否还有更好的方法,例如,将 html usign htmldocx 生成的一个 docx 与使用 docxtpl 生成的一个 docx 合并或使用 @ 获取内容来自一个 docx 的 987654330@ 模块并将其插入另一个。

在最坏的情况下,我也愿意切换到 JavaScript/BASH。

【问题讨论】:

  • 我正在处理同样的问题。您是否曾在 docxtpl 中找到解决方案?
  • 很抱歉,我还没有找到解决方案...
  • 我正在使用@Synthase 建议的解决方法。具体来说,我对大部分文档使用docxtpl,然后对于特定于html的内容,我创建一个独立的html文件,然后使用htmldocx将html文件转换为docx,然后将其附加回主docx使用docxcompose。不理想,但它适用于我的目的。

标签: python docx python-docx docxtpl


【解决方案1】:
from htmldocx import HtmlToDocx

new_parser = HtmlToDocx()
new_parser.parse_html_file("html_filename", "docx_filename")
#Files extensions not needed, but tolerated

这应该像在 docx 中转换 html 的魅力一样。

不确定我是否理解您的合并问题。最好的方法当然是将您的 docx 模板改为 html。然后,一旦您将所需的所有内容都转储到一个 html 文件中,就可以转换为 docx。

如果您想将 docx 合并/插入在一起左右,可以在这里查看:How do I append new data to existing doc/docx file using Python

【讨论】:

  • 是的,但是......正如我在问题中所说的那样,这并不是我想要的:比以不同方式生成的 merge 2 docx 更好的解决方案?我需要使用 docxtpl 或一些允许模板的模块
  • 我就是这么说的。您应该生成一个 HTML 模板,而不是一个 docx 模板。然后在最后将整个 html 内容传递到 docx 中。
猜你喜欢
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多