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

Angular 18集成ng2-pdf-viewer报错:document is not defined

Angular 18 中使用 ng2-pdf-viewer 出现 "document is not defined" 错误的解决方法

这个错误源于 Angular 18 默认启用服务端渲染(SSR),而 pdfjs-dist(ng2-pdf-viewer 的依赖)依赖浏览器环境的 document 对象,服务端渲染阶段无法访问该对象,因此触发报错。

以下是几种可行的解决方法:

方案1:禁用服务端渲染(快速修复)

修改 angular.json 配置,移除 SSR 相关内容:

  • 找到 projects -> [你的项目名称] -> architect -> server 节点,删除整个 server 配置块
  • 删除 projects -> [你的项目名称] -> architect -> build -> configurations -> production -> serverTarget 配置项
  • 重启项目:ng serve

方案2:仅在浏览器环境渲染 PDF 组件(推荐保留 SSR 的场景)

借助 Angular 的 isPlatformBrowser 工具,确保 PDF 组件只在浏览器端加载:

  1. 更新组件代码:
import { Component, OnInit, PLATFORM_ID, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { PdfViewerModule } from 'ng2-pdf-viewer';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, PdfViewerModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent implements OnInit {
  title = 'viewer';
  isBrowser = false;
  private platformId = inject(PLATFORM_ID);

  ngOnInit(): void {
    this.isBrowser = isPlatformBrowser(this.platformId);
  }
}
  1. 调整模板添加条件渲染:
<ng-container *ngIf="isBrowser">
  <pdf-viewer
    [src]="'https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf'"
    [rotation]="0"
    [original-size]="false"
    [show-all]="true"
    [fit-to-page]="false"
    [zoom]="1"
    [zoom-scale]="'page-width'"
    [stick-to-page]="false"
    [render-text]="true"
    [external-link-target]="'blank'"
    [autoresize]="true"
    [show-borders]="false"
    style="width: 100%; height: 100vh;"
  ></pdf-viewer>
</ng-container>

方案3:调整 ng2-pdf-viewer 版本

检查当前版本是否兼容 Angular 18,尝试安装最新兼容版本:

npm install ng2-pdf-viewer@latest

若最新版本仍有问题,可降级到已知兼容 Angular 18 的版本(参考包的更新日志确认具体版本)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 16:20:03