将aspx转换为pdf

时间:2011-07-20 06:37:23

标签: c# asp.net pdf itextsharp

string attachment = "attachment; filename=" + filename + ".pdf"; 
    Response.ClearContent(); 
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/pdf";
    StringWriter stw = new StringWriter();
    HtmlTextWriter htextw = new HtmlTextWriter(stw);
    htextw.AddStyleAttribute("font-size", "7pt");
    htextw.AddStyleAttribute("color", "Black");
    Panel_Name.RenderControl(htextw);// .RenderControl(htextw);
    //Name of the Panel 
    Document document = new Document();
    document = new Document(PageSize.A4, 5, 5, 15, 5);
    FontFactory.GetFont("Arial", 50, iTextSharp.text.BaseColor.BLUE);
    PdfWriter.GetInstance(document, Response.OutputStream);
    document.Open();
    StringReader str = new StringReader(stw.ToString());
    HTMLWorker htmlworker = new HTMLWorker(document);
    htmlworker.Parse(str);
    document.Close();
    Response.Write(document);

我已经返回此代码以生成aspx页面的pdf(即Default.aspx到Default.pdf)。它生成一个pdf文件但生成的pdf文件不受支持我有一个最新版本的pdf。它给出了一个打开文档时出错。文件已损坏,无法修复。

2 个答案:

答案 0 :(得分:3)

您需要下载ITextSharp并将其引用添加到您的项目中。 ITextSharp是免费的HTML到PDF库。您可以使用以下下载链接下载它。

HTML标记

<form id="form1" runat="server">
    <div>
       <img src = "//www.aspsnippets.com/images/Blue/Logo.png" /><br />
    </div>
    <div style = "font-family:Arial">This is a test page</div>
    <div>
       <table border = "1" width = "100">
          <tr><td>Name</td><td>Age</td></tr>
          <tr><td>John</td><td>11</td></tr>
          <tr><td>Sam</td><td>13</td></tr>
          <tr><td>Tony</td><td>12</td></tr>
       </table>
    </div>
    <div>
       <asp:Button ID="btnExport" runat="server" Text="Export" onclick="btnExport_Click" />
    </div>
</form>

命名空间

using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

C#代码

protected void btnExport_Click(object sender, EventArgs e)
{
    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();
}

答案 1 :(得分:0)

您可以使用第三方库创建pdf,例如PDFizer