首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ng2-pdfjs-viewer的PDF结构无效

ng2-pdfjs-viewer的PDF结构无效
EN

Stack Overflow用户
提问于 2020-09-15 04:25:28
回答 1查看 914关注 0票数 1

我试图在ng2-pdfjs-viewer中加载PDF,但我得到“无效的PDF结构,未定义的错误”。后端将数据以Blob格式返回给我,但当我将数据提供给UI时,它给出了上面的错误:

HTML代码:

代码语言:javascript
复制
  <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代码:

代码语言:javascript
复制
  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();
  }

有人能帮帮忙吗?

EN

回答 1

Stack Overflow用户

发布于 2020-11-17 19:16:55

当我把pdf文件从我的node.js应用程序接口作为缓冲区发送到我的angular前端时,我也遇到了同样的问题。我最终以base64的形式将文件发送到了前端。在那里,我将base64字符串转换为ArrayBuffer。

例如我的api路由:

代码语言:javascript
复制
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文件:

代码语言:javascript
复制
@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文件中的视图子项访问查看器。

我的viewer.service.ts文件:

代码语言:javascript
复制
getPDF(fileAbsolutePath: string): Observable<any> {
    return this.http.get<any>(`${apiUrl}`?fileAbsolutePath=${fileAbsolutePath});
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63891389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档