【问题标题】:Invalid PDF Structure with ng2-pdfjs-viewerng2-pdfjs-viewer 的 PDF 结构无效
【发布时间】:2021-01-01 14:14:52
【问题描述】:

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

有人可以帮忙吗?

【问题讨论】:

    标签: javascript angular ng2-pdfjs-viewer


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-11-11
      • 1970-01-01
      • 2019-11-12
      • 2020-04-24
      • 2021-12-27
      • 2021-09-07
      • 2018-03-06
      • 2020-05-06
      • 2020-08-08
      相关资源
      最近更新 更多