繁体   English   中英

如何在Sonata管理捆绑包中转换ConfigureShowFields以生成PDF?

[英]How to transform ConfigureShowFields to generate PDF in sonata admin bundle?

这是我的使用Sonata bundle的ConfigureShowFields

图片中的我的ConfigureShowFilds描述

我想将ConfigureShowFields数据转换为pdf,这可能吗?

其可能的用途

https://github.com/KnpLabs/KnpSnappyBundle

首先安装并配置KnpSnappyBundle

然后:

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

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

在管理控制器中为此操作创建逻辑

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视图以呈现不带管理菜单或标题的节目。

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 %}

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

/**
 * @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与url而不是字符串一起使用,以避免与资产(例如图像等)冲突。如果不需要打印图像或样式,只需使用$this->get('knp_snappy.pdf')->generateFromHtml()从响应生成pdf,而不是发送到另一个URL,并在使用缓存创建临时渲染文件时删除该部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM