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

Angular打印PDF时遇Type 'string | null'无法赋值给string错误求助

Angular打印PDF时iframe.src类型错误解决办法

问题

用Angular打印PDF时,设置iframe.src这行代码报错:

Type 'string | null' is not assignable to type 'string'.

相关代码:

this.myService.printPages(shareFilter)
.subscribe((result: any) => {

  const pdf = new Blob([result], { type: 'application/pdf' });
  const blobUrl = URL.createObjectURL(pdf);
  const iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  iframe.src = this.sanitizer.sanitize(SecurityContext.RESOURCE_URL, this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl));
  document.body.appendChild(iframe);
  iframe.contentWindow.print();
  }
)

原因

sanitizer.sanitize()方法返回的是string | null类型,但iframe.src只接受string类型,TypeScript的类型校验不允许这种赋值,所以触发了错误。

解决方法

方法1:非空断言(快速解决)

在sanitize()调用后加!,明确告诉TypeScript这个值肯定不为null:

iframe.src = this.sanitizer.sanitize(SecurityContext.RESOURCE_URL, this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl))!;

方法2:空值检查(更严谨)

先判断返回值是否有效,再执行后续操作,避免空值隐患:

this.myService.printPages(shareFilter)
.subscribe((result: any) => {

  const pdf = new Blob([result], { type: 'application/pdf' });
  const blobUrl = URL.createObjectURL(pdf);
  const safeUrl = this.sanitizer.sanitize(SecurityContext.RESOURCE_URL, this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl));
  
  if (safeUrl) {
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = safeUrl;
    document.body.appendChild(iframe);
    iframe.contentWindow.print();
  } else {
    console.error('PDF URL验证失败,无法打印');
    // 这里可以添加用户提示逻辑
  }
})

额外优化

打印完成后记得清理Blob URL和iframe,防止内存泄漏:

iframe.contentWindow.onafterprint = () => {
  document.body.removeChild(iframe);
  URL.revokeObjectURL(blobUrl);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:54:17