简体   繁体   中英

save ASP.NET page as PDF and iTextsharp

I want to save my ASP.NET page as a PDF, but I don't want to use response.write because I don't want to return it to the client. I want to save the PDF on the 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();

}

How do I just save the PDF?

How do I just save the PDF?

If you want to save the pdf to the file system, simply supply an appropriate FileStream to the PdfWriter.GetInstance call instead of your Response.OutputStream .


By the way, your line

Response.Write(pdfDoc);

results in trash in the response, the Document pdfDoc doesn't wrap or otherwise contain the result PDF, it merely provides an API to add content to the pdf.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM