2016-11-11 143 views
0

我在Angular 2中遇到問題在Iframe或任何控件中顯示PDF。PDF顯示Angular 2

你能指導我嗎?

我的Web API代碼:

[Route("GetReportStream")] 
    [HttpPost] 
    public HttpResponseMessage GetReportStream(string strReportUrl) 
    { 
     strReportUrl = "http://sample.com/ReportServer?%2fN+Team+3%2fD+Online+Reports%2fMemo+to+the+Court&rs:Command=Render&rc:Parameters=False&DocumentID=8&rs:Format=PDF"; 

     byte[] pdf; 
     byte[] buffer = new byte[4096]; 
     try 
     { 
      WebRequest request = WebRequest.Create(strReportUrl); 
      request.UseDefaultCredentials = true; 
      using (WebResponse resp = request.GetResponse()) 
      { 
       using (Stream responseStream = resp.GetResponseStream()) 
       { 
        using (MemoryStream memoryStream = new MemoryStream()) 
        { 
         int count = 0; 
         do 
         { 
          count = responseStream.Read(buffer, 0, buffer.Length); 
          memoryStream.Write(buffer, 0, count); 
         } while (count != 0); 
         pdf = memoryStream.GetBuffer(); 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      pdf = null; 
     } 
     var response = Request.CreateResponse<byte[]>(HttpStatusCode.OK, pdf);    
     return response; 
    } 

我回國作爲我接受它字節。

private getReportStreamOnSuccess(response): void { 
    debugger;   
    var byteArray = new Uint8Array(response); 
    var blob = new Blob([byteArray], { type: 'application/pdf' }); 
    //var file = new Blob([response], { type: 'application/pdf' }); 
    var fileURL = URL.createObjectURL(blob); 
    this.url = this.domSanitizer.bypassSecurityTrustResourceUrl(fileURL); 
} 

我試過所有的選項沒有任何工作。

我只想在iframe或任何控件中查看它。

當我嘗試加載BLOB我得到這個 Image

回答

0

我發現這個鏈接前一陣子,希望它幫助。 http://www.devsplanet.com/question/35368633' 基本上: 實際上,該功能尚未在HTTP支持中實現。

作爲一種解決方法,則需要擴展BrowserXhr類Angular2的如下所述設定的responseType成團塊底層XHR對象上:

import {Injectable} from 'angular2/core'; 
import {BrowserXhr} from 'angular2/http'; 

@Injectable() 
export class CustomBrowserXhr extends BrowserXhr { 
    constructor() {} 
    build(): any { 
    let xhr = super.build(); 
    xhr.responseType = "blob"; 
    return <any>(xhr); 
    } 
} 

然後,你需要包裝響應的負載成博客對象,並使用FileSaver庫打開下載對話框:

downloadFile() { 
    this.http.get(
    'https://mapapi.apispark.net/v1/images/Granizo.pdf').subscribe(
     (response) => { 
     var mediaType = 'application/pdf'; 
     var blob = new Blob([response._body], {type: mediaType}); 
     var filename = 'test.pdf'; 
     saveAs(blob, filename); 
     }); 
} 

的FileSaver庫必須納入到你的HTML文件:

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script> 

看到這個plunkr:http://plnkr.co/edit/tfpS9k2YOO1bMgXBky5Y?p=preview

不幸的是這將設置的responseType所有AJAX請求。爲了能夠設置這個屬性的值,在XHRConnection和Http類中有更多的更新。

作爲參考看到這些鏈接:

https://stackoverflow.com/questions/34586671/download-pdf-file-using-jquery-ajax

Receive zip file, angularJs

+0

它沒有工作,我嘗試同樣也是如此。我有一份SSRS報告我希望以PDF形式顯示在角度2中無需保存。 – Venk