php - 无法使用 FPDF 在 Php 中附加生成的 PDF

标签 php phpmailer fpdf

我正在使用 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();

最佳答案

您不清楚您使用的是哪个 Phpmailer 版本和哪个 FPDF 版本,因此很难说出确切的错误是什么。

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

$pdfString = $pdf->output();

如果打算让 $pdf->output() 返回一个字符串,那么调用在我看来是错误的。

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

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

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

PHP 是一种命令式语言,这意味着无论您是否将变量分配给返回值,它对方法调用都没有影响。

因此两个方法调用的行为相同:

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

这就像写作

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

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

潜在修复:

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

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

关于php - 无法使用 FPDF 在 Php 中附加生成的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68147986/

相关文章:

php - 语言字符串加载失败 : from_failed[from_email_address]

php - 使用 PHPMailer 为 Gmail API 格式化 MIME 消息时如何发送到 BCC 地址?

php - 在新标签页中从 FPDF 打开 PDF

php - 在设定的段落数后添加额外的广告

php - 拒绝获取不安全 header "Location"

php - 使用 PHPMailer 会导致许多电子邮件被阻止

php - 未定义字体 : In Fpdf. 如果我设置函数 __construct

php - 使用 "defined"ORM :s in PHP? 的优势

php - 无法在 html 中显示用户的详细数据(但可以使用 print_r() 显示数组) "codeigniter"

php - 动态pdf需要直接打开打印框