从HTML创建PDF时出错 [英] Error Creating PDF from HTML
问题描述
嗨专家,
在.aspx页面我在面板中有asp.Panel,有一个从DB生成的转发器。
点击按钮我将html转换为PDF哪个工作得很好。
当我尝试在Page_Load上做同样的事情时,它给了我错误:
Hi Experts,
In .aspx page I have asp.Panel inside the panel there's a repeater generated from DB.
On button click I convert the html to PDF Which work very well.
When I try to do the same on Page_Load it gives me error:
The document has no pages.
尝试通过添加以下内容来解决此问题:
Tried to fix this by adding:
Document.Add(new Paragraph("Hello World!"));.
但是它给出了空的PDF文件。
所以我试图在页面加载后运行我的转换函数:
but it gives empty PDF file.
So I tried to run my converting function after page load:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
Response.Flush();
ExportPDF();
}
它给出错误:
It gives error:
Server cannot set content type after HTTP headers have been sent
转换功能:
The converting function:
private void ExportPDF()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Invoice.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
pnlContents.RenderControl(hw); //the containing panel
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
所以看起来asp.Panel有问题。
请告知为什么它可以按下按钮点击但是不在页面加载或渲染。我缺少什么?
感谢您的帮助
Samira
So It looks like something wrong with the asp.Panel.
Please advise why it would work on button click but not on page load or Render. What I am missing?
Thanks for help
Samira
推荐答案
发现了问题。必须像下面的代码一样设置渲染事件:
Found the problem. Had to set Render event like the following code:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
ExportPDF();
//base.Render(writer);
//Response.Flush();
}
希望能帮到别人。
谢谢,
Samira
Hope will help others.
Thanks,
Samira
这篇关于从HTML创建PDF时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!