Git Product home page Git Product logo

knpsnappybundle's Introduction

KnpSnappyBundle

Build Status Scrutinizer Code Quality StyleCI

Snappy is a PHP wrapper for the wkhtmltopdf conversion utility. It allows you to generate either pdf or image files from your html documents, using the webkit engine.

The KnpSnappyBundle provides a simple integration for your Symfony project.

Limitations

If you use JavaScript to render your pages, you may encounter some issues because of wkhtmltopdf not being fully compatible with ES6 apis. The only way to solve this issue is to provide polyfills that fix the gaps between modern ES6 apis and the wkhtmltopdf rendering engine.

Installation

With composer, require:

composer require knplabs/knp-snappy-bundle

If you are not using Flex, enable it in your kernel :

// config/bundles.php
<?php

return [
    //...
    Knp\Bundle\SnappyBundle\KnpSnappyBundle::class => ['all' => true],
    //...
];

Configuration

If you need to change the binaries, change the instance options or even disable one or both services, you can do it through the configuration.

# config/packages/knp_snappy.yaml
knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf #"\"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe\"" for Windows users
        options:    []
    image:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltoimage #"\"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltoimage.exe\"" for Windows users
        options:    []

If you want to change temporary folder which is sys_get_temp_dir() by default, you can use

# config/packages/knp_snappy.yaml
knp_snappy:
    temporary_folder: "%kernel.cache_dir%/snappy"

You can also configure the timeout used by the generators with process_timeout:

# config/packages/knp_snappy.yaml
knp_snappy:
    process_timeout: 20 # In seconds

Usage

The bundle registers two services:

  • the knp_snappy.image service allows you to generate images;
  • the knp_snappy.pdf service allows you to generate pdf files.

Generate an image from a URL

// @var Knp\Snappy\Image
$knpSnappyImage->generate('http://www.google.fr', '/path/to/the/image.jpg');

Generate a pdf document from a URL

// @var Knp\Snappy\Pdf
$knpSnappyPdf->generate('http://www.google.fr', '/path/to/the/file.pdf');

Generate a pdf document from multiple URLs

// @var Knp\Snappy\Pdf
$knpSnappyPdf->generate(array('http://www.google.fr', 'http://www.knplabs.com', 'http://www.google.com'), '/path/to/the/file.pdf');

Generate a pdf document from a twig view

// @var Knp\Snappy\Pdf
$knpSnappyPdf->generateFromHtml(
    $this->renderView(
        'MyBundle:Foo:bar.html.twig',
        array(
            'some'  => $vars
        )
    ),
    '/path/to/the/file.pdf'
);

Render an image as response from a controller

use Knp\Bundle\SnappyBundle\Snappy\Response\JpegResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class SomeController extends AbstractController
{
    public function imageAction(Knp\Snappy\Image $knpSnappyImage)
    {
        $html = $this->renderView('MyBundle:Foo:bar.html.twig', array(
            'some'  => $vars
        ));

        return new JpegResponse(
            $knpSnappyImage->getOutputFromHtml($html),
            'image.jpg'
        );
    }
}

Render a pdf document as response from a controller

use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class SomeController extends AbstractController
{
    public function pdfAction(Knp\Snappy\Pdf $knpSnappyPdf)
    {
        $html = $this->renderView('MyBundle:Foo:bar.html.twig', array(
            'some'  => $vars
        ));

        return new PdfResponse(
            $knpSnappyPdf->getOutputFromHtml($html),
            'file.pdf'
        );
    }
}

Render a pdf document with a relative url inside like css files

use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class SomeController extends AbstractController
{
    public function pdfAction(Knp\Snappy\Pdf $knpSnappyPdf)
    {
        $pageUrl = $this->generateUrl('homepage', array(), true); // use absolute path!

        return new PdfResponse(
            $knpSnappyPdf->getOutput($pageUrl),
            'file.pdf'
        );
    }
}

Maintainers

KNPLabs is looking for maintainers (see why).

If you are interested, feel free to open a PR to ask to be added as a maintainer.

We’ll be glad to hear from you :)

Credits

SnappyBundle and Snappy are based on the awesome wkhtmltopdf. SnappyBundle has been developed by KnpLabs.

knpsnappybundle's People

Contributors

akerouanton avatar akovalyov avatar alexpozzi avatar andrewtch avatar bruno-ds avatar chris8934 avatar docteurklein avatar endroid avatar flug avatar garak avatar herzult avatar jvasseur avatar jzawadzki avatar l3pp4rd avatar lwagner avatar mbontemps avatar mhor avatar pilot avatar piotrantosik avatar polc avatar r2c avatar seangofus avatar soullivaneuh avatar sstok avatar stephanvierkant avatar stephpy avatar tacman avatar umpirsky avatar weaverryan avatar wouterj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

knpsnappybundle's Issues

Creating PDFs from html which contains CMYK colorspaced images

Hi,
I am using CYMK colorspaced images in my html and try to create pdf but it gives me some kind of empty pdf output. If i give normal JPG without CYMK colorspace in the html it produces the pdf. Is it because of wkhtmltopdf limitations ? or am i doing anything wrong ?

Xvfb failed to start if use in loop

When I use this code:
$this->get('knp_snappy.pdf')->generateFromHtml(...)
in foreach I got error:
The exit status code '1' says something went wrong:
stderr: "xvfb-run: error: Xvfb failed to start
"
stdout: ""
command: xvfb-run wkhtmltopdf --lowquality --encoding 'UTF-8' '/tmp/knp_snappy52cf09a32e5fd0.95781514.html' 'documents/8ed1b575b3752959340404b52a3c1f3a.pdf'

First loop give me correct document but second gives an error. Do you know why?
My config is as follows:
knp_snappy:
pdf:
enabled: true
binary: xvfb-run wkhtmltopdf
options:
encoding: UTF-8

please also log the actual commandline used to call wkhtmltopdf

Debugging becomes a lot easier, if I can see the commandline. A patch should be trivial, if you agree.

Update: It's not that trivial, since LoggableGenerator does not extend a generator but aggregates it. Please tell me, if you agree with this issue and we can think about an implementation.

Problem with wkhtmltopdf

When i try to use pdf generator service i got following error:

The exit status code '127' says something went wrong:
stderr: "sh: /usr/local/phpexec/wkhtmltopdf: No such file or directory
"
stdout: ""
command: /home/siciarek/workspace/meltingpot/app/bin/wkhtmltopdf --lowquality --margin-bottom '0' --margin-left '0' --margin-right '0' --margin-top '0.61cm' --orientation 'Portrait' --page-size 'A4' --disable-smart-shrinking '/tmp/knp_snappy53450ea1774ca1.22573169.html' '/tmp/knp_snappy53450ea1775392.19970615.pdf'.

As you can see customized path is used but /usr/local/phpexec/wkhtmltopdf is involved as well.

Want to generate pdf from twig

I am trying to generate a PDF from twig and I am using the following code


$myTwig= "ABCReportBundle:TestEH:showAsTable.html.twig";
$html1 = $this -> renderView($myTwig, array('portal' => $portal, 'reports' => $reports));
return new Response($this -> get('knp_snappy.pdf') -> getOutputFromHtml($html1), 200, 
                            array('Content-Type' => 'application/pdf', 
                            'Content-Disposition' => 'attachment; 
                            filename="ReportWithChart.pdf"'));

My intention is to produce PDF from the content of the twig file only. But it generating the the whole template. Its not showing any image and CSS is missing.

The process stopped because of a "0" signal

I am using the snappy bundle with Symfony2 version 2.1.*

When I call $this->get('knp_snappy.pdf')->getOutputFromHtml($html);

I get this error

"The process stopped because of a "0" signal"

I have tried with both wkhtmltopdf 0.11.0_rc1 and 0.9.9

I get the same error if I use

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
$snappy->setOption('header-html', false);
$snappy->setOption('footer-html', false);
$snappy->setOption('no-background', true);
$output = $snappy->getOutput('http://www.google.com');

Is the snappy bundle compatible with 2.1.* ?

Thanks

Images not showing in PDF on live server

I'm using this to render an HTML file to a pdf. I've built it on a test server and it all works perfectly but when I move it to the live server none of the images show at all. I've tried using png and jpg images as well as relative, absolute and full paths but nothing I do seems to work.

I've attached screen shots of both the live and test sites so you can see what I get.
live

live
test

Javascript not executed

Hi,

I try to exectute some javascript, at the end of the view construction, but it don't seem to work. The paths are ok.

$html = $this->renderView('WddbFrontBundle:Folder:showReportPdf.html.twig', array("report" => $report));
//
        $filename = $report->getTitle().'_'.date("Y_m_d_His").'.pdf';

        return new Response(
            //$this->get('knp_snappy.pdf')->getOutput($pageUrl),
            $this->get('knp_snappy.pdf')->getOutputFromHtml($html,
                    array('lowquality' => false,
                        'encoding' => 'utf-8',
                        'images' => true,
                        'enable-javascript' => true,
                        'javascript-delay' => 5000)
            ),
            200,
            array(
                'Content-Type'          => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="'. $filename .'"',
                'Set-Cookie'            => 'fileDownload=true; path=/'
            )
        );

At the bottom of my view, I've a jQuery ready event used to load my i18n plugin. Everything is ok (html + css) but my javascript don't seems to be executed.

 <script src={{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset("assets/plugins/i18next-1.7.2/i18next-1.7.2.js")}} type="text/javascript" ></script>
        <script>
            $(document).ready(function() {    

Is there an option that I didn't see?

Thank you for your help

Cannot set non-string options

Eg: cookies

Notice: Array to string conversion in /blahblah/vendor/knplabs/knp-snappy-bundle/Knp/Bundle/SnappyBundle/Snappy/LoggableGenerator.php line 84

Catch runtime exception in KnpSnappyBundle

Hi,

I implement KnpSnappyBundle in my project for capture screenshots of websites.
Everything is going smoothly, but some runtime exception of Wkhtmltoimage occurred by some websites and I can't fix it.

I wanna know have any solution of KnpSnappyBundle for catch exceptions of Wkhtmltoimage? It can avoid my symfony stock on these runtime exceptions.

Thanks your great work.

Broken get contents

Warning: file_get_contents(/tmp/knplabs_snappyf35hGd.pdf): failed to open stream: No such file or directory in /home/cordoval/sites-2/x/vendor/knplabs/snappy/src/Knplabs/Snappy/Media.php line 87

your syntax is jeopardizing the whole thing too, tried several variants but the same trouble

'Content-Disposition' => 'attachment; filename="file.pdf',

see the missing quotes?

grrr so frustrating.

500 Internal Server Error - RuntimeException

Hello,

i would like to export html to pdf from a response controller.

Here my script:

    $html = $this->renderView('AdopaleRefBundle:Admin:adminmissionsparconsultant.html.twig', array(
        'missionsparconsultant'=> $missionsparconsultant, 
        'consultant'=> $consultant));

    return new Response(
    $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
    200,
    array(
    'Content-Type'          => 'application/pdf',
    'Content-Disposition'   => 'attachment; filename="cv.pdf"'
    )
    );

I have this error: "500 Internal Server Error - RuntimeException"

I'm wondering if the problem comes from wkhtmltopdf and his location. The wkhtmltopdf.exe is in this file C:\wkhtmltopdf

My config script:

knp_snappy:
pdf:
enabled: true
binary: ./wkhtmltopdf/wkhtmltopdf
options: []

Thanks for your help!

setOption in generator vs setOption in LoggableGenerator

Method setOption in Abstract Generator (Knp/Snappy) allows to pass array in value parameter, but method setOption in LoggableGenerator class doesn't. Problem is in LoggableGenerator class, method setOption, line 84.

The notice message is "Notice: Array to string conversion". Commenting line 84 solves the problem.

Example of usage to performe notice message:
$pdf->setOption('custom-header', array('cookie' => 'COOKIENAME=COOKIEVALUE'));

Problem with pd file generation

hello i m using symfony2 in ubuntu
1- i installed wkhtmltopdf
2-This is my config.yml
knp_snappy:
pdf:
enabled: true
binary: wkhtmltopdf
options: [ ]
image:
enabled: true
binary: wkhtmltoimage
options: [ ]
3-my fonction :
public function pdfAction($id_facture){
$em = $this->getDoctrine()->getManager();
$facture=$em->getRepository('factureBundle:Facture')->find($id_facture);
$entities = $em->getRepository('prestationBundle:Prestation')->findByFacture($id_facture);

$html = $this->renderView('factureBundle:Facture:Facture.html.twig', array(
'prestations' => $entities,
'facture'=>$facture
));
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Facture.pdf"'
)
);

but when i m tring to generate a pdf i have this problem :
The file '/tmp/knp_snappy53ac74fd112c40.53969845.pdf' was not created (command: wkhtmltopdf --lowquality '/tmp/knp_snappy53ac74fd112545.31976019.html' '/tmp/knp_snappy53ac74fd112c40.53969845.pdf').

plz can anybody help me

Not working with Windows and Symfony 2.3

Hello,

I just installed knpSnappyBundle and Snappy bundle to convert my twig into PDF

using all the relative configuration steps given on

https://github.com/KnpLabs/KnpSnappyBundle

But getting error

The exit status code '1' says something went wrong:
stderr: "'wkhtmltopdf' is not recognized as an internal or external command,
operable program or batch file.
"
stdout: ""
command: wkhtmltopdf --lowquality "C:\Users\B27\AppData\Local\Temp\knp_snappy51d18e252dd498.24775690.html" "C:\Users\B27\AppData\Local\Temp\knp_snappy51d18e253397d5.24187873.pdf".

My Config.yml file Contains

app/config/config.yml

knp_snappy:
pdf:
enabled: true
binary: C:/wkhtmltopdf
options: []
image:
enabled: true
binary: C:/wkhtmltopdf
options: []

as My wkthtml.exe is installed here using 0.9 version

Small error in the documentation

Hi,

there is a mistake in your doc :
$this->get('knp_snappy.pdf')->getOutputFromHtml($html)

This is wrong as this method takes a 2d mandatory argument (an array of options)

A second thing in the config (might be me but...)
The autoload config did not work the way you indicate but worked this way
'Knp' => array(DIR.'/../vendor/snappy/src', DIR.'/../vendor/bundles'),

Thanks

Provide specialized response classes

I might be mistaken, but isn't it possible, to provide a specialized response class to transform this code

$html = $this->renderView('MyBundle:Foo:bar.html.twig', array(
    'some'  => $vars
));

return new Response(
    $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
    200,
    array(
        'Content-Type'          => 'application/pdf',
        'Content-Disposition'   => 'attachment; filename="file.pdf"'
    )
);

into

return new Snappy\PdfFromTwigResponse(MyBundle:Foo:bar.html.twig', [
    'some'  => $vars
]);

Would you accept a pull request for this?

Error when using cookie option

I need to print and output as a PDF file a page behind authentication, like this :

$output = $snappy->getOutput($url, array(
            'cookie' => array(
                $PHPSESSID_KEY => $PHPSESSID
            )));

return new Response($output, 200,
    array(
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'filename="' . $event->getName() . '.pdf"'
    )
);

It works perfectly when using wkhtmltopdf in command line:
wkhtmltopdf --cookie PHPSESSID SESSION_ID url file
, but fails when using the knp_snappy.pdf service.

Even more strange, it only fails when the PHPSESSIONID is valid. I mean if I replace php $PHPSESSID by 'foo', command will succeed.

I've tried to use the Symfony2 Symfony\Component\Process\Process class on my own, but it fails the same way.

New stable tag?

hey guys,

a lot has been going on since 1.1 was released, would it be possible to have another tag so that we can skip dev-master?

config error

Hi!

When I try to set an option like:

knp_snappy:
    pdf:
        enabled:    true
        binary:     wkhtmltopdf
        options:    { page-size: A4 }

I get the following error:

Unrecognized options "page_size" under "knp_snappy.pdf.options" 

convert to Symfony\Component\HttpFoundation\File\File object

hello!
First thing thanks you for this bundle.
i'd like to create a pdf and use Vich uploader to manage file,
so have you got an idea not to create a pdf file directly, but create
Symfony\Component\HttpFoundation\File\File object (maybe further improvment?)

500 Internal Server Error

The exit status code '1' says something went wrong:
stderr: "'wkhtmltopdf' n'est pas reconnu en tant que commande interne
ou externe, un programme ex�cutable ou un fichier de commandes.
"
stdout: ""
command: wkhtmltopdf --lowquality "http://www.google.fr" "/file.pdf".
500 Internal Server Error - RuntimeException

PDF creation error

Hi. I have a trouble with generation pdf from html.
When I'm calling
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($export),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename='.$filename
)
);
i'm having the error: The file '/tmp/knp_snappy4fbceb3b40b3b8.86837562.pdf' was not created (command: /usr/bin/wkhtmltopdf --lowquality '/tmp/knp_snappy4fbceb3b40a6d5.62571310.html' '/tmp/knp_snappy4fbceb3b40b3b8.86837562.pdf').

The .html file is created in tmp directory, but didn't converted into pdf. I'm using static version of wkhtmltopdf. Do you have any ideas for this problem?

error after register bundle

I put Snappy files and KnpSnappyBundle files into correct places, exactly like in Installation section od readme file

my app/autoload.php file fragment:

$loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs');
$loader->add('Stats_', __DIR__.'/../vendor/math_stats/lib');
$loader->add('Stfalcon', __DIR__.'/../vendor/bundles');
$loader->add('Knp'.__DIR__.'/../vendor/bundles');
$loader->add('Knp\\Snappy',__DIR__.'/../vendor/snapppy/src');

// $loader->registerNamespaces(array(
// 'Stfalcon' => DIR.'/../vendor/bundles',
// 'Knp'=> DIR.'/../vendor/bundles',
// 'Knp\Snappy'=> DIR.'/../vendor/snappy/src',
// ));

I add new Knp\Bundle\SnappyBundle\KnpSnappyBundle(), to app/appKernel.php,
on the local machine I have error: Fatal error: Class 'Knp\Bundle\SnappyBundle\KnpSnappyBundle' not found in "../appKernel.php" on line 25
and onthe server I have: Fatal error: Interface 'Knp\Snappy\GeneratorInterface' not found in /home/biostatn/public_html/raport/vendor/bundles/Knp/Bundle/SnappyBundle/Snappy/LoggableGenerator.php on line 13

what is wrong?
thank you in advance for your help and best regards
vesol

Remove header from pdf file

Hey folks,

when I generate a pdf it always has this

HTTP/1.0 200 OK Cache-Control: no-cache Date: Sun, 20 Jan 2013 11:17:25 GMT

at the top. How can I avoid that?

'cover' option failed under Windows System

in my config, i've juste added

options:   { 'cover': "http://localhost/foxp2projects/symfony/web/app_dev.php/fr/indexpdf.html" }

i got this error :
Unknown long argument --cover

i got the same error with prompt command

wkhtmltopdf-issue-with-cover

for my local test i've changed line 354 :
\Symfony\vendor\knplabs\knp-snappy\src\Knp\Snappy\AbstractGenerator.php

                    $command .= ' --'.$key." ".escapeshellarg($option);

with

                    if ( PHP_OS !== 'WINNT') {                    
                    $command .= ' --'.$key.' '.escapeshellarg($option);
                    }else{
                    $command .= ' '.$key.' '.escapeshellarg($option);   
                    }

without the double -, cover page is added to pdf document.

did i understood how options works?

Option to Ignore Errors

Hey,

Great bundle! One option I would like to see is the ability to suppress errors like 404's on images etc from throwing exceptions.

I have put in place a workaround for the time being to prevent exceptions being thrown. If I get time I'll implement a proper switch on this and submit pull request.

Cheers
Chris

Problem on ubuntu server

When i published on my ubuntu server i had this error.

wkhtmltopdf: cannot connect to X server

I've installed xvfb and set binary to '/usr/bin/xvfb-run /usr/bin/wkhtmltopdf' in my config.yml.

Now it works for simple pdf but i had to do the css again because the size (font-size, margin, padding...) are not interpreted in the same way on my dev environment (mac) and my server.

I have another problem, in one pdf i use options, but all the options are not displayed (on my server).

Thanks for your help

@font-face problem

If I use:

@font-face { font-family: 'Century Gothic'; src: url('/fonts/century_gothic.woff') format('woff'); font-weight: normal; font-style: normal;}

the result of html to pdf is:

The exit status code '1' says something went wrong:
stderr: "Loading pages (1/6)
[> ] 0%
[======> ] 10%
QSslSocket: cannot resolve SSLv2_client_method
QSslSocket: cannot resolve SSLv2_server_method
[===========> ] 19%
[============================> ] 48%
[====================================> ] 61%
[============================================================] 100%
Counting pages (2/6) 
[============================================================]         Object 1 of 1
Warning: Received createRequest signal on a disposed ResourceObject's     NetworkAccessManager. This migth be an indication of an iframe taking to long to  load.
Resolving links (4/6)
[============================================================]    Object 1 of 1
Loading headers and footers (5/6) 
Printing pages (6/6)
[> ] Preparing
[============================================================] Page     1 of 1
Done 
Exit with code 1 due to http error: 1203 
"
stdout: ""
command: /usr/local/bin/wkhtmltopdf.sh --lowquality     '/tmp/knp_snappy5381f86bd7bff0.37628631.html'         '/tmp/knp_snappy5381f86bd7c994.57969009.pdf'.

but the html output works properly

How to set options before generating the PDF?

New to this bundle, hopefully is not completed dead and there's still someone out there that might be able to help me with this question...

I'm trying to pass the page size format before generating the PDF document with getOutputFromHtml(). I tried the following without luck based on Snappy documentation, any reason why it doesn't work or how do I need to call that method on the Snappy object?

$snappyPDF = $this->get( "knp_snappy.pdf" );
$snappyPDF->setOption( "page-size", $pageSize );

Regards and thanks

Wrong URL call with URL encoded parameters

When passing an URL encoded parameter, the "%" sign is replace by a space during AbstractGenerator::buildCommand because the $input parameter escaped with "escapeshellarg()".

So that, this sample code does not work correctly because parameters are not set :

$pageUrl = $this->generateUrl('homepage', array('data' => array('foo', 'bar'), true); // use absolute path!

return new Response(
    $this->get('knp_snappy.pdf')->getOutput($pageUrl),
    200,
    array(
        'Content-Type'          => 'application/pdf',
        'Content-Disposition'   => 'attachment; filename="file.pdf"'
    )
);

Assetic not working

Is it possible to use assetic in a template that is rendered as a pdf? I haven't been able to get this to work yet.

Please see this thread for more info.

Error reporting doesn't honour log level

To get errors from the wkhtmltopdf binary you have to be running in the dev environment, instead of it reflecting the log level set in the configuration. If it errors on production I still want to get that error!

Render squares instead of characters.

sc6
Hi,

When I try to generate pdf from html or url it generated successfully but instead of render character it render squares.

Any solution ?

Thanks

  • Nirav Ranpara

Render a secure URL

I've tried this bundles and works well for me in all cases but one.

When I try to render a pdf froma a secure route which needs to be authenticated it prints the login page, that have all the sense for me, of course, but I want to know if it's any workarround to render pdf from a secure url of my project.

Thanks

Error: generate pdf from url. Error log

I get this error dev.log:
Uncaught PHP Exception RuntimeException: "The exit status code '1' says something went wrong: stderr: "" stdout: "Loading pages (1/6) [> ] 0% [======> ] 10% QSslSocket: cannot resolve SSLv2_client_method QSslSocket: cannot resolve SSLv2_server_method Error: Failed loading page http:///var/www/symensay/src/Acme/PortalBundle/Controller/../../../../web/app_dev.php/ver-hoja-de-vida

Exit status code '139' : Segmentation fault

Hi,

I try to generate a pdf from a rendered html content, but I got this error:

The exit status code '139' says something went wrong:
stderr: "Loading pages (1/6)
[> ] 0%
[======> ] 10%
QSslSocket: cannot resolve SSLv2_client_method
QSslSocket: cannot resolve SSLv2_server_method
[============> ] 21%
[=====================> ] 35%
[=======================> ] 39%
[=========================> ] 43%
[============================================================] 100%
Counting pages (2/6) 
[============================================================] Object 1 of 1
Resolving links (4/6) 
[============================================================] Object 1 of 1
Loading headers and footers (5/6) 
Printing pages (6/6)
[> ] Preparing
[============================================================] Page 1 of 1
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
Segmentation fault (core dumped)
"
stdout: ""
command: /usr/local/bin/wkhtmltopdf --lowquality '/tmp/knp_snappy51014036e89f72.50603536.html' '/tmp/knp_snappy51014036e8a389.88510503.pdf'.
500 Internal Server Error - RuntimeException

My crontroller's action (invoice already loaded):

        if ($this->getRequest()->get('format', '') === 'pdf') {
            $headers = array(
                'Content-Type'          => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="'.$invoice->getRef().'.pdf"',
            );

            $html = $this->renderView('NexyFrontBundle:Billing:invoice_only.html.twig', array('invoice' => $invoice));

//            return new Response($html);

            return new Response($this->get('knp_snappy.pdf')->getOutputFromHtml($html), 200, $headers);
        }

My template:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>{% block title %}Welcome!{% endblock %}</title>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <base href="{{ app.request.scheme ~ '://' ~ app.request.httpHost }}" />

        {% block stylesheets %}
    <link href="/theme/css/bootstrap.css" rel="stylesheet">
        {% endblock %}
    </head>

    <body>
        <div class="row-fluid">
            <div class="box span3" ontablet="span4" ondesktop="span3">
                <div class="box-header">
                    <h2><i class="fa-icon-user"></i><span class="break"></span>Destinataire</h2>
                    <div class="box-icon">
                    </div>
                </div>
                <div class="box-content">
                    <p>
                        <b>{{ invoice.recipientName }}</b>
                        <br/>
                        {{ invoice.recipientAddress | nl2br }}
                    </p>
                    <p>
                        TVA : {{ invoice.recipientNif }}
                        <br />
                        SIRET : {{ invoice.recipientSiret }}
                    </p>
                </div>
            </div>

            <div class="box span5" ontablet="span8" ondesktop="span5 offset4">
                <div class="box-header">
                    <h2><i class="fa-icon-file"></i><span class="break"></span>Références</h2>
                    <div class="box-icon">
                    </div>
                </div>
                <div class="box-content">
                    <ul class="unstyled">
                        <li><b>Facture # :</b>
                            {{ invoice.ref }}
                        </li>
                        <li><b>Date :</b>
                            {{ invoice.createdAt | date('d/m/Y') }}
                        </li>
                        <li><b>Payé :</b>
                            {{ invoice.paid | yesno('badge') }}
                        </li>
                        <li><b>Reste à devoir :</b>
                            {{ invoice.balance }} €
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="row-fluid">
            <div class="box span12" ontablet="span12" ondesktop="span12">
                <div class="box-header">
                    <h2><i class="fa-icon-list"></i><span class="break"></span>Eléments</h2>
                    <div class="box-icon">
                    </div>
                </div>
                <div class="box-content">
                    <table class="table table-striped table-condensed">
                        <thead>
                            <tr>
                                <th>Element</th>
                                <th>Description</th>
                                <th>Prix unitaire</th>
                                <th>Quantité</th>
                                <th>Total</th>
                            </tr>
                        </thead>

                        <tbody>
                            {% for item in invoice.items %}
                            <tr>
                                <td>{{ item.name }}</td>
                                <td>{{ item.description | nl2br }}</td>
                                <td>{{ item.price }} €</td>
                                <td>{{ item.quantity }}</td>
                                <td>{{ item.price * item.quantity }} €</td>
                            </tr>
                            {% endfor %}
                        </tbody>

                    </table>
                </div>
            </div>
        </div>

        <div class="row-fluid">
            <div class="box span9" ontablet="span9" ondesktop="span9">
                <div class="box-header">
                    <h2><i class="fa-icon-pencil"></i><span class="break"></span>Notes</h2>
                    <div class="box-icon">
                    </div>
                </div>
                <div class="box-content">
                    <p>{{ invoice.notes | nl2br }}</p>
                </div>
            </div>

            <div class="box span3" ontablet="span3" ondesktop="span3">
                <div class="box-header">
                    <h2><i class="fa-icon-plus"></i><span class="break"></span>Total</h2>
                    <div class="box-icon">
                    </div>
                </div>
                <div class="box-content">
                    <ul class="unstyled">
                        <li><b>Sous-total :</b>
                            {{ invoice.subTotal }} €
                        </li>
                        <li><b>TVA ({{ invoice.tva }} %) : </b>
                            {{ invoice.total - invoice.subTotal }} €
                        </li>
                        <li><b>Total :</b>
                            {{ invoice.total }} €
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="row-fluid">
            <div class="box span12" ontablet="span12" ondesktop="span12">
                <div class="box-header">
                    <h2><i class="fa-icon-list"></i><span class="break"></span>Paiements</h2>
                    <div class="box-icon">
                    </div>
                </div>
                <div class="box-content">
                    <table class="table table-striped table-condensed">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Méthode de paiement</th>
                                <th>ID de transaction</th>
                                <th>Somme</th>
                            </tr>
                        </thead>

                        <tbody>
                            {% for payment in invoice.payments %}
                            <tr>
                                <td>{{ payment.date | date('d/m/Y') }}</td>
                                <td>{{ payment.method.name }}</td>
                                <td>{{ payment.transactionId }}</td>
                                <td>{{ payment.amount }} €</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>

                    <a class="btn btn-block" href="{{ path('nexy_front_payment_paybox', { ref: invoice.ref }) }}">
                        Payer avec Paybox
                    </a>
                </div>
            </div>
        </div>
    <body>
</html>

Wkhtmltopdf version: wkhtmltopdf 0.11.0 rc1

This action works perfectly if I removed stylesheet links from <head>, so it's maybe cause of css file, but how ?

Thanks for help !

I cannot generate a pdf of a secure page

I'm trying to Render a pdf document with a relative url like so:

$pageUrl = $this->generateUrl('homepage', array(), true);
return new Response(
    $this->get('knp_snappy.pdf')->getOutput($pageUrl),
    200,
    array(
        'Content-Type'          => 'application/pdf',
        'Content-Disposition'   => 'attachment; filename="file.pdf"'
    )
);

But the $pageUrl requires login to access, so the pdf being returned is the login page. I cant seem to get around this.

Render dojo chart

Hi. I am trying to render a html page with af dojo spider chart. I have managed to get the page with the chart showing correctly when I use wkhtmltopdf and a php wrapper called WkHtmlToPdf (http://mikehaertl.github.io/phpwkhtmltopdf/), using the html that is rendered from Symfony2.3 and the dojo javascript.
When I try to render the page with KnpSnappyBundle, I get the page and text but not the chart. The same happens when I use WkHtmlToPdf in a Symfony Controller.
Any suggestions to where the problem can be.
Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.