Skip to content

Instantly share code, notes, and snippets.

@kcassam
Last active August 29, 2015 14:02
Show Gist options
  • Save kcassam/d4ce37525d7a0368d3e5 to your computer and use it in GitHub Desktop.
Save kcassam/d4ce37525d7a0368d3e5 to your computer and use it in GitHub Desktop.
<?php
/**
* This function allows you to make any view downloadable via pdf or jpg.
* You must have KnpSnappyBundle installed (https://github.com/KnpLabs/KnpSnappyBundle)
* To use it in any Action (example below) :
* - Add _format in route
* - Call return $this->renderSnappy($paramters) instead of return $paramters;
*/
public function renderSnappy($parameters) {
$properties = array(
'jpg' => array('Content-Type' => 'image/jpg', 'Content-Disposition' => 'filename="image.jpg"', 'knp' => 'knp_snappy.image'),
'pdf' => array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="file.pdf"', 'knp' => 'knp_snappy.pdf')
);
$template = $this->getRequest()->attributes->get('_template');
$format = $template->get('format');
if (!array_key_exists($format, $properties)) {
return $parameters;
}
// If i'm here, format is jpg or pdf
$view = $template->set('format', 'html')->getLogicalName();
$html = $this->renderView($view, $parameters);
$property = $properties[$format];
return new Response(
$this->get($property['knp'])->getOutputFromHtml($html),
200,
array(
'Content-Type' => $property['Content-Type'],
'Content-Disposition' => $property['Content-Disposition']
)
);
}
/**
* Example :
* @Route("/{id}/sponsorship.{_format}", requirements={"id" = "\d+", "_locale" = "en|fr", "_format" = "html|pdf|jpg" }, defaults = {"_format" = "html"}, name="frontend_sponsorship_show")
* @Template()
*/
public function showSponsorshipAction(Photo $photo)
{
return $this->renderSnappy(array('photo' => $photo));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment