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

在WordPress中用jQuery Ajax调用DOMPDF下载PDF出现空白页求助

WordPress下Ajax调用DOMPDF生成空白PDF的解决方法

问题根源

  1. 编码不匹配:Ajax默认以文本格式接收响应,PDF是二进制数据,直接将文本转Blob会导致内容乱码损坏。
  2. 额外输出干扰:generatepdf.php中可能存在空格、PHP警告或WordPress默认输出,破坏了PDF的二进制结构。

解决方案

1. 修改Ajax请求(test.php)

给Ajax请求添加responseType: 'blob',直接接收二进制Blob数据,无需手动转换:

$(document).ready(function() {
    $('#generatePdfButton').click(function() {
        $.ajax({
            url: 'generatepdf.php',
            type: 'GET',
            xhrFields: {
                responseType: 'blob' // 关键:指定接收二进制Blob
            },
            success: function(blob) {
                var url = window.URL.createObjectURL(blob);
                var link = document.createElement('a');
                link.href = url;
                link.download = 'test.pdf';
                link.click();
                window.URL.revokeObjectURL(url);
            },
            error: function(xhr, status, error) {
                console.error('生成PDF失败:', error);
            }
        });
    });
});

2. 修正generatepdf.php代码

确保脚本只输出PDF二进制内容,清空所有额外输出:

<?php
// 禁止WordPress输出任何额外内容
ob_start();
@ini_set('display_errors', 0);

// 引入DOMPDF(根据你的实际安装路径调整)
require_once ABSPATH . 'wp-content/plugins/your-plugin/dompdf/autoload.inc.php';
use Dompdf\Dompdf;

// 实例化DOMPDF
$dompdf = new Dompdf();

// 定义要渲染的HTML内容(可动态从WordPress获取,比如文章内容)
$html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>测试PDF文档</title>
</head>
<body>
    <h1>PDF内容标题</h1>
    <p>这是正常显示的PDF正文内容</p>
</body>
</html>';

// 加载HTML并渲染
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

// 清空缓冲区,确保无额外输出
ob_clean();
flush();

// 设置正确的HTTP响应头
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="test.pdf"');

// 输出PDF内容
echo $dompdf->output();
exit; // 终止脚本,阻止WordPress后续输出
?>

额外注意事项

  • 确认DOMPDF的路径正确,在WordPress中建议使用ABSPATH常量定位文件,避免路径错误。
  • 检查generatepdf.php文件开头是否有空格、换行符,这些会被当成额外输出破坏PDF结构。
  • 确保DOMPDF有读写临时文件的权限,否则可能无法生成PDF内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:12:46