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

Cordova Android应用渲染Web服务返回的Base64编码PDF最简方案

最简实现方案:无需额外插件

嘿,这个需求我刚好做过,完全不需要额外的Cordova插件就能搞定,核心就是利用Cordova WebView本身支持的HTML5特性(Blob、Object URL)来处理,步骤超清晰:

核心思路

  1. 从Web服务获取Base64编码的PDF字符串
  2. 清理Base64内容(移除可能存在的data:application/pdf;base64,前缀)
  3. 将Base64转换为Blob对象
  4. 生成Object URL,通过window.open打开或嵌入iframe展示

完整示例代码

1. 基础版:在新窗口打开PDF

async function fetchAndDisplayPdf() {
  try {
    // 1. 调用接口获取Base64 PDF(替换成你的实际接口地址)
    const apiResponse = await fetch('https://your-api-endpoint/get-pdf-base64');
    let base64Content = await apiResponse.text();

    // 2. 清理Base64前缀(如果接口返回带前缀的话)
    base64Content = base64Content.replace(/^data:application\/pdf;base64,/, '');

    // 3. Base64转Blob
    const decodedBytes = atob(base64Content);
    const byteArray = new Uint8Array(decodedBytes.length);
    for (let i = 0; i < decodedBytes.length; i++) {
      byteArray[i] = decodedBytes.charCodeAt(i);
    }
    const pdfBlob = new Blob([byteArray], { type: 'application/pdf' });

    // 4. 生成可访问的URL并打开
    const pdfUrl = URL.createObjectURL(pdfBlob);
    // Cordova中_blank会调用系统默认浏览器/PDF查看器,location=yes显示地址栏
    window.open(pdfUrl, '_blank', 'location=yes');

    // 5. 延迟释放URL,避免内存泄漏
    setTimeout(() => {
      URL.revokeObjectURL(pdfUrl);
    }, 15000); // 给足够时间让PDF加载完成
  } catch (error) {
    console.error('PDF加载失败:', error);
    alert('无法加载PDF,请检查网络或稍后重试');
  }
}

2. 进阶版:在页面内嵌入iframe展示

如果不想跳转到新窗口,也可以用iframe嵌入到当前页面:

<!-- 在你的HTML中添加iframe容器 -->
<div style="width:100%; height:80vh;">
  <iframe id="pdfIframe" width="100%" height="100%" frameborder="0"></iframe>
</div>

修改JavaScript部分的展示逻辑:

// 替换window.open的代码为:
const pdfIframe = document.getElementById('pdfIframe');
pdfIframe.src = pdfUrl;

关键注意事项

  • Base64格式校验:确保接口返回的是纯Base64字符串,没有多余的空格、换行或其他字符,否则转换Blob会失败。
  • Cordova配置:如果window.open没有正常弹出,可以在config.xml中添加配置:
    <preference name="AllowInlineMediaPlayback" value="true" />
    <preference name="OpenAllWindowsInWebView" value="false" />
    
    前者允许内嵌媒体,后者让外部链接调用系统浏览器(适合打开PDF)。
  • 内存管理:一定要调用URL.revokeObjectURL释放资源,否则长时间使用会导致WebView内存占用过高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:24:55