如何在没有加载页面的情况下单击链接按钮动态生成pdf文件

时间:2011-07-19 05:13:32

标签: .net asp.net

我有一个用户控件,其中有一个面板用于显示我需要时打印的信息。 我有一个网格视图,我在其中获得搜索结果它有一个链接按钮,我想在上面打开该面板的pdf。

2 个答案:

答案 0 :(得分:2)

我已经实现了这一点,我希望其他人也可以这样做。我在下面列出了我的代码。

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

导入上面的DLL

string attachment = "attachment; filename=" + "File Name" + ".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");
    Page pg = new Page();
    HtmlForm frm = new HtmlForm();
    pg.EnableEventValidation = false;

    pg.RenderControl(htextw);
    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();
    //This is how you can add text in div in a pdf
    Chunk c = new Chunk(TextHere + "\n", FontFactory.GetFont("Verdana", 15));
    Paragraph p = new Paragraph();
    p.Alignment = Element.ALIGN_LEFT;
    p.Add(c); p.Add(c1);
    // This is how you can generate table and can set proprties
    PdfPTable table = new PdfPTable(2);
    table.WidthPercentage = 100;
    //Bill No and Bill Date
    PdfPCell pdfcell1 = new PdfPCell(new Phrase("Text in TAble" + "TExt From Database"));
    pdfcell1.Border = iTextSharp.text.Rectangle.BOTTOM_BORDER | iTextSharp.text.Rectangle.TOP_BORDER;
    table.AddCell(pdfcell1);
    PdfPCell pdfcell = new PdfPCell(new Phrase("Text in TAble" + "TExt From Database"));
    pdfcell.Border = iTextSharp.text.Rectangle.BOTTOM_BORDER | iTextSharp.text.Rectangle.TOP_BORDER;
    pdfcell.HorizontalAlignment = Element.ALIGN_RIGHT;
    table.AddCell(pdfcell);

    document.Add(p);
    document.Add(table);
    document.Add(tablegrid);
    StringReader str = new StringReader(stw.ToString());
    HTMLWorker htmlworker = new HTMLWorker(document);
    htmlworker.Parse(str);

    document.Close();
    Response.Write(document);

答案 1 :(得分:0)

我想你可能会遇到这个问题。您无法在客户端执行此操作,因为JavaScript无法操作文件(按设计)。 所以你的选择是:

  1. 完全回发
  2. Ajax call
  3. 您可以尝试对自定义处理程序(.ashx)文件进行Ajax调用,该文件会返回PDF文件的响应。我以前没试过这个,但它可能会奏效。如何用target="_blank"打开另一个页面,它将运行服务器端代码并​​生成PDF,而原始页面保持原样?