【发布时间】:2015-07-28 09:03:57
【问题描述】:
我正在使用 ItextSharp 和 c#、asp.net MVC 来生成 PDF 报告。但是,当我生成报告时,PDF 返回为空白(除了工作正常的标题)。我会喜欢你的意见。
生成报告的代码如下:
using (var writer = PdfWriter.GetInstance(doc, ms))
{
// This sorts out the Header and Footer parts.
var headerFooter = new ReportHeaderFooter(reportsAccessor);
writer.PageEvent = headerFooter;
var rootPath = ConfigurationManager.AppSettings["SaveFileRootPath"];
string html = File.ReadAllText(rootPath + "/reports/report.html");
// Perform the parsing to PDF
doc.Open();
// The html needs to be sorted before this call.
StringReader sr = new StringReader(html);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr);
doc.Close();
writer.Close();
res = ms.ToArray();
}
我知道有很多隐藏的东西,但为了争论,这里有一个生成并放入 StringReader 的 HTML 示例:
<table style="font-size:10pt">
<tr>
<td rowspan="4"> Address<br/> </td>
<td>Phone: phone</td>
</tr>
<tr>
<td>Fax: fax</td>
</tr>
<tr>
<td>Email: email@example.com</td>
</tr>
<tr>
<td>Website: example.com</td>
</tr>
<table>
<table style="font-size:10pt; width:100%">
<tr style="width:50%">
<td>Settlement: 30 days from invoice</td>
</tr>
<tr>
<td>Delivery Charge Notes: N/A</td>
</tr>
</table>
<p style="width:100%; font-size:10pt">
I love notes</p>
<table>
<tr style="font-weight:bold">
<td>Item</td>
<td>Item Code</td>
<td>Description</td>
<td>Unit Size</td>
<td>Units Per Outer</td>
<td>Units Per Pallet</td>
<td>Invoice Price Volume Breaks</td>
<td>Branding</td>
<td>Notes</td>
</tr>
</table>
但是,这个 html 会生成一个漂亮的空白 PDF 文件(不是我想要的)。我看不出这可能有什么问题,并且希望对两件事提供一些意见:
[1] 为什么报告为空白 [2] 如果这是解析中的错误,为什么它没有出现错误而是空白报告(是否有我可以设置的设置或参数会抛出比空白报告更有用的错误? )
更新: 我已经添加了页眉/页脚的代码
公共字符串 HeaderTitle { get;放; } 公共 IReportsAccessor ReportsAccessor { 获取;放; } 公共 ReportHeaderFooter(IReportsAccessor 报告访问器) { this.ReportsAccessor = 报告访问者; }
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
var rootPath = ConfigurationManager.AppSettings["SaveFileRootPath"];
GetReportImageResult imgInfo = ReportsAccessor.GetImage(4);
byte[] header_img = imgInfo.ReportImage;
string logoFn = rootPath + "/tmp/logo.png";
File.WriteAllBytes(logoFn, header_img);
string html = File.ReadAllText(rootPath + "/reports/report_header.html");
html = html.Replace("{{ title }}", HeaderTitle);
html = html.Replace("{{ logo_img }}", logoFn);
StringReader sr = new StringReader(html);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr);
}
【问题讨论】:
-
您尝试过使用非常简单的 HTML 吗?您在下面显示的片段至少包含一个我已经看到的 HTML 错误(查看第一个表 - 您没有结束标记(您写的是“
”而不是“
”。它知道一个真正简单有效的 HTML 是否有效会很有趣;这意味着错误出在您的特定 HTML 文件中... -
@DavidvanDriessche - 测试并确认在传递无效 HTML 片段时引发异常。
标签: c# pdf itextsharp xmlworker