问题
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.
Shows: "Failed to load PDF document"
Code as below:
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.
回答1:
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 => {})
}
Server side:
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);
});
来源:https://stackoverflow.com/questions/55158582/angular-6-open-and-download-pdf-issue-in-production