我正在尝试使用版本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格式打印相同内容。
这是实际的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 </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 </b> <span style="color: rgb(255, 0, 0);"> <span style="font-weight: bold;">Description</span> </span><span style="color: rgb(153, 51, 153); font-style: italic;">Other Color</span></div> ".
有什么不对,我错过了吗?
请帮我打印PDF格式的所有效果和样式的富文本。
由于
答案 0 :(得分:2)
我的评论,您要求的示例是如何使用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
<强>更新强>
生成的PDF文件为test-herin2.pdf,如下所示:
这看起来完全符合我的预期。换句话说:我无法重现你所描述的问题。如果我无法重现问题,我就无法修复它。