简体   繁体   English

PDF Blob 未显示内容,Angular 2

[英]PDF Blob is not showing content, Angular 2

I have problem very similar to this PDF Blob - Pop up window not showing content , but I am using Angular 2. The response on question was to set responseType to arrayBuffer, but it not works in Angular 2, the error is the reponseType does not exist in type RequestOptionsArgs.我有与此PDF Blob非常相似的问题- 弹出窗口未显示内容,但我使用的是 Angular 2。问题的回答是将 responseType 设置为 arrayBuffer,但它在 Angular 2 中不起作用,错误是 reponseType 不存在于 RequestOptionsArgs 类型中。 I also tried to extend it by BrowserXhr, but still not work ( https://github.com/angular/http/issues/83 ).我也尝试通过 BrowserXhr 扩展它,但仍然不起作用( https://github.com/angular/http/issues/83 )。

My code is:我的代码是:

createPDF(customerServiceId: string) {
   console.log("Sending GET on " + this.getPDFUrl + "/" + customerServiceId);

   this._http.get(this.getPDFUrl + '/' + customerServiceId).subscribe(
       (data) => {
            this.handleResponse(data);
         });
}

And the handleResponse method:和 handleResponse 方法:

handleResponse(data: any) {
     console.log("[Receipt service] GET PDF byte array " + JSON.stringify(data));

     var file = new Blob([data._body], { type: 'application/pdf' });            
     var fileURL = URL.createObjectURL(file);
     window.open(fileURL);
 }

I also tried to saveAs method from FileSaver.js, but it is the same problem, pdf opens, but the content is not displayed.我也尝试从 FileSaver.js 中使用 saveAs 方法,但它是同样的问题,pdf 打开,但不显示内容。 Thanks谢谢

I had a lot of problems with downloading and showing content of PDF, I probably wasted a day or two to fix it, so I'll post working example of how to successfully download PDF or open it in new tab:我在下载和显示 PDF 内容时遇到了很多问题,我可能浪费了一两天来修复它,所以我将发布如何成功下载 PDF 或在新选项卡中打开它的工作示例:

myService.ts我的服务.ts

downloadPDF(): any {
        return this._http.get(url, { responseType: ResponseContentType.Blob }).map(
        (res) => {
            return new Blob([res.blob()], { type: 'application/pdf' })
        }
}

myComponent.ts myComponent.ts

this.myService.downloadPDF().subscribe(
        (res) => {
            saveAs(res, "myPDF.pdf"); //if you want to save it - you need file-saver for this : https://www.npmjs.com/package/file-saver

        var fileURL = URL.createObjectURL(res);
        window.open(fileURL); / if you want to open it in new tab

        }
    );

NOTE注意

It is also worth mentioning that if you are extending Http class to add headers to all your requests or something like that, it can also create problems for downloading PDF because you will override RequestOptions , which is where we add responseType: ResponseContentType.Blob and this will get you The request body isn't either a blob or an array buffer error.还值得一提的是,如果您要扩展Http类以向所有请求或类似内容添加headers ,它也会为下载 PDF 带来问题,因为您将覆盖RequestOptions ,这是我们添加responseType: ResponseContentType.Blob会让你The request body isn't either a blob or an array buffer错误。

ANGULAR 5角度 5

I had the same problem which I lost few days on that.我遇到了同样的问题,我在这方面失去了几天。

Here my answer may help others, which helped to render pdf.在这里,我的回答可能对其他人有所帮助,这有助于呈现 pdf。

For me even though if i mention as responseType : 'arraybuffer', it was unable to take it.对我来说,即使我提到 responseType : 'arraybuffer',它也无法接受。

For that you need to mention as responseType : 'arraybuffer' as 'json'.( Reference )为此,您需要提及 responseType : 'arraybuffer' 为 'json'。(参考

Working code工作代码

downloadPDF(): any {
    return this._http.get(url, {  responseType: 'blob' as 'json' }).subscribe((res) => {
        var file = new Blob([res], { type: 'application/pdf' });            
        var fileURL = URL.createObjectURL(file);
        window.open(fileURL);
    }
}

Referred from the below link来自以下链接

https://github.com/angular/angular/issues/18586 https://github.com/angular/angular/issues/18586

Amit, You can rename the filename by adding a variable to the end of the string so saveAs(res, "myPDF.pdf"); Amit,您可以通过在字符串末尾添加一个变量来重命名文件名,因此saveAs(res, "myPDF.pdf");

Becomes成为

saveAs(res, "myPDF_"+someVariable+".pdf");

where someVariable might be a counter or my personal favorite a date time string.其中 someVariable 可能是一个计数器或我个人最喜欢的日期时间字符串。

This worked for me这对我有用

 var req = this.getPreviewPDFRequest(fd);
        this.postData(environment.previewPDFRFR, req).then(res => {
          res.blob().then(blob => {
            console.clear();
            console.log(req);
            console.log(JSON.stringify(req));
            const fileURL = URL.createObjectURL(blob);
            window.open(fileURL, '', 'height=650,width=840');
          })
        });

Server side (Java/Jetty) : REST service that returns a File Response The File Response itself will automatically be parsed into a pdf blob file by Jetty (because of the annotation @Produces("application/pdf") ), in other to be send to and read by the web client服务器端(Java/Jetty):返回文件响应REST 服务文件响应本身将被 Jetty 自动解析为 pdf blob 文件(因为注释@Produces("application/pdf") ),在其他情况下发送到 Web 客户端并由其读取

    @GET
    @Path("/download-pdf/{id}")
    @Produces("application/pdf")
    public Response downloadPDF(@ApiParam(value = "Id of the report record")
                            @PathParam("id") Long id) {
        ResponseBuilder response = null;
        try {
            PDFReportService service = new PDFReportService();
            File reportFile = service.getPDFReportFile(id);

            response = Response.ok((Object) reportFile);  
            response.header("Content-Disposition","attachment; filename="+reportFile.getName());  
            return response.build();
        } catch (DomainException e) {
            response = Response.serverError().entity("server.error");
        }
        return response.build();
    }

Client side code (angular 2) : grab the blob and print it in a new browser tab客户端代码(角度 2):抓取 blob 并将其打印在新的浏览器选项卡中

The key is to insure that you read the request reponse as a blob (as the server returned a blob; in my case)关键是确保您将请求响应读取为 blob(因为服务器返回 blob;在我的情况下)

Now, I tried so hard but I finally figured out that Angular 2 has not implemented any function to handle blob responses (neither res['_body'] , nor res.blob() worked for me)现在,我非常努力,但我终于发现 Angular 2 没有实现任何函数来处理 blob 响应( res['_body']res.blob()都不适合我)

So I found no other workaround than using JQuery ajax to perform that file blob request, like following:所以我发现除了使用 JQuery ajax 执行该文件 blob 请求之外没有其他解决方法,如下所示:

public downloadPDFFile() {
    let fileURL = serverURL+"/download-pdf/"+id;
    let userToken: string = your_token;

    showWaitingLoader();

    $.ajax({
        url: fileURL,
        cache: false,
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Basic " + userToken
        },
        xhrFields: {
            responseType: 'blob' //Most important : configure the response type as a blob
        },
        success: function(blobFile) {
            const url = window.URL.createObjectURL(blobFile);
            window.open(url);
            stopWaitingLoader();
        },
        error: function(e){
            console.log("DOWNLOAD ERROR :", e);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM