I want to generate a PDF file and send it in an email as an attachment using Swift Mailer and knp-snappy-bundle. The problem is it generates and downloads the PDF file only without rendering the template. I want it to generate the PDF and render the template at the same time.
Code:
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]);
}
Your code returns the PDF that it creates, that's why the rest is not executed. You should change
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="classement.pdf"'
)
);
into the code that generates local PDF file:
$this->get('knp_snappy.pdf')->generateFromHtml($html, 'C:\Users\acer\Downloads\classement.pdf');