iTextSharp生成PDF并直接在浏览器上显示

mrj*_*_05 3 asp.net pdf-generation itextsharp

如何在ASP.Net上使用iTextSharp创建后打开PDF文件?我不想将其保存在服务器上,但是直接在生成新PDF时,它会在浏览器上显示.有可能吗?

这是我的意思的例子:点击这里.但是在这个例子中,文件直接下载.

我怎样才能做到这一点?

    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()
Run Code Online (Sandbox Code Playgroud)

上面的代码确实将PDF保存到服务器.

非常感谢你提前!:)

cod*_*der 5

您需要设置Content TypeResponse object,添加binary的形式pdfheader

 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); 
        }

    }
Run Code Online (Sandbox Code Playgroud)

(或)你可以System.IO.MemoryStream用来阅读和显示:

在这里你可以找到这种方式

直接通过代码打开生成的pdf文件,而不将其保存到磁盘上


mrj*_*_05 5

问题通过下面的代码解决:

    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()
Run Code Online (Sandbox Code Playgroud)

希望有帮助!:)