在Symfony中同时渲染模板并返回响应

时间:2019-04-06 23:44:11

标签: php symfony swiftmailer knp-snappy

我想生成一个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]);
}

1 个答案:

答案 0 :(得分:1)

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

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

插入generates local PDF file中的代码:

$this->get('knp_snappy.pdf')->generateFromHtml($html, 'C:\Users\acer\Downloads\classement.pdf');