Its possible using
https://github.com/KnpLabs/KnpSnappyBundle
Firstly install and configure the KnpSnappyBundle
Then:
create custom action in your admin:
protected function configureRoutes(RouteCollection $collection)
{
$collection->add('pdf', $this->getRouterIdParameter().'/pdf');
}
Create the logic for this action in the admin controller
public function pdfAction(Request $request)
{
$id = $request->get($this->admin->getIdParameter());
$object = $this->admin->getObject($id);
if (!$object) {
throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
}
$this->admin->checkAccess('show', $object);
$this->admin->setSubject($object);
$response = $this->render(
'@App/Admin/pdf.html.twig',
[
'action' => 'print',
'object' => $object,
'elements' => $this->admin->getShow(),
],
null
);
$cacheDir = $this->container->getParameter('kernel.cache_dir');
$name = tempnam($cacheDir.DIRECTORY_SEPARATOR, '_print');
file_put_contents($name, $response->getContent());
$hash = base64_encode($name);
$options['viewport-size'] = '769x900';
$url = $this->container->get('router')->generate('app_print', ['hash' => $hash], Router::ABSOLUTE_URL);
$pdf = $this->container->get('knp_snappy.pdf')->getOutput($url, $options);
return new Response(
$pdf,
200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'filename="show.pdf"',
]
);
}
Create the pdf view to render the show without admin menu or headers.
App/Admin/pdf.html.twig
{% extends '@SonataAdmin/CRUD/base_show.html.twig' %}
{% block html %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
{% block head %}
{{ parent() }}
{% endblock %}
<body style="background: none">
{% block sonata_admin_content %}
{{ parent() }}
{% endblock %}
</body>
</html>
{% endblock %}
Create a print controller in the app.
/**
* @Route(path="/core/print")
*/
class PrinterController
{
/**
* @Route(path="/{hash}", name="app_print")
*
* @param string $hash
*
* @return Response
*/
public function indexAction($hash)
{
$file = base64_decode($hash);
if (!file_exists($file)) {
throw new NotFoundHttpException();
}
$response = new Response(file_get_contents($file));
unlink($file);
return $response;
}
}
NOTE: This controller is used to use knpSnappy with a url instead of string, in order to avoid conflicts with assets, eg images etc. If you don't need print images or styles, simply use $this->get('knp_snappy.pdf')->generateFromHtml()
to generate the pdf from the response instead of send to another url and remove the part when is used the cache to create a temporal rendered file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.