dompdf: white margin on A4 page

2019-07-16 18:34发布

问题:

I am using dompdf (a PHP library) to create a PDF page and I have a problem to set proper dimensions. When I use CSS property:

@page {
    size: 21cm 29.7cm; 
}

… and for example I want to have the upper part of the page in red color, the PDF file is OK, but after print I got white margin. How can I fix it?

回答1:

You've set the size of the page, but not the content boundaries. If you don't want any border on the page you have to set the page margins to 0.

@page {
  size: 21cm 29.7cm;
  margin: 0;
}

This removes the margin around the body, but it also means that your content will bump up against the page edge. If you want the body content to having some spacing from the edge give it some padding.

body {
  padding: .5in;
}


回答2:

nolbadi111:

Did you set the right paper size, with setPaper() function?

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml('hello world');

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();

Reference: https://github.com/dompdf/dompdf



回答3:

Ok, so the problem was not with the domPDF, but with the printer settings. To acheive the goal you have to set borderless property.

btw. when you use

$dompdf->setPaper('A4', 'landscape');

you don't need to set page size property in css (but it helps during creating page in html)