我试图在ng2-pdfjs-viewer中加载PDF,但出现“无效的PDF结构,未定义的错误”。后端以Blob格式将数据返回给我,但是当我输入UI时,它会出现上述错误:
HTML代码:
<div class="mlp-flex-container mlp-flex-container--relative mlp-flex-item">
<div *ngIf="!showReport" class="informationMessage">Please Select a Trader</div>
<ng2-pdfjs-viewer *ngIf="showReport" #pdfViewer class="pdfViewer"></ng2-pdfjs-viewer>
</div>
JS代码:
private async getDataAsync(message: ReportGroupMessage) {
const rawData = await this.croDashboardPerformanceReportsDataService.getPerformanceReportsLocationDataAsync(message);
this.pdfViewer.pdfSrc = rawData;
this.pdfViewer.refresh();
}
public getPerformanceReportsLocationDataAsync(reportGroupMessage: ReportGroupMessage | any): Promise<any> {
debugger
const url = `Confidential URL`;
return this.http.get(url, { responseType: 'blob' })
.pipe(
map((result: any) => {
return result;
})
).toPromise();
}
有人可以帮忙吗?
答案 0 :(得分:1)
从node.js api发送pdf文件作为我的有角前端的缓冲区时,我遇到了同样的问题。最后,我将文件作为base64发送到了前端。在那里,我将base64字符串转换为ArrayBuffer。
例如我的api路线:
const fs = require('fs');
const fsPromises = fs.promises;
router.get("/", async (req, res) => {
try {
// Set absolute path
const fileAbsolutePath = req.query.fileAbsolutePath;
// Read file as base64 string
const base64Source = await fsPromises.readFile(fileAbsolutePath, { encoding: 'base64'});
return res.status(200).send({ pdf: base64Source.toString('utf-8') });
} catch (e) {
logger.error("Error while sending the PDF File: ", e);
return res.status(500).send(e.message);
}
});
我的component.ts文件:
@ViewChild('pdfViewer') public pdfViewer;
getPDFSource(fileAbsolutePath: string): void {
this.viewerService.getPDF(fileAbsolutePath).pipe(take(1)).subscribe(source => {
// Convert base64 to ArrayBuffer
const myBuffer = Uint8Array.from(atob(source.pdf), c => c.charCodeAt(0));
// Set the source of the pdf viewer
this.pdfViewer.pdfSrc = myBuffer;
// Refresh the pdf viewer
this.pdfViewer.refresh();
});
}
如here所述,您可以将base64字符串转换为ArrayBuffer。
在.html文件中,将ng2-pdfjs-viewer定义为模板变量,以通过.ts文件中的viewchild访问查看器。
我的viewer.service.ts文件:
getPDF(fileAbsolutePath: string): Observable<any> {
return this.http.get<any>(`${apiUrl}`?fileAbsolutePath=${fileAbsolutePath});
}