如何在 iTextSharp 中显示水平线
Posted
技术标签:
【中文标题】如何在 iTextSharp 中显示水平线【英文标题】:How to show horizontal line in iTextSharp 【发布时间】:2013-02-26 10:38:26 【问题描述】:我正在创建一个 pdf,需要在页面中放置一条水平线。谁能告诉我该怎么做?
我有一个 xml 文件,其中包含我的 html 标签 (<table>....</table>
)。并且xml
文件的全部内容被解析为string
,用于创建pdf
。现在不支持某些标签。其中之一是<hr>
。那么我可以在xml
文件中使用任何其他标签,以便绘制一个
line
使用 xml 数据创建 pdf 时。
下面是xml xontent的例子
<table>
<tr>
<td>
<span>
This is working properly.
</span>
</td>
<tr>
</table>
<table>
<tr>
<td>
<span>
<hr>
This is not working properly.
</span>
</td>
<tr>
</table>
如果需要更多信息,请告诉我。
提前致谢。
【问题讨论】:
Look here 和Here too 谢谢哈里斯。我需要一个等效的 我没有使用 pdf 元素创建背后的代码。我有简单的 html 需要显示。特别是我想只显示表格行的底部边框。 您使用的是哪个版本的 Itextsharp? @Nil版本是5.4.1.0。 查看此链接,其中给出了有关 itextSharp 的功能数量bluelemoncode.com/post/2011/12/06/… 【参考方案1】:下面创建了一条几像素厚的全宽黑线,我使用的是HTMLWorker.Parse
:
<table>
<tr>
<td>
<span>
This is working properly.
</span>
</td>
<tr>
</table>
<table>
<tr>
<td>
<span>
<table border="1" cellpadding="0" cellspacing="0"><tr><td> </td></tr></table>
This is working properly now too!
</span>
</td>
<tr>
</table>
【讨论】:
谢谢彼得。这将创建一条 2px 宽度的线。但我想知道是否有其他方法可以做到这一点。如果在 1-2 天内没有提供更好的答案,我会将答案标记为已接受。 @Narendra - 我同意这不是一个理想的解决方案。我开始查看源代码以尝试追踪它如何呈现各种标签,看看是否有更好的选择,但我并没有停止寻找。为了使您的 xml 更漂亮,您可以留在中,然后用表格 HTML 对
进行字符串替换。【参考方案2】:
您可以从开始位置(moveto)、LineTo 开始画线,然后描边(提交线):
...
PdfContentByte cb = writer.DirectContent;
....
cb.MoveTo(doc.PageSize.Width / 2, doc.PageSize.Height / 2);
cb.LineTo(doc.PageSize.Width / 2, doc.PageSize.Height);
cb.Stroke();
...
【讨论】:
请检查已编辑的问题。实际上我是在 xml 中创建内容。然后这个xml内容直接用来创建pdf。我没有使用代码隐藏 pdf 元素。【参考方案3】:希望对你有帮助
PdfPTable table = new PdfPTable(1); //Create a new table with one column
PdfPCell cellLeft = new PdfPCell(); //Create an empty cell
StyleSheet style = new StyleSheet(); //Declare a stylesheet
style.LoadTagStyle("h1", "border-bottom", "red"); //Create styles for your html tags which you think will be there in PDFText
List<IElement> objects = HTMLWorker.ParseToList(new StringReader(PDFText),style); //This transforms your HTML to a list of PDF compatible objects
for (int k = 0; k < objects.Count; ++k)
cellLeft.AddElement((IElement)objects[k]); //Add these objects to cell one by one
table.AddCell(cellLeft);
【讨论】:
以上是关于如何在 iTextSharp 中显示水平线的主要内容,如果未能解决你的问题,请参考以下文章