1

我正在尝试在 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();
  }

有人可以帮忙吗?

4

1 回答 1

1

将我的 pdf 文件从我的 node.js api 作为缓冲区发送到我的角度前端时,我遇到了同样的问题。我最终将文件作为 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();
    });
  }

如此处所述您可以将 base64 字符串转换为 ArrayBuffer。
在您的 .html 文件中,将 ng2-pdfjs-viewer 定义为模板变量,以通过 .ts 文件中的 viewchild 访问查看器。

我的 viewer.service.ts 文件:

getPDF(fileAbsolutePath: string): Observable<any> {
    return this.http.get<any>(`${apiUrl}`?fileAbsolutePath=${fileAbsolutePath});
  }
于 2020-11-17T11:16:54.863 回答