Angular 6,打开并下载PDF,已发行 [英] Angular 6, Open and Download PDF, Issue in Production

查看:311
本文介绍了Angular 6,打开并下载PDF,已发行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在角度Web应用程序中打开以及下载PDF.该代码在开发时可以正常工作,并在angular应用上获取PDF.但是在为生产和部署进行构建时,这是行不通的.

I am trying to open as well as download PDF in angular web application. the code works fine while development and gets the PDF on angular app. But the same doesn't work while build for production and deployed.

显示:无法加载PDF文档"

代码如下:

Service.ts

export(pdfName) {
 const httpOptions = {'responseType': 'arraybuffer' as 'json'};
 return this.http.get<any>(environment.apiBaseUrl + '/download?path='+policyPath,
                           httpOptions);
 }

Component.ts

GetDocument(pdfName:any)
{
 this.service.export(pdfName)
 .subscribe((data) =>
   {
     window.open(URL.createObjectURL(new Blob([data], {type: 'application/pdf'})),'Popup', 'height=700px,width=900px,scrollbars=1,')
     console.log(data);
   }
   ,(error)=>{
     var res= JSON.parse(JSON.stringify(error));
     console.log(res);
     this.alertService.warn("Resource "+res.statusText);
     $('#alertModel').modal('show');
   }
   );
}

同样:此代码可以按开发要求正常运行.仅当部署到生产中时才会产生问题.

Again: this code works fine as required in development. Produces issues only when deployed to production.

推荐答案

在我之前的项目中,只有这种方法对我而言是完美的

In my previous project only this approach worked flawlessly for me

getOrderPdf(id: string): Observable<ArrayBuffer> {
  return this.http
    .get(environment.api + "/orders/" + id + "/pdf", {
      responseType: "arraybuffer",
      headers: {
        Accept: "application/pdf"
      }
    });
}

printOrder() {
  this.ordersService
    .getOrderPdf(this.order._id)
    .pipe(take(1))
    .subscribe(blob => {
      var newBlob = new Blob([blob], { type: "application/pdf" });

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(newBlob);
        return;
      }

      const data = window.URL.createObjectURL(newBlob);
      var link = document.createElement("a");
      link.href = data;
      link.download = "Order No " + this.order.number + ".pdf";
      link.click();

      setTimeout(() => {
        window.URL.revokeObjectURL(data);
      }, 100);
    }, err => {})
}

服务器端:

import * as pdf from "html-pdf";

const template = pug.renderFile(
  path.join(__dirname, "template/print.pug"),
  { order: order }
);

pdf.create(template).toBuffer((err, buffer) => {
  if (err) {
    logger.error(JSON.stringify(err));
    return res.sendStatus(500);
  }
  res.setHeader("Content-type", "application/pdf");
  res.send(buffer);
});

这篇关于Angular 6,打开并下载PDF,已发行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆