Converting HTML to PDF via PHP (install font for html2pdf) - php

I'm currently attempting to convert HTML markup (from an xml feed) into a PDF dynamically via a PHP script.
From reading other answers the best free way of doing this seemed to be to use html2pdf.
// HTML2PDF
require_once('/public_html/html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('P','A4','en');
$html2pdf->WriteHTML($htmlContent);
$html2pdf->Output('/public_html/wp-content/uploads/rns/html2pdf.pdf');
The problem I'm having is my $htmlContent contains the css: FONT-FAMILY: "Times New Roman","serif" in various places and my script gives the error:
TCPDF ERROR: Could not include font definition file: "times new roman"
I've googled and the only documentation is this:
http://wiki.spipu.net/doku.php?id=html2pdf:en:v4:font
Which in turn leads you to:
http://www.tcpdf.org/fonts.php
I'm lost though, the second link says that times/Times New Roman is a core PDF font... I've tried various things and get the same error.
What would I actually need to write to add the font, or alternatively, how could I strip all of the FONT-FAMILY classes out of the $htmlContent (I don't even need it in any particular font, just one that works).

Yes, you should use DOMPDF instead of other libraries. There are lots of fonts available. You can see at "dompdf/lib/fonts/dompdf_font_family_cache.dist.php" and choose according to your requirements. For change the font you need to change the def("DOMPDF_DEFAULT_FONT", "serif") at file path "dompdf/dompdf_config.inc.php":
You can download the latest version available of DOMPDF from: https://code.google.com/p/dompdf/downloads/detail?name=dompdf_0-6-0_beta3.tar.gz&can=2&q=
See the below example:
require_once("dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$dompdf->load_html($htmlContent);
$dompdf->render();
$fileName = "invoice.pdf";
$dompdf->stream($fileName);//DOWNLOAD PDF
//GET OUTPUT AS STRING AND PUT IN TO SOME FILE
$output = $dompdf->output();
file_put_contents($fileName, $output);

Try to use DomPdf instead of html2pdf. It works great for me on creating invoices in PDF. But some treatments (positioning and font sizes) in your CSS code are needed. The screen content placed as it is didn't work as i expected.
https://github.com/dompdf/dompdf

It's a bit of a hack, but I found the best way for me was to call capturejs using exec:
$run = "capturejs -u ";
$run .= "https://www.example.com/";
$run .= " -p tlsv1 -V ";
$run .= "1024x768";
$run .= " -o 'myimage.png'";
exec($run);
https://github.com/superbrothers/capturejs

Related

(Inline) PHP in domPDF 7.0

I switched from TCPDF to domPDF because it seems more convenient to handle when creating invoices from html to pdf (I am rather a low pro on PHP :)). Now that I created the html file as a PDF file I recognized it does not output any PHP in the PDF - since the data from my sql databanks should fill the PDF it is kinda a problem.
I saw that you can enable PHP in the options.php included in the src-folder and I tried to do like it is written in the manual (and also tried various other code lines) but it just doesn't want to work:
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
require_once ("$root/../xxx/dompdf/autoload.inc.php");
use Dompdf\Dompdf;
use Dompdf\Options;
$options = new Options();
$options->setIsPhpEnabled('true');
$dompdf = new Dompdf($options);
$dompdf->loadHtml(file_get_contents("testdomhtml.php"));
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("bla",array("Attachment"=>0));
The PDF is shown but without the input from any PHP code.
If someone would be so kind, I would also be interested in knowing why and in how far enabling PHP is a security risk since I actually want to use that for my business. Would it be more advisable to wrap it all up in the main php file without loading external html and css files?
Thanks a lot in advance!
You could do something like this (not tested the code). Replace
$dompdf->loadHtml(file_get_contents("testdomhtml.php"));
With
ob_start();
include 'testdomhtml.php';
$output = ob_get_clean();
$dompdf->loadHtml($output);
More options How to execute and get content of a .php file in a variable?
Your file_get_contents("testdomhtml.php") will get actual content of file and will not execute any code inside it. Instead make it web accessible and pass URL to this page:
$dompdf->load_html_file('http://yourdomain.ext/testdomhtml.php');

curl or file_get_contents needs full url path

I use this code to generate a QR Code and display it:
<?php
$aux = 'qr_img0.50j/php/qr_img.php?';
$aux .= 'd=Text&';
$aux .= 'e=H&';
$aux .= 's=4&';
$aux .= 't=P';
?>
<img width="250" src="<?php echo $aux; ?>" />
It generates and displays it without problems,
but I don't want to display it, but load it into "dompdf" (PHP PDF Generator).
I found out, that I can't give dompdf the "$aux" variable ("< img src='$aux' />"). The variable returns the correct string, but dompdf can't display it (Probably due to being a PHP file).
I came up with file_get_contents, but surprisingly, it returned a blank file.
I used:
file_put_contents('tempqr.png', file_get_contents($qrc));
It is not due to wrong permissions, because...
when I typed the entire URL path, it 'copied' the file successfully (http://localhost:2180/work/qr_img0.50j/php/qr_img.php?...), but I think that's not a reliable solution, because of the port and stuff that can change over time. I installed cURL, and the same issue persists: It only displays with the full URL path. I tried fopen to 'read' the image into a buffer, and the buffer remained blank.
Maybe anyone can help me (and other readers), to get those two functions to load the file (maybe without the whole http unreliable thing?).
Or maybe there's another way to generate images from "qr_img0.50j" without calling php that I didn't know...
Dompdf (as of 0.6.1) will no longer parse PHP in your document. You will need to do that prior to passing the document to Dompdf. Probably the easiest method to do this is to render the image and insert it into the document as a data-uri.
You may have to modify your QR generator to work in this flow if it's not designed for command-line execution. Ideally it would just be a callable function, which is what I presumed for the sample.
With Dompdf 0.7.x:
<?php
// require dompdf autoloader, then ...
using Dompdf\Dompdf;
$image = qr_img('Text', 'H', '4', 'P'); // assumine PNG output
$html = '<img width="250" src="data:image/png;base64,' . base64_encode($image) . '" />';
$dompdf = new Dompdf();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream();
?>
FYI, the same issue applied to file_get_contents. It does not parse the PHP of a file. It can only be used to get the file itself.
Regardless of the particular method you use to get a file the results depend on the source. Files retrieved from the local file system will not have their PHP parsed. Files retrieved via a web server will.

Generate PDF from HTML/CSS/PHP in Symfony 1.4

I am working on a Symfony 1.4 project. I need to make a PDF download link for a (yet to be) generated voucher and I have to say, I am a bit confused. I already have the HTML/CSS for the voucher, I created the download button in the right view, but I don't know where to go from there.
Use Mpdf to create the pdf file
http://www.mpdf1.com/
+1 with wkhtmltopdf
I'd even recommand the snappy library.
If you use composer, you can even get the wkhtmltopdf binaries automatically
Having used wkhtmltopdf for a while I've moved off it as 1) it has some serious bugs and 2) ongoing development has slowed down. I moved over to PhantomJS which is proving to be much better in terms of functionality and effectiveness.
Once you've got something like wkhtmltopdf or PhantomJS on your machine you need to generate the HTML page and pass that along to it. I'll give you an example assuming you use PhantomJS.
Initially set what every request parameters you need to for the template.
$this->getRequest->setParamater([some parameter],[some value]);
Then call the function getPresentation() to generate the HTML from a template. This will return the resulting HTML for a specific module and action.
$html = sfContext::getInstance()->getController()->getPresentation([module],[action]);
You'll need to replace the relative CSS paths with a absolute CSS path in the HTML file. For example by running preg_replace.
$html_replaced = preg_replace('/"\/css/','"'.sfConfig('sf_web_dir').'/css',$html);
Now write the HTML page to file and convert to a PDF.
$fp = fopen('export.html','w+');
fwrite($fp,$html_replaced);
fclose($fp)
exec('/path/to/phantomjs/bin/phantomjs /path/to/phantomjs/examples/rasterize.js /path/to/export.html /path/to/export.pdf "A3");
Now send the PDF to the user:
$this->getResponse()->clearHttpHeaders();
$this->getResponse()->setHttpHeader('Content-Description','File Transfer');
$this->getResponse()->setHttpHeader('Cache-Control','public, must-revalidate, max-age=0');
$this->getResponse()->setHttpHeader('Pragma: public',true);
$this->getResponse()->setHttpHeader('Content-Transfer-Encoding','binary');
$this->getResponse()->setHttpHeader('Content-length',filesize('/path/to/export.pdf'));
$this->getResponse()->setContentType('application/pdf');
$this->getResponse()->setHttpHeader('Content-Disposition','attachment; filename=export.pdf');
$this->getResponse()->setContent(readfile('/path/to/export.pdf'));
$this->getResponse()->sendContent();
You do need to set the headers otherwise the browser does odd things. The filename for the generated HTML file and export should be unique to avoid the situation of two people generating PDF vouchers at the same time clashing. You can use something like sha1(time()) to add a randomised hash to a standard name e.g. 'export_'.sha1(time());
Use wkhtmltopdf, if possible. It is by far the best html2pdf converter a php coder can use.
And then do something like this (not tested, but should be pretty close):
public function executeGeneratePdf(sfWebRequest $request)
{
$this->getContext()->getResponse()->clearHttpHeaders();
$html = '*your html content*';
$pdf = new WKPDF();
$pdf->set_html($html);
$pdf->render();
$pdf->output(WKPDF::$PDF_EMBEDDED, 'whatever_name.pdf');
throw new sfStopException();
}

Output Buffer + Pdf - PHP

I have a page that uses the glob function and file_get_contents to have a few html files and store them in the buffer.
So I want to convert this buffer ob_get_contents() to an pdf file.
What is the best way to do that? how?
Thanks in advance.
For creating PDF files from HTML and CSS, check out DOMpdf.
While this solution doesn't support the full range of HTML and CSS and its rendering can be a pain sometimes, it has one advantage: it does not require any special binaries to be installed (like wkhtmltopdf). It should run on your average shared PHP hosting.
Usage example:
<?php
require_once("dompdf_config.inc.php");
$html =
'<html><body>'.
'<p>Put your html here, or generate it with your favourite '.
'templating system.</p>'.
'</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("sample.pdf");
?>
why using the outputbuffer for this? you have it in variables using file_get_contents and can simply create your pdf with the data from the variables. when using ob_get_contents all it does is return the outputbuffer and what you normally do with the result is saving into a variable...
btw. you do want to convert html into pdf? If yes have a look at wkhtmltopdf
If ob_get_contents contains html files they are so many solutions out there that can achieve what you want. I think you should look at the following
PrinceXML
FPDF
TCPDF
HTML to PDF converter (PHP5)
wkhtmltopdf
Example using Simple HTML 2 PDF using PHP
$html = ob_get_contents();
ob_end_clean();
$pdf = new HTML2FPDF();
$pdf->SetTopMargin(1);
$pdf->AddPage();
$pdf->WriteHTML($html);
$pdf->Output('test.pdf','D');

Writing PDF using PHP (PDFLib)

I'm currently writing a code to output a pdf file in PHP using PDFlib from http://www.pdflib.com/. The problem is all html tag is also written in the output file. How can be able to cancel out all those tags?
Here is my sample code.
$postVariable = $_POST;
$contentData = "";
foreach($postVariable as $key => $value){
if(is_array($key)){
foreach($key as $key1 => $value1){
$contentData.= $key1 .": ". $value1."<nextline>";
}
}else{
$contentData.= $key .": ". $value."<nextline>";
}
}
$testdata = nl2br($contentData);
$pdf = pdf_new();
// open a file
pdf_open_file($pdf, $_SERVER['DOCUMENT_ROOT']."cas".DIRECTORY_SEPARATOR."$filename.pdf");
// start a new page (A4)
pdf_begin_page($pdf, 595, 842);
// Locate Font Directory
$fontdir = "C:\WINDOWS\Fonts";
// Font Name Parameters
pdf_set_parameter($pdf, "FontOutline", "arialMyName=$fontdir\arial.ttf");
// Find Font
$arial = PDF_findfont($pdf,"arialMyName","host",0 );
// Set font size and font name
pdf_setfont($pdf, $arial, 10);
//$arial = pdf_findfont($pdf, "Arial", "host", 1);
//pdf_setfont($pdf, $arial, 10);
// print text
pdf_show_xy($pdf, "TO THE UNIT OWNER",50, 750);
pdf_show_xy($pdf, "Test ext", 50,730);
pdf_show_xy($pdf, "test test", 50,715);
pdf_show_xy($pdf, $contentData, 50,700);
// end page
pdf_end_page($pdf);
// close and save file
pdf_close($pdf);
and the sample output is:
TO THE UNIT OWNER
Test text
test test
type: Apartment****var_name: ****var_company: ****var_date: ****submit: Save and Download<
It disregards the html tags and it include it on the content.
Is there any other methods on how to print out HTML to PDF using the library that I'm currently using (PDFlib).
Thanks.
regards,
Resty
I would recommend the TCPDF library. It can convert your HTML to a PDF file, including CSS code. It has support for quite a lot of HTML tags, and does a decent job. HOWEVER, from personal experience, while it is very possible to generate high quality PDF files with it, the results are not always 100% as expected. It might need a bit of tweaking and fiddling to get the result you want.
If you only want to remove the HTML tags, I think you might want to take a look at strip_tags. But I guess that's not really what you're after.
Finally, there's a really really cool new kid on the block - a PHP extension that uses the WebKit HTML and rendering engine to generate PDFs. It is called the libwkhtmltox extension and can be found here. It produces amazing results. For example, look at this PDF it made from the homepage of the New York Times - see (http://www.2shared.com/document/kYuS_G7p/nytimes.html - click "save to my pc" down below). That output was generated without specifying any additional options. Exceptional. HOWEVER, you need to get it running as PHP extension, and that might be a non-trivial task. So I would say: stick with the TCPDF library for now.
You cannot generate PDF content from HTML by using PDFLib. Ok, you can write convertor, but that's a huge work to do.
I recommend using TCPDF which supports HTML input.
Man... I was trying to do same thing once. It is very hard to work with pdflib directly.
I found this project, hosted on Google code site. The project deserved 10 stars out of 5.
It is called DOM PDF, you can download it here. You can generate PDFs from HTML pages, with CSS support. You can generate PDF with less than 10 lines of code!
Look at samples to see it in action.

Categories