我从REST服务器收到PDF文件的base64字符串。我希望PDF显示在窗口中。但是我在创建URL时遇到问题。生成的invoicePdfURL如下所示:
blob:https://localhost:4200/dc391fef-25fb-4dcf-921b-779384182920
我可以控制REST服务器,并且可以让它返回任何合适的东西。在这个例子中,它返回一个base64字符串,我也让它返回一个byte [],但是有同样的问题。
编写此代码的正确方法是什么?
此处为component.ts:
public invoicePdfURL: SafeResourceUrl;
...
public getInvoicePDF() {
this.invoiceService.getInvoicePDF(this.rowID)
.subscribe( base64Data => {
const byteArray = new Uint8Array(atob(base64Data).split('').map(char => char.charCodeAt(0)));
const binaryData = [];
binaryData.push(byteArray);
const blob = new Blob(binaryData, {type: "application/pdf"});
this.invoicePdfURL = this.domSanitizer.sanitize(SecurityContext.HTML,
this.domSanitizer.bypassSecurityTrustHtml(URL.createObjectURL(blob)));
console.log("this.invoicePdfURL: " +this.invoicePdfURL);
});
}
此处为component.html:
<button class="btn btn-danger pull-left" onclick="window.open('{{invoicePdfURL}', '_blank')">
<i class="fa fa-download"></i> Download PDF
</button>
答案 0 :(得分:0)
blob URL是正确的,问题出在我试图将其传递给component.html的方式中。我通过注入html来修复它,如下所示。我还重构了component.ts。
component.ts:
public getInvoicePDF() {
this.invoiceService.getInvoicePDF(this.rowID)
.subscribe( base64Data => {
const byteArray = new Uint8Array(atob(base64Data).split('').map(char => char.charCodeAt(0)));
const blob = new Blob([byteArray], {type: 'application/pdf'});
this.invoicePdfURL = URL.createObjectURL(blob);
this.downloadPdfHTML =
`
<button class="btn btn-danger pull-left" onclick="window.open('` +this.invoicePdfURL +`', '_blank')">
<i class="fa fa-download"></i> Download PDF
</button>
`;
});
}
component.html:
<div [innerHTML]="downloadPdfHTML | safeurl: 'html'"></div>