【发布时间】:2011-02-16 23:46:37
【问题描述】:
以下代码将不起作用,因为控件(page1、page2、page3)要求调用它们的“Page_Load”事件。
using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
public partial class utilities_getPDF : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// add user controls to the page
AddContentControl("controls/page1");
AddContentControl("controls/page2");
AddContentControl("controls/page3");
// set up the response to download the rendered PDF...
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment;filename=FileName.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
// get the rendered HTML of the page
System.IO.StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
this.Render(htmlWrite);
StringReader reader = new StringReader(stringWrite.ToString());
// write the PDF to the OutputStream...
Document doc = new Document(PageSize.A4);
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
parser.Parse(reader);
doc.Close();
}
// the parts are probably irrelevant to the question...
private const string contentPage = "~/includes/{0}.ascx";
private void AddContentControl(string page)
{
content.Controls.Add(myLoadControl(page));
}
private Control myLoadControl(string page)
{
return TemplateControl.LoadControl(string.Format(contentPage, page));
}
}
所以我的问题是:
如何获取控件 HTML?
【问题讨论】:
标签: c# .net pdf-generation