【问题标题】:save ASP.NET page as PDF and iTextsharp将 ASP.NET 页面保存为 PDF 和 iTextsharp
【发布时间】:2015-12-29 16:44:54
【问题描述】:

我想将我的 ASP.NET 页面保存为 PDF,但我不想使用 response.write,因为我不想将它返回给客户端。我想将 PDF 保存在服务器端。

 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?

【问题讨论】:

    标签: c# asp.net pdf


    【解决方案1】:

    如何保存 PDF?

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


    顺便说一句,你的台词

    Response.Write(pdfDoc);
    

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

    【讨论】:

    • 谢谢!我知道答案很简单。示例按钮单击代码是文档中的文字复制/粘贴。我这样做了:FileStream fio = new FileStream(Server.MapPath("~/pdfs/ozzy.pdf"), FileMode.Create); PdfWriter.GetInstance(pdfDoc, fio);
    猜你喜欢
    • 1970-01-01
    • 2011-06-06
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多