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

如何将jsPDF生成的PDF自动保存到服务器并通过PHP发送邮件?

解决方案:将生成的PDF上传至服务器并通过PHP发送邮件

你的当前代码已经能成功生成PDF并触发下载,要实现自动保存到服务器+发送邮件的需求,我们需要把前端生成的PDF数据发送到后端PHP处理,而不是直接在浏览器触发下载。下面分两步来实现:

一、修改前端代码:将PDF数据发送到后端

原来的pdf.save('output.php')会触发浏览器下载,我们需要替换这部分逻辑,把生成的PDF转为Blob,然后通过AJAX发送到你的PHP接口:

function makePDF() {
    var quotes = document.getElementById('container-fluid');
    html2canvas(quotes, {
        onrendered: function(canvas) {
            var pdf = new jsPDF('p', 'pt', 'letter');
            for (var i = 0; i <= quotes.clientHeight/980; i++) {
                var srcImg = canvas;
                var sX = 0;
                var sY = 1278*i;
                var sWidth = 990;
                var sHeight = 1278;
                var dX = 0;
                var dY = 0;
                var dWidth = 990;
                var dHeight = 1278;
                window.onePageCanvas = document.createElement("canvas");
                onePageCanvas.setAttribute('width', 990);
                onePageCanvas.setAttribute('height', 1278);
                var ctx = onePageCanvas.getContext('2d');
                ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);
                var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);
                var width = onePageCanvas.width;
                var height = onePageCanvas.clientHeight;
                
                if (i > 0) {
                    pdf.addPage(612, 791);
                }
                pdf.setPage(i+1);
                pdf.addImage(canvasDataURL, 'PNG', 0, 0, (width*.62), (height*.62));
            }

            // 关键修改:生成Blob并发送到PHP后端
            var pdfBlob = pdf.output('blob');
            var formData = new FormData();
            formData.append('pdf_file', pdfBlob, 'output.pdf'); // 文件名可自定义

            // 使用fetch发送请求
            fetch('save_and_email.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(result => {
                console.log('操作完成:', result);
                // 这里可以添加成功后的提示,比如alert('PDF已保存并发送邮件!')
            })
            .catch(error => {
                console.error('错误:', error);
                alert('生成或发送过程中出现错误');
            });
        }
    });
}

二、创建PHP后端脚本(save_and_email.php)

这个脚本负责接收前端传来的PDF文件,保存到uploads/pdfs/目录,然后发送邮件(带PDF附件):

<?php
// 1. 设置保存目录并确保存在
$uploadDir = 'uploads/pdfs/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true); // 递归创建目录,设置合适的权限
}

// 2. 接收上传的PDF文件
if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === UPLOAD_ERR_OK) {
    $fileName = uniqid() . '_' . $_FILES['pdf_file']['name']; // 添加唯一前缀避免重名
    $filePath = $uploadDir . $fileName;

    // 移动临时文件到目标目录
    if (move_uploaded_file($_FILES['pdf_file']['tmp_name'], $filePath)) {
        echo "PDF已成功保存到: " . $filePath . "\n";

        // 3. 发送带附件的邮件
        $to = 'recipient@example.com'; // 替换为实际收件人邮箱
        $subject = '生成的PDF文档';
        $message = '您好,这是您请求生成的PDF文档,请查收附件。';
        $headers = 'From: sender@example.com' . "\r\n" .
                   'Reply-To: sender@example.com' . "\r\n" .
                   'X-Mailer: PHP/' . phpversion();

        // 处理邮件附件(使用PHP内置mail函数,也可以用PHPMailer更可靠)
        $boundary = md5(time());
        $headers .= "\r\nMIME-Version: 1.0\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";

        $body = "--{$boundary}\r\n";
        $body .= "Content-Type: text/plain; charset=UTF-8\r\n";
        $body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
        $body .= $message . "\r\n\r\n";

        // 添加PDF附件
        $fileContent = file_get_contents($filePath);
        $encodedContent = chunk_split(base64_encode($fileContent));
        $body .= "--{$boundary}\r\n";
        $body .= "Content-Type: application/pdf; name=\"{$fileName}\"\r\n";
        $body .= "Content-Disposition: attachment; filename=\"{$fileName}\"\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= $encodedContent . "\r\n\r\n";
        $body .= "--{$boundary}--";

        // 发送邮件
        if (mail($to, $subject, $body, $headers)) {
            echo "邮件已成功发送!";
        } else {
            echo "邮件发送失败,请检查服务器邮件配置。";
        }
    } else {
        echo "保存PDF文件失败,请检查目录权限。";
    }
} else {
    echo "未接收到有效的PDF文件。";
}
?>

注意事项

  • 目录权限:确保uploads/pdfs/目录有写入权限(通常设置为755或775),否则无法保存文件。
  • 邮件配置:如果使用PHP内置的mail()函数,需要服务器已正确配置邮件服务(如Sendmail、Postfix)。如果遇到发送问题,推荐使用PHPMailer库,它更稳定且支持SMTP(比如Gmail、企业邮箱)。
  • 文件名唯一性:代码中用uniqid()添加前缀,避免多个用户生成的PDF重名覆盖。
  • 前端反馈:可以在fetch的then回调中添加用户提示,比如告知用户操作成功或失败。

内容的提问来源于stack exchange,提问作者Muhammad Ahsan Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:50:29