DOM PDF generate only 1 page pdf skip remaining co

2019-07-14 03:32发布

I have the following code which uses DOM PDF Library for converting Html content to PDF file.

$dompdf = new DOMPDF();
$dompdf->set_paper(array(0,0,450,306));
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
file_put_contents($pdf_path, $output);

But it generates 2-3 pages based on the html content. I wanted to limit it to single page only and skip the remaining content.

标签: php pdf dompdf
1条回答
时光不老,我们不散
2楼-- · 2019-07-14 04:25

The easiest way is to render to image. The GD adapter allows you to specify the page you want to render.

dompdf 0.6.2 or earlier: set DOMPDF_PDF_BACKEND to "GD" which only renders the first page of the document.

dompdf 0.7.0 or later: $dompdf->set_option('pdfBackend', 'GD');. This release renders all pages and allows you to specify the page to output/stream (default is to send the first page).

If you really need to render only the first page to a PDF that's a bit more difficult. Though technically possible to do this only with dompdf I'd actually be inclined to fully render the PDF then use an external library to pull out just the first page.

For example, with libmergepdf you could do it like this:

use iio\libmergepdf\Merger;
use iio\libmergepdf\Pages;
use Dompdf\Dompdf;

$m = new Merger();

$dompdf = new Dompdf();
$dompdf->load_html('...');
$dompdf->render();
$m->addRaw($dompdf->output(), new Pages('1'));

file_put_contents('onepager.pdf', $m->merge());

(specific to dompdf 0.7.0, but code is nearly the same for 0.6.2)

查看更多
登录 后发表回答