将ASP.NET页面保存为PDF和iTextsharp

时间:2015-12-29 16:44:54

标签: c# asp.net pdf

我想将我的ASP.NET页面保存为PDF,但我不想使用response.write,因为我不想将其返回给客户端。我想将PDF保存在SERVER SIDE上。

 protected void btnSubmit_Click(object sender, EventArgs e)
{
   //code below saves current ASP.NET page as PDF and returns save dialog to client on where to download PDF
    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    this.Page.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());

    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);

    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();

    Response.Write(pdfDoc);
    Response.End();

}

如何保存PDF?

1 个答案:

答案 0 :(得分:1)

  

如何保存PDF?

如果您想将pdf保存到文件系统,只需向FileStream电话提供适当的PdfWriter.GetInstance,而不是Response.OutputStream

顺便说一下,你的行

Response.Write(pdfDoc);

在响应中导致垃圾,Document pdfDoc不包装或以其他方式包含结果PDF,它仅提供一个API来向pdf添加内容。