kriansa / h2p Goto Github PK
View Code? Open in Web Editor NEWH2P - Convert HTML to PDF using PHP and PhantomJS. Unmaintained.
Home Page: https://garajau.com.br/projects/h2p-convert-html-files-to-pdf/
H2P - Convert HTML to PDF using PHP and PhantomJS. Unmaintained.
Home Page: https://garajau.com.br/projects/h2p-convert-html-files-to-pdf/
Hi, I followed the readme to create a pdf. I am using 1.9.7 version of phantomjs.
My error log says
at PhantomJS ->convert ('/tmp/c7247b948ccddf19f9b8c86b1f3accc12b766178.tmp', '/tmp/c26d4285406f78a398c9d99234eef1cb3c822c25.tmp', 'A4', 'Portrait', '1cm')
in /home/seshachalam/Projects/post/vendor/kriansa/h2p/src/H2P/Converter.php at line 168
Hello, I like h2p so much, but I get an error when running. I'm sorry if it's a newbie question:
Fatal error: Class 'H2P\Converter' not found in /var/www/public/index.php on line 15
This is my index.php
It's located in public/index.php
and my composer.json
and vendor
folder are in the root.
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use H2P\Converter;
use H2P\Converter\PhantomJS;
use H2P\TempFile;
// Set the input content to convert $input = new TempFile($htmlString);
$input = 'http://www.google.com/';
// $input = '/path/to/file.html';
// Then do the conversion $output = new TempFile();
$output = new TempFile();
$instance = new Converter(new PhantomJS(), $input, $output);
$instance->convert();
// Save it somewhere $output->save('/another/path/to/file.pdf');
// or output it header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($output->getFileName()));
echo $output->getContent();
This is the line where I get the error:
...
$instance = new Converter(new PhantomJS(), $input, $output);
...
I already required the vendor autoload but I can't pass that error.
Thank you for your help.
— Asael
Olá. Estou gerando alguns PDF´s, mas o tamanho médio é de 600k.
Quando eu abro eles no Acrobat PDF e peço pra salvar como PDF otimizado, o tamanho já diminui pela metade.
Pergunta: É possível a seleção de DPI ou alguma resolução, para diminuir o tamanho do PDF?
Obrigado.
I would like to add zoom
and margin
and footer
and header
support.
We can of course, keep adding parameters to __construct()
in converter
, but pretty soon, we will end up in argument hell.
What do you think about reworking the constructor, so that all arguments will be passed in as an element in an associative array?
We can then convert the associative array to json and passed it to converter.js
.
E aí, blz? Estou tentando executar um dos exemplos e está me retornando esse erro. Fiz teste em uma distribuição linux e em um windows 7. No linux compilei o executável e no windows fiz o download. Vi que tem mais gente com o mesmo problema, o que seria?
Fatal error: Uncaught exception 'H2P\Exception' with message 'Error while executing PhantomJS: "SyntaxError: JSON Parse error: Expected '}'"' in
C:\xampp\htdocs\h2p\src\H2P\Converter\PhantomJS.php on line 283 H2P\Exception: Error while executing PhantomJS: "SyntaxError: JSON Parse error: Expected '}'" in C:\xampp\htdocs\h2p\src\H2P\Converter\PhantomJS.php on line 283
In case of a js error (on the page that phantomjs is trying to render) the converter returns the Exception but with success true and thus the page created.
I discovered the error within a page that uses "requestAnimationFrame" js object, and as far as I know Phantomsjs doesn't deal with it.
I'm working on handling the errors with phantomjs native handler like:
page.onError = function(msg, trace) {
var msgStack = ['[ERROR]' + msg + " in " + page.url + "[/ERROR]"];
if (trace && trace.length)
{
msgStack.push('[TRACE]');
trace.forEach(function(t)
{
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
});
msgStack.push('[/TRACE]');
}
returnConsoleMsg(msgStack.join('\n'), false);
};
function returnConsoleMsg(msg, result)
{
console.log(JSON.stringify({
success: result,
response: msg
}));
// Stop the script
phantom.exit(0);
}
Here is my script in the PHP file:
require_once("include/h2p/autoloader.php");
use H2P\Converter\PhantomJS;
use H2P\TempFile;
$converter = new PhantomJS();
$input = new TempFile('test string to pdf', 'html'); // Make sure the 2nd parameter is 'html'
$converter->convert($input, '/pdf/testpage.pdf');
Here is the error:
Fatal error: Uncaught exception 'H2P\Exception' with message 'Error while executing PhantomJS: ""' in /h2p/src/H2P/Converter/PhantomJS.php:283 Stack trace: #0 /h2p/src/H2P/Converter/ConverterAbstract.php(136): H2P\Converter\PhantomJS->transform(Object(H2P\Request), '/...') #1 /h2ptest.php(19): H2P\Converter\ConverterAbstract->convert(Object(H2P\TempFile), '/...') #2 {main} thrown in /h2p/src/H2P/Converter/PhantomJS.php on line 283
Nao estou conseguindo rodar nem o exemplo
instalei via composer, copiei o executavel para pasta certa mas mesmo assim da erro
'Error while executing PhantomJS: "SyntaxError: JSON Parse error: Expected '}'"'
eu tentei a dica em outro topico falando para nao usar escapeshellarg no windows mas nada funcionou
poderia ajudar?
obrigado
I really like how the wip-2.0 branch is coming along! I will give it more testing when I get some time later.
I notice that you have allowed defining headers and footers in PHP. What do you think about adding an additional way to define as a script like here: https://github.com/kriansa/h2p/pull/6/files#L0R83
The main reason is that in some cases, I am generating pdfs from templates which are built using twig.
In those cases, it makes sense for the header and footer template snippets to be in the template file rather than being defined in PHP code during run time.
So, we could do something like this:
When writing HTML to a PDF file using the h2p
class I notice there is quality loss on the images.
Any tips?
I've added the quality
parameter to the render
function inside the converter.js
file, but that does not show any difference.
page.render(options.destination, { format: 'pdf', quality: '100' });
I've also set the page DPI to 72 and higher... no difference.
I'm using this simple code to generate a PDF:
<?php
//include('autoload.php');
include('h2p/autoloader.php');
use H2P\Converter\PhantomJS;
use H2P\TempFile;
$filename = time();
$converter = new PhantomJS();
$input = new TempFile('<html>THIS IS A TEST</html>', 'html'); // Make sure the 2nd parameter is 'html'
// Convert destination accepts H2P\TempFile or string with the path to save the file
$converter->convert($input, $filename.'.pdf');
?>
The PDF is generated but it's 0 KB and Adobe Reader says it's corrupted when trying to open it.
My application is currently running on Windows 10 (via XAMPP) and I've put PhantomJS.exe (version 2.1) in h2p/bin/win32 folder.
No error are reported, even in console.
The PHP page that is running the script is placed in the root.
Any suggestion?
Library is creatin following command on window
"C:\www\myproject\vendor\kriansa\h2p\bin/win32/phantomjs.exe" "C:\www\myproject\vendor\kriansa\h2p\bin/converter.js" "{ destination : C:\Windows\TEMP\14b6e6edc209b6e731bdbc79976a9430438409ae.tmp , request :{ uri : C:\Windows\TEMP\127ef8f78c335d9af694a9cef0423541dd17a256.html , method : GET }, orientation : Portrait , format : A3 , zoomFactor :1, allowParseCustomFooter :false, allowParseCustomHeader :false, border : 1cm , header :null, footer :null}"
When I run this command it is giving me parse error . Seems json is not getting created properly
I am using PhantomJS 1.9.1 on Ubuntu 13.04 64-bit.
When converting a temp file (using an HTML string in my case), the process fails.
$html = "<html><body><h1>Hello world!</h1></body></html>";
$input = new TempFile($html);
$output = new TempFile();
$instance = new Converter(new PhantomJS('/usr/bin/phantomjs'), $input, $output);
$instance->convert();
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($output->getFileName()));
echo $output->getContent();
This results in this exception:
Fatal error: Uncaught exception 'H2P\Exception' with message 'Error while executing PhantomJS: Unable to access the URI!' in /server/h2p-master/src/H2P/Adapter/PhantomJS.php on line 187
For html strings, we can set page.content
in converter.js
. However, we will still need to find a way to read local files, not sure if phantomjs support this.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.