2012-05-05 59 views
2

如何在ASP.Net上使用iTextSharp創建後打開PDF文件?我不想將它保存在服務器上,但是當生成新的PDF時直接,它在瀏覽器上顯示。有可能這樣做嗎?iTextSharp生成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保存到服務器。

非常感謝您提前! :)

回答

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

希望幫助! :)

+0

@ mrjimoy.how在新標籤頁中打開它...當前在同一個標​​籤頁中打開,以便網頁被替換,不能去bak ... – Sivajith

5

您需要設置Response objectContent Type並添加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); 
     } 

    } 

(或)可以使用System.IO.MemoryStream讀取和顯示:

在這裏你可以發現這樣做的這樣,它

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

+0

所以這意味着我仍然應該將PDF保存到服務器,然後讀取它? –

+0

是絕對的,還有另一種更新方式。 – coder