iTextSharp generate PDF and show it on the browser directly

99封情书 提交于 2020-01-21 08:40:07

问题


How to open the PDF file after created using iTextSharp on ASP.Net? I don't want to save it on the server, but directly when the new PDF is generated, it shows on the browser. Is it possible to do that?

Here is the example for what I mean: Click here . But on this example, the file directly downloaded.

How can I do that?

    Dim doc1 = New Document()

    'use a variable to let my code fit across the page...
    Dim path As String = Server.MapPath("PDFs")
    PdfWriter.GetInstance(doc1, New FileStream(path & "/Doc1.pdf", FileMode.Create))

    doc1.Open()
    doc1.Add(New Paragraph("My first PDF"))
    doc1.Close()

The code above do save the PDF to the server.

Thank you very much in advance! :)


回答1:


You need to set Content Type of the Response object and add the binary form of the pdf in the header

 private void ReadPdfFile()
    {
        string path = @"C:\Somefile.pdf";
        WebClient client = new WebClient();
        Byte[] buffer =  client.DownloadData(path);

        if (buffer != null)
        {
            Response.ContentType = "application/pdf"; 
            Response.AddHeader("content-length",buffer.Length.ToString()); 
            Response.BinaryWrite(buffer); 
        }

    }

(or) you can use System.IO.MemoryStream to read and display:

Here you can find that way of doing it

Open Generated pdf file through code directly without saving it onto the disk




回答2:


The problem solved with the code below:

    HttpContext.Current.Response.ContentType = "application/pdf"
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)

    Dim pdfDoc As New Document()
    PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream)

    pdfDoc.Open()
    'WRITE PDF <<<<<<

    pdfDoc.Add(New Paragraph("My first PDF"))

    'END WRITE PDF >>>>>
    pdfDoc.Close()

    HttpContext.Current.Response.Write(pdfDoc)
    HttpContext.Current.Response.End()

Hope help! :)



来源:https://stackoverflow.com/questions/10462853/itextsharp-generate-pdf-and-show-it-on-the-browser-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!