使用 iTextSharp 在 pdf 中打印具有所有效果和样式的富文本字符串

Print rich text string with all effect and styles in pdf using iTextSharp

我正在尝试使用版本为 5.5.8.0 的 itextSharp 库以 pdf 格式打印富文本内容。但我正在打印富文本,它只会打印普通字符串,没有任何样式效果或 html 标签。

这是我的包含富文本的网页视图

但是在使用 iTexhSharp 打印 pdf 时,它会像富文本一样打印,但每个 html 元素都会以新行开始打印,如下图

这是我用来打印 pdf 格式文本的代码:

ElementList elements = XMLWorkerHelper.ParseToElementList(descriptionData, "");

                PdfPCell cell = new PdfPCell();
                foreach(var ele in elements) {
                    cellDescriptionData.AddElement(ele);
                }

                tableThirdBlock.AddCell(cellDescriptionData);

此处 "descriptionData" 字段将包含 html 字符串。

我希望以 pdf 格式打印与 Web 视图中可用的内容相同。

这里是动态生成的实际 HTML 字符串。所以 html 字符串将是动态的,带有动态 css 和文本。

" <b style="font-family: Arial, Verdana; font-size: 10pt; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal; color: rgb(204, 255, 255); background-color: rgb(51, 102, 255);">zzz&nbsp;</b><div style="font-family: Arial, Verdana; font-size: 10pt; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"><b style="color: rgb(204, 255, 255); background-color: rgb(51, 102, 255);"><br /></b></div><div><b style="font-family: Arial, Verdana; font-size: 10pt; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal; color: rgb(204, 255, 255); background-color: rgb(51, 102, 255);">Test &nbsp;</b> &nbsp; <span style="color: rgb(255, 0, 0);">&nbsp;<span style="font-weight: bold;">Description</span> &nbsp;</span><span style="color: rgb(153, 51, 153); font-style: italic;">Other Color</span></div> ".

有什么问题,我想念的吗?

请帮我在pdf中打印出所有效果和样式的富文本。

谢谢

我是你的评论,你要求的是一个关于如何使用 XML Worker 将 HTML 解析为 Element 对象列表的示例。这样的例子可以在官方 iText 网站上的问题答案中找到,例如:

在 1 中,您会发现可以将 HTML 和 CSS 文件解析为 ElementList 对象:

ElementList elements = XMLWorkerHelper.parseToElementList(HTML, CSS);

在 2 中,您将学习如何将 ElementList 中的元素添加到 PdfPCell:

PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell();
for (Element e : elements) {
    cell.addElement(e);
}
table.addCell(cell);
document.add(table);

请注意,我简化了原始问题中的示例。您不需要 RTL,因为您的文本可能不是阿拉伯语。您可能可以使用便捷方法 parseToElementList() 而不是使用 2.

中使用的完整代码

我已经创建了一个概念证明,结果是文件 test-herin.pdf:

获得此结果的 HTML 如下所示:

<div><span class="bluetextwhitebackground">zzz</span></div>
<div>
<span class="bluetextwhitebackground">Test</span>
<span class="redtext">Description</span>
<span class="italicpurple">Other Color</span>
</div>

获得所需样式的 CSS 如下所示:

.bluetextwhitebackground
    { font-family: times; color: white; background: blue}
.redtext
    { font-family: times; color: red; }
.italicpurple
    { font-family: times; font-style: italic; color: purple }

如您所见,当我想要一段在呈现文本后导致换行的文本时,我使用了 <div>。我在不希望出现新行的情况下使用 <span>

很难回答你的问题,因为你没有展示你的HTML。使用 <p><div> 标签时,或通过在 CSS.

中将某些内容定义为 div 时,会触发新行

顺便说一下,生成 PDF 的代码可以在这里找到:ParseHtml13

更新:

在您分享 HTML 之后,我创建了另一个概念证明:

生成的 PDF 文件是 test-herin2.pdf,看起来像这样:

这看起来完全符合我的预期。换句话说:我无法重现您所描述的问题。如果我不能重现问题,我就无法修复它。