Giter Club home page Giter Club logo

snappy's Introduction

Snappy

Build Status AppVeyor CI Build Status Scrutinizer Code Quality

Snappy is a PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. It uses the excellent webkit-based wkhtmltopdf and wkhtmltoimage available on OSX, linux, windows.

You will have to download wkhtmltopdf 0.12.x in order to use Snappy.

Please, check FAQ before opening a new issue. Snappy is a tiny wrapper around wkhtmltox, so lots of issues are already answered, resolved or wkhtmltox ones.

Following integrations are available:

Installation using Composer

composer require knplabs/knp-snappy

Usage

Initialization

<?php

require __DIR__ . '/vendor/autoload.php';

use Knp\Snappy\Pdf;

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');

// or you can do it in two steps
$snappy = new Pdf();
$snappy->setBinary('/usr/local/bin/wkhtmltopdf');

Display the pdf in the browser

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
header('Content-Type: application/pdf');
echo $snappy->getOutput('http://www.github.com');

Download the pdf from the browser

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $snappy->getOutput('http://www.github.com');

Merge multiple urls into one pdf

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $snappy->getOutput(array('http://www.github.com','http://www.knplabs.com','http://www.php.net'));

Generate local pdf file

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
$snappy->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', '/tmp/bill-123.pdf');

Pass options to snappy

// Type wkhtmltopdf -H to see the list of options
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
$snappy->setOption('disable-javascript', true);
$snappy->setOption('no-background', true);
$snappy->setOption('allow', array('/path1', '/path2'));
$snappy->setOption('cookie', array('key' => 'value', 'key2' => 'value2'));
$snappy->setOption('post', array('key' => 'value'));
$snappy->setOption('cover', 'pathToCover.html');
// .. or pass a cover as html
$snappy->setOption('cover', '<h1>Bill cover</h1>');
$snappy->setOption('toc', true);
$snappy->setOption('cache-dir', '/path/to/cache/dir');

Reset options

Options can be reset to their initial values with resetOptions() method.

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
// Set some options
$snappy->setOption('copies' => 4);
// ..
// Reset options
$snappy->resetOptions();

wkhtmltopdf binary as composer dependencies

If you want to download wkhtmltopdf and wkhtmltoimage with composer you add to composer.json:

composer require h4cc/wkhtmltopdf-i386 0.12.x
composer require h4cc/wkhtmltoimage-i386 0.12.x

or this if you are in 64 bit based system:

composer require h4cc/wkhtmltopdf-amd64 0.12.x
composer require h4cc/wkhtmltoimage-amd64 0.12.x

And then you can use it

<?php

use Knp\Snappy\Pdf;

$myProjectDirectory = '/path/to/my/project';

$snappy = new Pdf($myProjectDirectory . '/vendor/h4cc/wkhtmltopdf-i386/bin/wkhtmltopdf-i386');

// or

$snappy = new Pdf($myProjectDirectory . '/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64');

N.B. These static binaries are extracted from Debian7 packages, so it might not be compatible with non-debian based linux distros

Some use cases

If you want to generate table of contents and you want to use custom XSL stylesheet, do the following:

<?php
$snappy = new Pdf('/path/to/binary');

$snappy->setOption('toc', true);
$snappy->setOption('xsl-style-sheet', 'http://path/to/stylesheet.xsl') //or local file;

$snappy->generateFromHtml('<p>Some content</p>', 'test.pdf');

Bugs & Support

If you found a bug please fill a detailed issue with all the following points. If you need some help, please at least provide a complete reproducer so we could help you based on facts rather than assumptions.

  • OS and its version
  • Wkhtmltopdf, its version and how you installed it
  • A complete reproducer with relevant php and html/css/js code

If your reproducer is big, please try to shrink it. It will help everyone to narrow the bug.

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

Snappy has been originally developed by the KnpLabs team.

snappy's People

Contributors

akerouanton avatar akovalyov avatar alexpozzi avatar antoinelelaisant avatar barryvdh avatar carlescliment avatar craue avatar daniel-helpling avatar desarrolla2 avatar docteurklein avatar eveyonline avatar gromnan avatar h4cc avatar herzult avatar krispypen avatar l3pp4rd avatar louterrailloune avatar martinssipenko avatar mbontemps avatar merlijntishauser avatar pilot avatar piotrantosik avatar seangofus avatar shaneog avatar stloyd avatar trsteel88 avatar weaverryan avatar wouterbulten avatar woutersioen avatar zairigimad 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  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

snappy's Issues

How to use footer-html option?

Hey guys,

i want to use footer in my dynamic generated pdf files with the footer-html option but it doesn't work.
Here is my code:

$footer = url('documents/pdf/footer'); // generate footer url (html output)
PDF::loadView('documents.pdf.offer', $data)->setOption('footer-html', $footer);

If i want to view my pdf i only get an error: Error on load pdf file. :(

When not set the option:

setOption('footer-html', $footer);

the pdf generations works fine.

Screen size for mobile version

When I generated pdf I have always mobile version. Where can I set screen size? When I checked in javascript my screen and window size for pdf I have 640px for screen and 0px for windows width. I would like to have normal version (no mobile).

I use foundation for responsive template.

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.

When I go to /home/ubuntu/wkhtmltox/bin/wkhtmltopdf http://www.google.com test.pdf I get this:

Loading pages (1/6)
QSslSocket: cannot resolve SSLv2_client_method ] 10%
QSslSocket: cannot resolve SSLv2_server_method
Counting pages (2/6)

Resolving links (4/6)

Loading headers and footers (5/6)

Printing pages (6/6)
Done

Then it saves a pdf of the homepage (containing the images too) to the server.

I've tried using:

http://{{ domain }}/pdf/images/background_logo.png
http://subdomain.livesite.com/pdf/images/background_logo.png

both of which work on the test server, but not the live one.

The code used to generate the pdf is:

public function generatePdf($app)
{
$products = $this->getRecurringOrderProducts();
if (count($products) > 0) {
$filename = $this->getPdfFilename($app);
if (!file_exists($filename)) {
// Generate HTML
$html = $app['twig']->render('order/pdf.twig', array(
'entry' => $this,
'products' => $products,
'expiry_date' => $this->getExpiryDate(), // Add this line
'content_height' => intval( (8_100_count($products))/95 )+1,
'domain' => $app['config']['domain'],
));
// Generate PDF
$snappy = new Pdf($app['wkhtmltox_bin']);
$snappy->setOption('orientation', 'landscape');
$snappy->generateFromHtml(utf8_decode($html), $filename);
}
}
}

I've spent weeks getting this to work without any luck, if anybody has any suggestions I'm be extremely grateful.

Thank you

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

unlink(): No such file or directory

If header-html or footer-html is null, then the tmp files are not created but snappy still tries to unlink them.
#121

Origin of the problem:
7bbb268
The same logic isn't used when deciding to generate as deciding to unlink.

Returning blank PDF file

I'm running this class using the code on your site, but it's returning a zero byte empty PDF file.

require_once 'libraries/autoload.php';
use Knp\Snappy\Pdf;

$snappy = new Pdf('/usr/bin/wkhtmltopdf');

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
$snappy->generateFromHtml($out1, '/tmp/'.session_id().'.pdf');

I've checked the tmp file and it's there but NOT empty. What gives and why is the downloaded version empty??

Command Errors handling

Got an Uncaught PHP Exception RuntimeException: "The exit status code '1' says something went wrong when Warning: Failed loading page even with the --load-error-handling ignore. The pdf is correctly generated from the command, but cannot be displayed immediatly after generation because of this RuntimeException. (This is provocated when any asset cannot be loaded (404 for instance)).

This is due to the checkProcessStatus method from Knp\Snappy\AbstractGenerator class, which is only checking if status code === 0.

Catching the Exception isn't enough to get output, since tmp file content isn't retrieved before. Cannot we let the choice to retieve or not the errors and display the pdf by :

  • Catching excption internally (generate method)
  • Populating an errors array
  • Giving the possibility to add the errors array to getOutput($input, array $options = array()) method as reference

So it will result to :

public function getOutput($input, array $options = array(), array &$errors = array())
 {
       $filename = $this->createTemporaryFile(null, $this->getDefaultExtension());

       try {
            $this->generate($input, $filename, $options);
        } catch(RuntimeExcpetion){
            //Populates $errors
        }

        $result = $this->getFileContents($filename);

        $this->unlink($filename);

        return $result;
 }

Idem for LoggableGenerator from KNPSanppyBundle.

How to use cover & toc options

Hi there,

can someone explain me how to deal with toc (table of contents) and cover objects ? I believe buildCommand does not support them properly as it seems they are treated like regular options (adding "--" to them) but they are not.

This is almost similar to request #29 because cover and toc are objects just like pages, so if we were able to add several pages to the command, there wouldn't be much work to add support for toc and cover objects either.

The exit status code '1' says something went wrong:
stderr: "Unknown long argument --cover

[...]

(page)? <input url/file name> [PAGE OPTION]...
Options for the page object can be placed in the global options and the page
options areas. The applicable options can be found in the Page Options and
Headers And Footer Options sections.

A cover objects puts the content of a singe webpage into the output document,
the page does not appear in the table of content, and does not have headers
and footers.

cover <input url/file name> [PAGE OPTION]...
All options that can be specified for a page object can also be specified for
a cover.

A table of content object inserts a table of content into the output document.

toc [TOC OPTION]...
All options that can be specified for a page object can also be specified for
a toc, further more the options from the TOC Options section can also be
applied. The table of content is generated via XSLT which means that it can be
styled to look however you want it to look. To get an aide of how to do this
you can dump the default xslt document by supplying the
--dump-default-toc-xsl, and the outline it works on by supplying
--dump-outline, see the Outline Options section.

Thanks

File name is longer than the maximum allowed path length on this platform

Passing large html string to $options['header-html'] & $options['footer-html'] cause handleOptions() to check if those options are uris or files before fallback on creatingTemporaryFile().

This call AbstractGenerator:isFile(), and so php's is_file() with strings which can be too large for many filesystem defaults. Response is false as expected but emit a warning.

We can check for string length in Pdf.php, or in AbstractGenerator.php, or simply ignore the warning.

Strange Exception while generating PDF

I've load the current wkhtmltopdf-0.9.9-OS-X.i368 from the developer page (http://code.google.com/p/wkhtmltopdf/) and install SnappyBundle as described at install guide.
Everything looks fine but when I try to generate an pdf throw the snappy bundle I got following error:

The exit status code '5' says something went wrong:
stderr: "dyld: Symbol not found: __cg_jpeg_resync_to_restart
Referenced from: /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/Resources/libTIFF.dylib
Expected in: /Applications/MAMP/Library/lib/libJPEG.dylib
in /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/Resources/libTIFF.dylib
"
stdout: ""
command: /usr/bin/wkhtmltopdf 'http://www.google.at' '/Applications/MAMP/htdocs/cosamui/web/data/test.pdf'.
500 Internal Server Error - RuntimeException 
´´´´

When I run the some command from the terminal: command: /usr/bin/wkhtmltopdf 'http://www.google.at' '/Applications/MAMP/htdocs/cosamui/web/data/test.pdf' it works as expected.

What can I do to solve this issue? Anyone other the same problem?

Bad PDF generated, PDF is generated but broken and cannot be oppened

I get the PDF downloaded instantly, and it's not empty either (arround 3KB, single page) but upon opening chrome says "failed to load" and adobe reader says the document is damaged and cannot be opened.
I also noticed that it only gives me the download when I have PHP display errors ON, with them off for some reason the page (The file below) is not available and cannot load but other parts of my application still work witch means my PHP server works (I'm using wamp).
Here's the code:

require_once '/vendor/knplabs/knp-snappy/src/autoload.php';

use Knp\Snappy\Pdf;

$snappy = new Pdf('/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64');

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $snappy->getOutput('http://localhost/Ponudomat%20wSnappy/printRdy.php');

How to add more than one page?

There is an option in wkhtmltopdf that allows converting of more than one URL at a time. Is there a way to do this with snappy? I did not see it in the options class.

Thanks!

Other backends than wkhtmltopdf

What do you think of supporting other pdf generators than wkhtmltopdf ?

I'm thinking about prince xml for example : http://www.princexml.com/

I can manage this if you give me the entry points for a multiple pdf generator backends code modifications.

Generate PDF file without outputting

Using Laravel 4 with wkhtmltopdf installed via Homebrew.

Is it possible to generate the pdf and store it without doing anything further?

This would be really useful where other non-snappy processing needs to take place. E.g Creating a pdf file, then creating some other project files. Zipping them up and then I can output the zip file myself for download.

Trouble generating pdf

I have gone through the previous posts for the same topic (Issue #20) and other posts providing solutions for the problem. But nothing seems to work for me. I keep getting :

The file 'bill-123.pdf' was not created (command: /usr/local/bin/wkhtmltopdf --lowquality --no-background '/var/folders/p6/p6c0IfxzHbCVZZR6XsXBB++++TI/-Tmp-/knp_snappy501019a8e558f6.63368539.html' 'bill-123.pdf').

I am using MAMP and Symfony2.1. Although I am able to generate the pdf using the same command in the terminal. Please let me know if I am missing something here. Anticipating your response. Thank you.

Exception fired when generating from HTML

Based on the example in the readme, when I use generateFromHtml I get the following.

Fatal error: Uncaught exception 'RuntimeException' with message 'The file '/tmp/bill-123.pdf' was not created (command: /Users/jmorton/Sites/tests/wkpdf/wkhtmltopdf --lowquality "/var/folders/EH/EH1NBNSiGU0hy8p-WZ78Bo2kqHI/-Tmp-/knp_snappy4e7223ebe7a27.html" "/tmp/bill-123.pdf").' in /Users/jmorton/Sites/tests/wkpdf/Knp/Snappy/AbstractGenerator.php:260 Stack trace: #0 /Users/jmorton/Sites/tests/wkpdf/Knp/Snappy/AbstractGenerator.php(116): AbstractGenerator->checkOutput('/tmp/bill-123.p...', '/Users/jmorton/...') #1 /Users/jmorton/Sites/tests/wkpdf/Knp/Snappy/AbstractGenerator.php(126): AbstractGenerator->generate('/var/folders/EH...', '/tmp/bill-123.p...', Array, false) #2 /Users/jmorton/Sites/tests/wkpdf/index.php(14): AbstractGenerator->generateFromHtml('

Bill

<p...', '/tmp/bill-123.p...') #3 {main} thrown in /Users/jmorton/Sites/tests/wkpdf/Knp/Snappy/AbstractGenerator.php on line 260

If I try to have it send the pdf for download then the pdf is corrupted and wont open.

Background images have weird behavior

I have a weird error with background images. In my system, I loop through a number of pages each containing some HTML to output. This is the master page:

<html>
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="/home/vagrant/code/acme/app/storage/bootstrap.css">
        <style type="text/css">
            div.page:not(:first-child) {
                page-break-before: always;
            }
            div.page {
                background-image: url('/home/vagrant/code/acme/app/storage/bg.jpg');
                background-size: 100% 100%;
                height: 100%;
                width: 100%;
                color: white;
            }
        </style>
    </head>
    <body>
        @foreach($pages as $page)
            {{ $page }}
        @endforeach
    </body>
</html>

However, the output is not as expected: when I have 5 pages in the $pages array, I get 16 pages in the PDF. The first two pages are rendered correctly, but the third spans 2 pages, the fourth spans 4 pages and the fifth spans 8 pages. The content of each $page is just <div class="page">foo</div>.

How can I use background images with snappy?

Error setting option

knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf-amd64
        options:    
          redirect-delay: 1000

throws an invalid option exception

Removing lines 70-72 from Knp\Snappy\AbstractGenerator.php solves the problem but I see that this provides some validation.

How do I set the allowed options using the snappy-bundle?

Getting a Fatal Error

Fatal error: Class 'Knp\Snappy\Pdf' not found in /Users/joseym/Sites/tests/pdf/index.php on line 6

The process has been signaled with signal "5".

Warning: file_put_contents(/var/folders/xs/80v35bxd2xnbr36jq93qcl6m0000gn/T/knp_snappy53874552c8f521.74433518.html): failed to open stream: Permission denied in .....

/bin/wkhtmltopdf/wkhtmltopdf --lowquality '/var/folders/xs/80v35bxd2xnbr36jq93qcl6m0000gn/T/knp_snappy53874552c8f521.74433518.html' '/web/uploads/pdf/export_backgroundcheck_2014_05_29_09_33_52.pdf'

html breaks in two pages.

We are using wkhtmltopdf to export html to pdf. It breaks the HTML

in two pages of pdf. can we add break?

Can anybody confirm how we can insert page break at the time of conversion from html to pdf with wkhtmltopdf?

Error when installing wkhtmltopdf

When trying both wkhtmltopdf-amd64 and wkhtmltopdf-i386 through composer I get the following error:

Loading composer repositories with package information
Installing dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package google/wkhtmltopdf-amd64 could not be found in any version, there may be a typo in the package name.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.```

Special characters are not displayed properly with Snappy

When I print with wkhtml from the command line, no problem.
When I print with snappy, special characters are not displayed properly.
' becomes ’
é becomes é
and so on.

Maybe its an option that I have to set. Or a php extension that I am missing. Does it work with you to print special characters in snappy?

thanks.

For "wkhtmltoImage": is possible add functions/url at the param "'run-script'"?

Hi!

First off all, congratulations for your "library", is great!! ;-D

I have been studying the params relationated with "wkhtmltoImage", and one of the params is --run-script, but you only can add js code directly.

Is there any posibility (or do you know) of adding a URL of a 'file.js' in order to create functions or more code in a separated file (like the '-user-style-sheet' param)?

At the moment, I have checked that you can only add js code in one line, and it's a problem if you want to add more code :-(

  • I'm using the libwkhtmltox-0.11.0_rc1.zip (Win) and I'll install it in Linux too.

Thank you very much in advance!
Regards,

Cannot connect to server X

Hi,

When i use wkhtmltojpg from the command line it work but when i use it from my application it doesn't. That why i think it come from KnpSnappy.

The error:

The exit status code '1' says something went wrong:
stderr: "wkhtmltopdf: cannot connect to X server 
"
stdout: ""
command: /bin/wkhtmltopdf --lowquality --encoding 'utf-8' '/tmp/knp_snappy535a8764551075.01876888.html' '/tmp/knp_snappy535a87645513f8.46100863.pdf'.
wkhtmltopdf --version
Name:
  wkhtmltopdf 0.12.1-dev

Any ideas ?

How to make it work on Windows

Hello guys

I've been trying to put Snappy to work on Windows (IIS) with no success.

What I've done:

My code:

getOutput('http://www.github.com'); ?>

Result:
Shows one pdf file to open or save, but it's corrupted.

P.S: In the command line wkhtmltopdf works well.

I'm doing something wrong?

Thanks in advance,
Pete

Autoloader / Namespace in Zend

Hey there,

I am able to include the autoloader (require_once('snappy/src/autoload.php');) but when I specify the namespace (use Knp\Snappy\Pdf;) I get a fatal error (white screen) but nothing actually comes back in the error log.

Has anyone had any luck using snappy from within the Zend (1.12) framework?

Use toc parameter

I try to use the toc parameter without success.
The generated command contains --toc instead of toc.

Do you think it can be done easily ?

Thanks

Uncaught exception on start

Getting an error while trying to execute this code:

require_once 'src/autoload.php';
use Knp\Snappy\Pdf;
$snappy = new Pdf('/var/www/seos/bin/wkhtmltopdf-amd64');
$snappy->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', 'bill-1233.pdf');

Error message:
Fatal error: Uncaught exception 'RuntimeException' with message 'The file 'bill-1233.pdf' was not created (command: /var/bin/wkhtmltopdf-amd64 --lowquality '/tmp/knp_snappy50c77c04ba9bf1.73763694.html' 'bill-1233.pdf').' in /var/www/htdocs/src/Knp/Snappy/AbstractGenerator.php:261 Stack trace...

hanging process

On Windows, I'm using symfony/symfony@fae4523, KnpLabs/KnpSnappyBundle@b8be046, and wkhtmltopdf 0.11.0_rc1. When doing a conversion of a document and adding a footer with the footer-html option, the process is hanging until max_execution_time is reached. After that, the wkhtmltopdf process gets killed and the perfectly rendered PDF file is in the system's temp folder. So the conversion is already done at that moment.

The script is aborted with a timeout referred to

$stdout = stream_get_contents($pipes[1]);
.

I took another approach by removing the code in

protected function executeCommand($command)
and replacing it with

$process = new \Symfony\Component\Process\Process($command);
$process->run();
return array(
    $process->getExitCode(),
    $process->getOutput(),
    $process->getErrorOutput(),
);

to use Symfony's Process class and take advantage of symfony/symfony#4069. But even in this case the process is hanging and the script is aborted referring to https://github.com/symfony/symfony/blob/fae4523f3baf1595b1c632e4953f667e93149f9b/src/Symfony/Component/Process/Process.php#L360.

Without the footer-html option, everything runs fine.

key-value options

How are values for options

--cookie <name> <value>
--custom-header <name> <value>
--post <name> <value>
--post-file <name> <path>
--replace <name> <value>

meant to be passed to the generator? I couldn't find a proper way.

Release tag request

Could we have a new release tag to include the latest toc & cover option changes?
Thanks

Header and Footer

How do you setup a Header and Footer HTML with this class? I can't find the documentation anywhere :(

Proc_open on Mac

Sorry to bug you guys. I wish I could figure this out on my own but I'm utterly stuck at this point. I'm running a Mac with MAMP and can run wkhtmltopdf from the command line just fine. In fact I can run the exact command that Snappy is attempting to run (copied and pasted from $command) just fine and get the PDF I'm looking for. I've run chmod a+x and chmod 777 on the executable. I've changed the owner of the executable to the apache account. But when Snappy tries to run the command it fails with exit code 5 and nothing in stderr or stdout. Any ideas?

Error Acces to wkhtmltoimage with MAMP

Impossible de generate with php (MAMP PRO 2)

Fatal error: Uncaught exception 'RuntimeException' with message 'The file '/Users/sebastien/Documents/git/test/test.jpg' was not created (command: /usr/local/bin/wkhtmltoimage --format 'jpg' 'http://www.google.fr' '/Users/sebastien/Documents/git/test/test.jpg').' in /Users/sebastien/Documents/git/test/vendor/knplabs/knp-snappy/src/Knp/Snappy/AbstractGenerator.php:276 Stack trace: #0 /Users/sebastien/Documents/git/test/vendor/knplabs/knp-snappy/src/Knp/Snappy/AbstractGenerator.php(132): Knp\Snappy\AbstractGenerator->checkOutput('/Users/sebastie...', '/usr/local/bin/...') #1 /Users/sebastien/Documents/git/test/index.php(8): Knp\Snappy\AbstractGenerator->generate('http://www.goog...', '/Users/sebastie...') #2 {main} thrown in /Users/sebastien/Documents/git/test/vendor/knplabs/knp-snappy/src/Knp/Snappy/AbstractGenerator.php on line 276

$snappy = new Image('/usr/local/bin/wkhtmltoimage');
$snappy->generate("http://www.google.fr","/Users/sebastien/Documents/git/test/test.jpg");
?>

When i exec usr/local/bin/wkhtmltoimage --format 'jpg' 'http://www.google.fr' '/Users/sebastien/Documents/git/test/test.jpg' in a terminal, the image is generated.

PDF was not created

My code:

$html = $this->renderView('AcmeDemoBundle:Demo:pdfHello.html.twig', array(
'name' => $name,
));
$myProjetDirectory = '/var/www/symfony';

    $snappy = new Pdf($myProjetDirectory . '/vendor/google/wkhtmltopdf-i386/wkhtmltopdf-i386');

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

Erro:
The file '/tmp/knp_snappy51ea66b07d9299.07533021.pdf' was not created (command: /var/www/symfony/vendor/google/wkhtmltopdf-i386/wkhtmltopdf-i386 --lowquality '/tmp/knp_snappy51ea66b07d8b79.13624602.html' '/tmp/knp_snappy51ea66b07d9299.07533021.pdf').

I'm doing something wrong?

Temporary files are never deleted

Snappy create a lot of temporary files but never delete them.
On a production server, this could become problematic since the size of the temp dir could increase very fast.

When the input or the output are stored in a temporary file, these files should be deleted just before the result is returned.

Include wkhtml2pdf binaries as composer requires.

Hi,

I just start to do my own handler of wkhtml2pdf, when someone tell me about this project.

I include wkhtp2pdf as composer require, and as composer repositories as you can see here https://github.com/desarrolla2/php-wkhtmltopdf/blob/master/composer.json

And then i was thinking in initialize the environment as you can see in this constructor method https://github.com/desarrolla2/php-wkhtmltopdf/blob/master/src/Desarrolla2/WKHtml2Pdf/Handler.php

What about if i send PR for include this in this package?

Regards

getOutputFromHtml - no images

I have file.html with content below

<div class="Logo">
    <img src="/assets/ui/logo-commoncore.svg">
</div>

I use code below to render pdf

$fileContent = file_get_content('file.html');
$snappy = new Pdf('wkhtmltopdf');
header('Content-Type: application/pdf');
return $snappy->getOutputFromHtml($fileContent );

The image assets/ui/logo-commoncore.svg is not apears

but if i add absolute url it will fix the problem

<div class="Logo">
    <img src="http://mysite.com/assets/ui/logo-commoncore.svg">
</div>

How i can avoid to add sile_url to any image tag in page?
What is the native way to set path to images in php code ?

Not generating correct page

I am trying to use


$pageUrl = $this->generateUrl('arout', array(), true); 

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

It generating the login page of my web application. I am sure 'arout' do not rout to login page.

multiple input files

I installed and tested snappy library for pdf generating.
Everything works fine.
But is there a way to have multiple html url´s or html files as input.

When i try this:
$snappy->generate('http://bag2go.de http://bag2go.de/taschen.php http://bag2go.de/material.php', 'tmp/test-5.pdf');

i get this:
Error: Failed loading page http://bag2go.de/taschen.php http://bag2go.de/material.php

When i try the same on console bash it works:

wkhtmltopdf-i386 http://bag2go.de http://bag2go.de/taschen.php http://bag2go.de/material.php /var/www/upload/test.pdf

Any hints?

best regards

Klaus

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.

#29866d9 Escaping binary path breaks b/c

As nobody seemed to respond to my comment, Ill create it here.
We're passing the following as the path with the symfony2 snappy bundle:

  wkhtmltopdf_bin: 'export DISPLAY=:0;/bin/wkhtmltopdf'

The commit #29866d9 breaks that by enclosing the path in quotes.

cannot execute binary (on Mac OS X)

I get this error when below code runs

The file '/var/tmp/knp_snappy51db03691aa540.12804579.pdf' was not created (command: [site-dir]/vendor/google/wkhtmltopdf-i386/wkhtmltopdf-i386 --lowquality 'http://www.github.com' '/var/tmp/knp_snappy51db03691aa540.12804579.pdf').

$snappy = Helper::snappyPdf(); #this just returns snappy pdf object
echo $snappy->getOutput('http://www.github.com');

So I tried running wkhtmltopdf as sudo from command line (below code) and got a cannot execute binary error

[site path]/vendor/google/wkhtmltopdf-i386/wkhtmltopdf-i386 --lowquality 'http://www.github.com' '/var/tmp/knp_snappy51db03691aa540.12804579.pdf'

FYI I tried both 32 and 64 bit binaries and I installed wkhtmltopdf using composer

Process fails on Windows 8

When running HTML to image converter it hangs forever. The exec runs fine, and outputs the file and quits, but Snappy just hangs.

Installing Symfony Process fixes this, but then causes an error:

RuntimeException 0 The exit status code '3' says something went wrong:
stderr: "Qt: Untested Windows version 6.2 detected!

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
"
stdout: ""
command: wkhtmltoimage --format "jpg" --transparent "http://www.somesite.com/bla" "C:\Windows\knp_snappy516201a411f4c1.11355432.jpg".

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.