以PDF格式获取整个页面

时间:2013-11-13 07:21:00

标签: asp.net .net c#-4.0 pdf pdf-generation

问题:

我想在我的页面上点击一个按钮,以pdf的形式保存页面的全部内容。

查询:

所以任何人都知道,是否有任何库或程序集或任何代码可以为我提供此功能?

提前致谢

1 个答案:

答案 0 :(得分:1)

身体部位

 <asp:PlaceHolder ID="PlaceholderPdf" runat="server">   
 <asp:Label ID="Label1" runat="server" Text="hi hw r u ...i m fine wht about u"></asp:Label>
</asp:PlaceHolder>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click1" 
        Text="converting to pdf" />

下载itextsharp.dll

一些必要的名称空间

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

.cs part

protected void Button2_Click1(object sender, EventArgs e)
{
//SIMPLE TEXT IS CONVERTING
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Filename.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    //Render PlaceHolder to temporary stream
    System.IO.StringWriter stringWrite = new StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    PlaceholderPdf.RenderControl(htmlWrite);
    StringReader reader = new StringReader(stringWrite.ToString());
    //Create PDF document
    Document doc = new Document(PageSize.A4);
    HTMLWorker parser = new HTMLWorker(doc);
    PdfWriter.GetInstance(doc, Response.OutputStream);
    doc.Open();
    try
    {
        //Create a footer that will display page number
        //Parse Html
        parser.Parse(reader);

    }
    catch (Exception ex)
    {
        //Display parser errors in PDF.
        //Parser errors will also be wisible in Debug.Output window in VS
        Paragraph paragraph = new Paragraph("Error! " + ex.Message);
        Chunk text = paragraph.Chunks[0] as Chunk;
        if (text != null)
        {
        }
        doc.Add(paragraph);
    }
    finally
    {
        doc.Close();
    }
}
 public override void VerifyRenderingInServerForm(Control control)
{
}

试试这个让我知道