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

如何修复Angular应用中PDF文件的字体编码渲染空白问题

修复Angular中部分PDF转base64后渲染空白的问题

可能的问题根源

  • JSON存储/读取base64字符串时,可能出现字符转义(如+、/被转义)或内容截断
  • 原生atob无法处理URL安全格式的base64编码(部分PDF生成的base64会用-替代+、_替代/)
  • 手动循环转换Uint8Array的逻辑,在处理特殊编码字符或大文件时易出错

解决方案

1. 先清理并修复base64字符串

读取JSON后,先对base64字符串做标准化处理,确保格式合法:

function sanitizeBase64(base64: string): string {
  // 移除所有非base64有效字符(换行、空格等)
  base64 = base64.replace(/[^A-Za-z0-9+/=]/g, '');
  // 修复URL安全的base64编码
  base64 = base64.replace(/-/g, '+').replace(/_/g, '/');
  // 补全base64的padding位(如果缺失)
  const padding = 4 - (base64.length % 4);
  if (padding !== 4) {
    base64 += '='.repeat(padding);
  }
  return base64;
}

2. 替换更可靠的base64转Uint8Array逻辑

优化原有的转换代码,结合清理后的base64字符串使用:

function base64ToUint8Array(base64: string): Uint8Array {
  const sanitized = sanitizeBase64(base64);
  const binaryString = atob(sanitized);
  const byteArray = new Uint8Array(binaryString.length);
  
  // 直接遍历赋值,避免额外数组占用
  for (let i = 0; i < binaryString.length; i++) {
    byteArray[i] = binaryString.charCodeAt(i);
  }
  return byteArray;
}

3. 验证PDF数据有效性

赋值给PDF viewer前,先检查转换后的字节数组是否为合法PDF:

function isValidPdf(byteArray: Uint8Array): boolean {
  if (byteArray.length < 4) return false;
  // PDF文件固定以%PDF开头
  const header = new TextDecoder().decode(byteArray.subarray(0, 4));
  return header === '%PDF';
}

// 使用示例
const cleanedBase64 = sanitizeBase64(case.inputPdf);
const convertedBytes = base64ToUint8Array(cleanedBase64);

if (isValidPdf(convertedBytes)) {
  pdfviewer.pdfsrc = convertedBytes;
} else {
  console.error('当前base64编码不是有效的PDF数据');
}

4. 尝试改用Blob作为PDF源

部分PDF viewer组件对Blob的兼容性更好,可以直接将base64转为Blob使用:

async function base64ToBlob(base64: string): Promise<Blob> {
  const sanitized = sanitizeBase64(base64);
  const response = await fetch(`data:application/pdf;base64,${sanitized}`);
  return response.blob();
}

// 使用示例
base64ToBlob(case.inputPdf).then(blob => {
  pdfviewer.pdfsrc = blob;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:57:20