使用 iTextSharp 将生成的 html 页面转换为 pdf,我无法让从 asp:DataGrid 创建的表格显示在 PDF 中。数据网格的页面 HTML 输出如下所示:
<p>Purchases:</p>
<table rules="all" id="dg_Purchase" style="font-size: smaller; border-collapse: collapse;" border="1" cellspacing="0">
<tbody><tr>
<td>Lot #</td>
<td> </td>
<td>Title</td>
<td align="right">Price</td>
<td align="right">Buyer's Premium</td>
<td align="right">Tax</td>
<td align="right">Sub Total</td>
</tr><tr>
<td>118</td>
<td><input id="dg_Purchase_ctl02_CheckBox1" name="dg_Purchase$ctl02$CheckBox1" type="checkbox"></td>
<td>Yih-Wen Kuo (1959, Taiwan)</td>
<td align="right">$1,900.00</td>
<td align="right">$332.50</td>
<td align="right">$0.00</td>
<td align="right">$2,232.50</td>
</tr><tr>
<td>119</td>
<td><input id="dg_Purchase_ctl03_CheckBox1" name="dg_Purchase$ctl03$CheckBox1" type="checkbox"></td>
<td>Yih-Wen Kuo (1959, Taiwan)</td>
<td align="right">$1,800.00</td>
<td align="right">$315.00</td>
<td align="right">$0.00</td>
<td align="right">$2,115.00</td>
</tr>
</tbody></table>
<p>Payments:</p>
<table rules="all" id="dg_Payment" style="font-size: smaller; border-collapse: collapse;" border="1" cellspacing="0">
<tbody><tr>
<td style="width: 120px;">Payment Method</td>
<td>Date</td>
<td align="right">Amount </td>
</tr><tr>
<td>Total</td>
<td> </td>
<td align="right">$0.00</td>
</tr>
</tbody></table>
当查看 HTML 页面时,表格看起来与它应有的完全一样。但是当我生成 PDF 时,表格(或者更确切地说,表格中的所有内容)没有显示。只有边框是可见的,几乎只是每个表格的 2 px 直线。
因此,在我的普通脚本中,加载整个页面后,我要做的最后一件事是:
StringWriter stringWriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringWriter);
Render(writer);
iTextSharp 的功能如下:
protected override void Render(HtmlTextWriter writer)
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
base.Render(myWriter);
myWriter.Flush();
myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
strmRdr.Dispose();
mem.Dispose();
writer.Write(pageContent);
CreatePDFDocument(pageContent);
}
public void CreatePDFDocument(string strHtml)
{
string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
document.Close();
ShowPdf(strFileName);
}
public void ShowPdf(string strFileName)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.ContentType = "application/pdf";
Response.WriteFile(strFileName);
Response.Flush();
Response.Clear();
}
同样,页面上以编程方式设置的所有内容都会显示在 PDF 中,但数据网格除外。越过边界,似乎这不是width
问题。它只是看起来是空的,仅此而已。任何帮助将不胜感激。