2017-05-04 81 views

回答

1

其可能使用

https://github.com/KnpLabs/KnpSnappyBundle

首先安装和配置KnpSnappyBundle

然后:

在您的管理员创建自定义操作:

protected function configureRoutes(RouteCollection $collection) 
{ 
    $collection->add('pdf', $this->getRouterIdParameter().'/pdf'); 
} 

创建逻辑这个行动在管理公司ntroller

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"', 
     ] 
    ); 
} 

创建pdf视图来呈现没有管理员菜单或标题的节目。

应用程序/管理/ 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 %} 

在应用中创建一个打印控制器。

/** 
* @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; 
    } 
} 

注意:此控制器用于使用knpSnappy而不是字符串,以避免与资产发生冲突。图像等。如果您不需要打印图像或样式,只需使用$this->get('knp_snappy.pdf')->generateFromHtml()从响应生成PDF而不是发送到另一个网址,并在使用缓存创建时间渲染文件时删除该部分。

相关问题