使用以下 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>