不確定是否在代碼中跳過了一個步驟,我正在使用ItextSharp版本5.5.1和XML Worker版本5.5.1。 doc.Close拋出一個異常「文檔沒有頁面」,但我看了sw.toString(它有html內容)。使用Itextsharp(XMLWorker)將Asp.net頁面轉換爲pdf返回已損壞/空白pdf
private void ExporttoPDF()
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=RequestSummaryReport.pdf");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/pdf";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
var doc = new Document(PageSize.A3, 45, 5, 5, 5);
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser xmlParse = new XMLParser(true, worker);
pnlReport.RenderControl(htw);
StringReader sr = new StringReader(sw.ToString());
xmlParse.Parse(sr);
xmlParse.Flush();
doc.Close();
Response.Write(doc);
}
起初看起來大多是正確的。您直接寫入HTTP響應流,因此不需要執行Response.Write(doc);(該行不會執行大多數人認爲它的操作)。我手邊沒有一個ASP.Net服務器,所以我用'StringReader sr = new StringReader'(「Hello」)嘗試了它;'並且它工作正常。 –