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

Angular中点击按钮预览PDF:基于Base64数据预览时出现空白页的问题求助

Fixing Blank PDF Preview with Base64 Data in Angular

Hey there! I see exactly where the issue is—you’re passing the raw Base64 string directly into the Blob constructor, which leaves the browser with text data instead of the actual binary PDF content it needs to render. That’s why your preview is blank and the blob URL looks off. Let’s fix this step by step.

The Root Problem

Base64 is a text-based encoding of binary data. When you create a Blob with the raw Base64 string, you’re telling the browser to treat that text as the file content—not the decoded binary PDF data required for proper rendering.

Corrected Code

First, we need to decode the Base64 string into binary data, then create the Blob from that valid binary source:

// 1. Strip any Base64 prefix if present (like "data:application/pdf;base64,")
const cleanBase64 = this.byte64String.split(';base64,').pop();

// 2. Decode the Base64 string to binary format
const decodedBinary = atob(cleanBase64);

// 3. Convert decoded binary to Uint8Array (the format Blob expects for binary files)
const uint8Array = new Uint8Array(decodedBinary.length);
for (let i = 0; i < decodedBinary.length; i++) {
  uint8Array[i] = decodedBinary.charCodeAt(i);
}

// 4. Create the Blob with proper PDF binary data
const pdfBlob = new Blob([uint8Array], { type: 'application/pdf' });

// 5. Generate the valid blob URL for preview
this.pdfSourceUrl = URL.createObjectURL(pdfBlob);

Template Usage

Make sure your template uses the URL correctly—an iframe is a reliable choice for inline PDF previews:

<iframe 
  [src]="pdfSourceUrl" 
  width="100%" 
  height="600px"
  title="PDF Preview"
></iframe>

Key Tips

  • Always strip the data:application/pdf;base64, prefix from your Base64 string first—this is a super common gotcha that breaks decoding!
  • Add cleanup logic to your component to free up memory when you’re done with the preview:
    ngOnDestroy() {
      if (this.pdfSourceUrl) {
        URL.revokeObjectURL(this.pdfSourceUrl);
      }
    }
    

That should get your PDF rendering properly instead of showing a blank page. Let me know if you hit any other snags!

内容的提问来源于stack exchange,提问作者Mujtaba Hussain Bhat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 02:07:41