使用以下ASP.net/iTextSharp代码将HTML文件的内容解析为PDF并将其转储到响应流:
Response.Clear();
Response.ContentType = "application/pdf";
using (Document doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
using (TextReader reader = File.OpenText(Server.MapPath("~/Test.htm")))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, reader);
}
doc.Close();
}
Response.End();这是可行的,但生成的PDF的样式与原始HTML页面完全不同。对于初学者来说,内置的css解析器似乎只能处理直接的标签样式和类(没有像thead th { background-color:#999; }这样的链接)。
其次,边界似乎是一个要么全有要么全无的交易。它没有上边界、下边界等概念,而且边界折叠不会折叠相邻单元格的边界,因此边界最终会是我想要的两倍。
最后,我不知道如何将表格与文档的左侧或右侧对齐。它始终居中。我尝试使用text-align在div中进行换行,尝试设置align属性,尝试直接在表上设置text-align。你想不出来吗?
以下是我的演示文档,我试图将其用作概念验证:
<!DOCTYPE html>
<html>
<head>
<title>This is the title</title>
<meta name="description" content="This is the description" />
<meta name="keywords" content="abc, 123, xyz" />
<style type="text/css">
body { font-family:Arial, Verdana, Sans-Serif; font-size:9pt; }
.dataGrid { font-family:Arial, Verdana, Sans-Serif; font-size:9pt; border-collapse: collapse; border:1px solid #000; width:80%; margin:0; text-align:left; }
th { padding:3px 4px; font-weight:bold; border:1px solid #000; }
td { padding:3px 4px; border:1px solid #000; }
.head { border-bottom:2px solid #000; background-color:#9BBA1F; font-weight:bold; }
.odd { background-color:#fff; }
.even { background-color:#D6EB87; }
.foot { border-top:2px solid #000; background-color:#BAB0C4; font-weight:bold; }
h1 { font-size:14pt; color:#FFA200; text-align:center; }
.right { text-align:right; }
.center { text-align:center; }
.left { text-align:left; }
</style>
</head>
<body>
<h1>Sample Document</h1>
<div style="text-align:left;">
<table class="dataGrid" align="left">
<thead>
<tr class="head">
<th width="70%">Name</th>
<th width="15%" class="center">Qty</th>
<th width="15%" class="center">Price</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>ABC</td>
<td class="center">2</td>
<td class="right">$5.00</td>
</tr>
<tr class="even">
<td>XYZ</td>
<td class="center">1</td>
<td class="right">$10.00</td>
</tr>
<tr class="odd">
<td>123</td>
<td class="center">3</td>
<td class="right">$2.00</td>
</tr>
<tr class="even">
<td>789</td>
<td class="center">1</td>
<td class="right">$4.00</td>
</tr>
</tbody>
<tfoot>
<tr class="foot">
<td class="right">Totals</td>
<td class="center">7</td>
<td class="right">$30.00</td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>发布于 2012-09-27 21:01:32
在这上面花了一大堆时间之后,我无法让它正常工作。因此,我最终切换到了另一个工具: wkHtmlToPdf。我使用了Nuget中可用的Codaxy包装器类来帮助创建调用,并且看到了比使用iTextSharp更好的结果。它主要理解CSS选择器,并自动处理图像和链接等事情。
https://stackoverflow.com/questions/12606835
复制相似问题