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

能否用PHP将PDF编码进JSON并通过AJAX返回?求实现方法

解决方案

核心思路:将PDF文件编码为Base64字符串嵌入JSON返回

由于后端只能返回JSON,可让后端把PDF文件内容转换成Base64编码的字符串,放在JSON的指定字段(比如pdf_content)中,前端拿到后解码还原成PDF文件,即可实现查看和下载。

后端PHP处理示例(无需修改现有JSON入参/返回的核心规则)

// 假设已获取到PDF文件路径
$pdfPath = '/path/to/target.pdf';
$pdfContent = file_get_contents($pdfPath);
$base64Pdf = base64_encode($pdfContent);

// 保持原有JSON返回结构,新增字段携带Base64编码的PDF
echo json_encode([
    'code' => 200,
    'msg' => 'success',
    'pdf_content' => $base64Pdf,
    'filename' => 'report.pdf' // 可选:返回文件名用于前端下载命名
]);

前端处理方案(AJAX请求后解码并实现查看/下载)

1. 下载功能实现

// 假设AJAX请求成功后拿到response数据
function downloadPdf(response) {
    // 解码Base64字符串
    const byteChars = atob(response.pdf_content);
    const byteNums = new Array(byteChars.length);
    for (let i = 0; i < byteChars.length; i++) {
        byteNums[i] = byteChars.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNums);
    const pdfBlob = new Blob([byteArray], { type: 'application/pdf' });
    
    // 创建下载链接并触发下载
    const link = document.createElement('a');
    link.href = URL.createObjectURL(pdfBlob);
    link.download = response.filename || 'download.pdf';
    link.click();
    URL.revokeObjectURL(link.href); // 释放URL对象内存
}

2. 在线查看功能实现

可使用浏览器内置PDF查看器,或嵌入到页面中:

function viewPdf(response) {
    // 解码Base64字符串生成Blob
    const byteChars = atob(response.pdf_content);
    const byteNums = new Array(byteChars.length);
    for (let i = 0; i < byteChars.length; i++) {
        byteNums[i] = byteChars.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNums);
    const pdfBlob = new Blob([byteArray], { type: 'application/pdf' });
    const pdfUrl = URL.createObjectURL(pdfBlob);
    
    // 方式1:打开新窗口查看
    window.open(pdfUrl);
    
    // 方式2:嵌入到页面iframe中
    // const iframe = document.createElement('iframe');
    // iframe.src = pdfUrl;
    // iframe.style.width = '100%';
    // iframe.style.height = '800px';
    // document.getElementById('pdf-container').appendChild(iframe);
}

注意事项

  • Base64编码会使文件体积增加约30%,若PDF文件过大,需确认服务器内存配置足够读取文件,且前端能正常处理大字符串。
  • 确保后端返回的JSON中pdf_content字段未被截断,PHP的json_encode默认支持长字符串,但需留意服务器memory_limit设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 03:32:44