【问题标题】:Blank pdf attachment while sent using FPDF and SwiftMailer使用 FPDF 和 SwiftMailer 发送时的空白 pdf 附件
【发布时间】:2014-06-15 15:32:49
【问题描述】:

我正在尝试使用 FPDF 库创建 PDF 流,并使用 Swift Mailer 通过电子邮件发送 pdf。下面是我的代码。邮件发送成功,甚至还附加了pdf,但pdf的大小为零,因此无法打开。当我使用 $pdf->Output('receipt.pdf', 'D') 下载 pdf 时,它成功并且 PDF 的内容也存在。有人可以帮我确定我是否做错了什么吗?或者我是否需要在消息中设置一些额外的字段,以便它能够正确发送 PDF。我搜索了所有与 FPDF 和 swiftmailer 相关的帖子,但在我的代码中找不到问题。

$pdf = new FPDF();
$pdf->AddPage();
$pdf->Text(80, 30, "Dummy text");
$pdfstream = $pdf->Output('receipt.pdf', 'S');
$attachment = Swift_Attachment::newInstance($pdfstream, 'name.pdf', 'application/pdf');

$message = Swift_Message::newInstance('Dummy subject')
    ->setFrom(array("abc@xyz.com" => 'XYZ'))
    ->setTo('pqr@abc.com')
    ->setBody('Dummy body text');

$message->attach($attachment);

$transport = Swift_MailTransport::newInstance();

$mailer = Swift_Mailer::newInstance($transport);

$result = $mailer->send($message);

编辑 1: 下面对我来说工作得很好。请注意,我使用了两个外部库 SwiftMailer 和 FPDF,所以你需要做一些必要的事情,比如导入等才能使它们工作。

$pdf = new FPDF();
$pdf->AddPage();
$pdf->Text(80, 30, "Dummy text");
$data=$pdf->Output('receipt.pdf', 'S');

$message = Swift_Message::newInstance('Subject')
    ->setFrom(array("Geoff" => 'abc@xyz.com'))
    ->setTo('xyz@abc.com')
    ->setBody('This is body text', 'text/html');    
if(!empty($data))
{
  $attachment = Swift_Attachment::newInstance($data, 'pdf_name.pdf', 'application/pdf');
  $message->attach($attachment);
}
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);

【问题讨论】:

    标签: php pdf fpdf swiftmailer


    【解决方案1】:

    试试这个:

    $pdfstream = $pdf->Output('receipt.pdf', 'S');
    
    $emailStream = 'Content-Type: application/pdf;'."\r\n";
    $emailStream.= ' name="name.pdf"'."\r\n";
    $emailStream.= 'Content-Transfer-Encoding: base64'."\r\n";
    $emailStream.= 'Content-Disposition: attachment;'."\r\n";
    $emailStream.= ' filename="name.pdf"'."\r\n\r\n";
    $emailStream.= chunk_split(base64_encode($pdfstream), 76, "\r\n");
    
    $attachment = Swift_Attachment::newInstance($emailStream, 'name.pdf', 'application/pdf');
    

    【讨论】:

    • 感谢 MonkeyZeus。实际上编码是由 SwiftMailer 在内部完成的,所以不需要明确的。但是在尝试这个时,我意识到我在我的代码中使用了错误的变量,这就是它生成空白 pdf 的原因。无论如何感谢您的建议。
    • @Mandar 究竟是什么错误的变量。我想做类似的事情并尝试了您的代码,但它仍然存在错误。你能提供一个更正的版本吗?
    • @Geoff 用答案编辑了我的问题。让我知道您面临的具体问题。
    • @Geoff 我不知道你的代码是什么样的。如果您需要本网站的帮助,您应该在 StackOverflow 上创建一个新问题并发布代码示例。
    • @MonkeyZeus 我听取了您的建议,并在link 提出了另一个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    相关资源
    最近更新 更多