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

时间:2012-05-05 14:36:26

标签: asp.net pdf-generation itextsharp

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

以下是我的意思:Click here。但是在这个例子中,文件直接下载。

我该怎么做?

    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()

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

非常感谢您提前! :)

2 个答案:

答案 0 :(得分:5)

您需要设置Content Type的{​​{1}}并在Response object

中添加binary pdf形式
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); } } 阅读和显示:

在这里你可以找到这样做的方式

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

答案 1 :(得分:4)

问题通过以下代码解决:

    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()

希望有所帮助! :)

相关问题