2015-06-05 94 views
1

我有一個由ASPose生成的PDF作爲字節數組,並且我想在網頁上的組件內呈現該PDF。如何在HTML對象標記中呈現PDF字節數組

 using (MemoryStream docStream = new MemoryStream()) 
     { 
      doc.Save(docStream, Aspose.Words.SaveFormat.Pdf); 
      documentStream = docStream.ToArray(); 
     } 

我認爲這只是將字節數組賦值給後面代碼中的數據屬性的簡單變體。下面是設置,以及我嘗試的一些變化。我能做些什麼來將該字節數組作爲我的網頁的可見子組件?

 HtmlGenericControl pTag = new HtmlGenericControl("p"); 
     pTag.InnerText = "No Letter was Generated."; 
     pTag.ID = "errorMsg"; 
     HtmlGenericControl objTag = new HtmlGenericControl("object"); 
     objTag.Attributes["id"] = "pdf_content"; 
     objTag.Attributes["height"] = "400"; 
     objTag.Attributes["width"] = "500"; 
     String base64EncodedPdf = System.Convert.ToBase64String(pdfBytes); 

     //1-- Brings up the "No Letter was Generated" message 
     objTag.Attributes["data"] = "data:application/pdf;base64," + base64EncodedPdf.ToString(); 

     //2-- Brings up the gray PDF background and NO initialization bar. 
     objTag.Attributes["type"] = "application/pdf"; 
     objTag.Attributes["data"] = "data:application/pdf;base64," + base64EncodedPdf.ToString(); 

     //3-- Brings up the gray PDF background and the initialization bar, then stops. 
     objTag.Attributes["type"] = "application/pdf"; 
     objTag.Attributes["data"] = pdfBytes.ToString(); 

     //4-- Brings up a white square of the correct size, containing a circle with a slash in the top left corner. 
     objTag.Attributes["data"] = "application/pdf" + pdfBytes.ToString(); 


     objTag.Controls.Add(pTag); 
     pdf.Controls.Add(objTag); 
+0

你可以檢查[這裏] [1] ,相信pdf.js將幫助您 [1]:http://stackoverflow.com/questions/16266663/displaying-pdf- on-website-using-pdf-js – Yousef

回答

4

data屬性object標籤應包含指向一個終點,這將提供PDF字節流的URL。它不應該包含內聯字節流本身。

爲了使該頁面正常工作,您需要添加一個額外的handler,以提供字節流,例如, GetPdf.ashx。處理程序的ProcessRequest方法將準備PDF字節流並將其以內聯方式返回到響應中,並以適當的標題開頭,表示它是PDF對象。

protected void ProcessRequest(HttpContext context) 
{ 
    byte[] pdfBytes = GetPdfBytes(); //This is where you should be calling the appropriate APIs to get the PDF as a stream of bytes 
    var response = context.Response; 
    response.ClearContent(); 
    response.ContentType = "application/pdf"; 
    response.AddHeader("Content-Disposition", "inline"); 
    response.AddHeader("Content-Length", pdfBytes.Length.ToString()); 
    response.BinaryWrite(pdfBytes); 
    response.End(); 
} 

同時你的主頁將填充data attibute用在處理程序指向一個URL,例如

objTag.Attributes["data"] = "GetPdf.ashx"; 
+0

優秀。我試圖將所有內容都保存在頁面中。這可以算得上更合適。 – Joe