【问题标题】:Not able to attach the generated PDF in Php using FPDF无法使用 FPDF 在 PHP 中附加生成的 PDF
【发布时间】:2021-06-27 04:28:40
【问题描述】:

我正在使用 FPDF 和 Phpmailer 生成 PDF 文件并将其作为电子邮件附件发送。

当我将它们用作独立脚本时,我的 PDF 生成脚本和 phpmailer 运行良好。

现在,当我结合这两个脚本来生成和显示 PDF 表单(不将其保存到文件系统)并将此 PDF 文档作为附件发送时,它无法生成 PDF 并将其显示在浏览器上,但不通过邮件发送。

我的代码是:

<?php declare(strict_types=1);

use PHPMailer\PHPMailer\PHPMailer;

require 'vendor/autoload.php';

$pdf = new mypdf();
$pdf->AliasNbPages();
$pdf->AddPage('P', 'A4', 0);
$pdf->Header();
$pdf->headerTable();
$pdf->viewTable();
$pdf->footer();
$pdf->setMargins(20, 20, 20);
$pdf->output();
$pdfString = $pdf->output();

$mail = new PHPMailer;

// getting post values
$first_name = $_POST['fname'];
$to_email = "receipent@gmail.com";
$subject = "stationery issued";
$message = "Dear sir your requested stationery has been issued by Stationery store ";
$mail->isSMTP();                      // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';       // Specify main and backup SMTP servers
$mail->SMTPAuth = true;               // Enable SMTP authentication
$mail->Username = 'sender@gmail.com'; // SMTP username
$mail->Password = 'password';         // SMTP password
$mail->SMTPSecure = 'tls';            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;                     // TCP port to connect to
$mail->setFrom('sender@gmail.com', 'Your_Name');
$mail->addReplyTo('sender@gmail.com', 'Your_Name');
$mail->addAddress($to_email);         // Add a recipient
$mail->addStringAttachment((string)$pdfString, 'name file.pdf');
$mail->isHTML(true);                  // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = 'Dear ' . $first_name . '<p>' . $message . '</p>';

$mail->send();

【问题讨论】:

    标签: php phpmailer fpdf


    【解决方案1】:

    您不清楚您使用的是哪个 Phpmailer 版本以及哪个 FPDF 版本,因此很难说到底是什么错误。

    乍一看,这引起了我的注意:

    $pdfString = $pdf->output();
    

    如果打算让$pdf-&gt;output() 返回一个字符串,那么调用对我来说是错误的。

    那是因为$pdf-&gt;output() 的调用正在执行默认输出,即发送到浏览器。

    你说的有效,那已经是上面的那行了:

    $pdf->output();
    $pdfString = $pdf->output();
    

    PHP 是一种命令式语言,也就是说,无论您是否将变量分配给返回值,它都不会影响方法调用。

    所以两个方法调用的行为都是一样的:

    $pdf->output();
    $pdfString = $pdf->output();
    

    这就像写作

    $pdf->output();
    $pdf->output();
    

    也许只是调试过程中的疏忽。对于调试,请尽早检查前提条件,逐步验证您的脚本。不要问超过五分钟。那就验证一下吧。

    可能的修复:

    $pdfString = $pdf->output('S');
    

    可以这样做,最好查看您手头的文档以了解您正在使用的版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 2011-04-04
      相关资源
      最近更新 更多