You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic 5 Angular项目中ng2-pdf-viewer无法正常显示PDF问题求助

修复方案

1. 修正异步逻辑执行顺序

你当前代码中getLivre是HTTP异步请求,ngOnInit中调用完getLivre后立刻执行ouvrirPDF、渲染pdf-viewer时,pdfSrc还未完成赋值,会导致资源加载失败。
修改lecture.page.ts的异步逻辑:

ngOnInit() {
  this.route.paramMap.subscribe(params=>{
    this.id=+params.get('id');
    this.getLivre();
    // 移除此处的ouvrirPDF调用,挪到getLivre的回调里
  });
}
 
getLivre(){
  this.http.get(this.url+"api/livre/"+this.id)
  .subscribe((res:any)=>{
    this.livre=res;
    this.pdfSrc=this.url+"app/public/doc_livre/"+this.livre.lien_livre;
    // 确认pdfSrc赋值完成后,再执行PDF相关操作
    this.ouvrirPDF();
  })
}

2. 修正模块配置错误

Ionic原生插件(File/FileTransfer/DocumentViewer)属于服务类依赖,不能放在imports数组中,需要放到providers数组里,否则会触发依赖注入报错导致页面异常。
修改lecture.module.ts配置:

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    PdfViewerModule,
    HttpClientModule,
    LecturePageRoutingModule
  ],
  declarations: [LecturePage,MenuComponent],
  // 新增providers数组,放入原生插件
  providers: [
    File,
    FileTransfer,
    DocumentViewer
  ]
})
export class LecturePageModule {}

3. 给pdf-viewer设置明确宽高

ng2-pdf-viewer默认没有固定高度,未设置高度时组件高度为0,无法正常渲染PDF内容。
修改lecture.page.html中的组件配置:

<pdf-viewer [src]="pdfSrc"
      [render-text]="true"
      style="display: block;width: 100%;height: 80vh;"
      *ngIf="pdfSrc"
></pdf-viewer>

新增*ngIf判断是为了避免pdfSrc未赋值时组件初始化报错。

4. 按需选择PDF渲染方案

你当前代码同时使用了两种PDF浏览方案:

  • 内嵌渲染:用ng2-pdf-viewer在应用内直接显示PDF
  • 原生调用:用DocumentViewer调用系统默认PDF应用打开文件
    如果需要使用内嵌渲染的方案,直接删除ouvrirPDF()的调用即可,否则会触发页面跳转,无法看到内嵌的PDF内容。

其他排查点

  • 如果你的PDF资源地址是HTTP协议,Android 9及以上系统默认禁止HTTP明文请求,需要在AndroidManifest.xml中配置android:usesCleartextTraffic="true"
  • 后端需要配置CORS规则,允许前端域名请求PDF资源,否则会触发跨域拦截导致加载失败
  • 确认ng2-pdf-viewer版本和项目的Angular版本兼容,Ionic 5对应Angular 11/12版本,建议使用ng2-pdf-viewer@8.x版本

内容的提问来源于stack exchange,提问作者KarterGo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:06:04