iTextSharp generate PDF and show it on the browser directly

主宰稳场 提交于 2019-12-01 09:27:43
coder

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

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! :)

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