Angular 6,打开和下载PDF,已发行

时间:2019-03-14 09:07:20

标签: angular angular6

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

显示:“无法加载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');
   }
   );
}

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

1 个答案:

答案 0 :(得分:0)

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

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);
});