Converting HTML to PDF via PHP (install font for h

2019-09-08 14:41发布

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

3条回答
SAY GOODBYE
2楼-- · 2019-09-08 15:21

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);
查看更多
家丑人穷心不美
3楼-- · 2019-09-08 15:32

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

查看更多
来,给爷笑一个
4楼-- · 2019-09-08 15:35

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

查看更多
登录 后发表回答