Angular 6,打开并下载 PDF,生产中的问题 [英] Angular 6, Open and Download PDF, Issue in Production

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

问题描述

我正在尝试在 Angular 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天全站免登陆