0

我想生成一个 PDF 文件并使用 Swift Mailer 和 knp-snappy-bundle 将其作为附件发送到电子邮件中。问题是它只生成和下载 PDF 文件而不渲染模板。我希望它同时生成 PDF 和渲染模板。

代码:

public function viewPostAction() {
  $html = "Just a sample text to produce the PDF";

  return new Response(
    $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
    200,
    array(
      'Content-Type'          => 'application/pdf',
      'Content-Disposition'   => 'attachment; filename="classement.pdf"'
    )
  );
  $message = \Swift_Message::newInstance()
    ->setSubject('Some Subject')
    ->setFrom('test@gmail.com')
    ->setTo('test@gmail.com')
    ->setBody("test email")
    ->attach(Swift_Attachment::fromPath('C:\Users\acer\Downloads\classement.pdf'));

  # Send the message
  $this->get('mailer')
    ->send($message);
  $post = $this->getDoctrine()->getRepository('AppBundle:Post')->findAll();
  return $this->render("pages/index.html.twig", ['post' => $post]);
}
4

1 回答 1

1

您的代码返回它创建的 PDF,这就是为什么不执行其余部分的原因。你应该改变

return new Response(
    $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
    200,
    array(
        'Content-Type'          => 'application/pdf',
        'Content-Disposition'   => 'attachment; filename="classement.pdf"'
    )
);

进入生成本地 PDF 文件的代码:

$this->get('knp_snappy.pdf')->generateFromHtml($html, 'C:\Users\acer\Downloads\classement.pdf');
于 2019-04-07T00:16:08.883 回答