如何设置自定义宽度和高度的pdf使用dompdf


How to set custom width and height of pdf using dompdf?

当我使用dompdf创建我的pdf时,它生成它作为默认的宽度和高度。我想设置自定义宽度和高度的我创建的pdf。如果在dompdf中不可能,那么请建议使用其他php插件。

默认情况下渲染的是US Letter,你可以使用:

$dompdf->setPaper(DEFAULT_PDF_PAPER_SIZE, 'portrait');

你可以用'letter', 'legal', 'A4'等。

不过你可以这样设置你自己的大小:

$customPaper = array(0,0,360,360);
$dompdf->setPaper($customPaper);

更多信息:https://github.com/dompdf/dompdf/wiki/Usage

我正在寻找如何使文档的高度动态打印在热敏纸卷上。这是我使用DomPDF得到的最接近的解决方案。

  • 你需要创建包含所有属性的文件并加载html:

     $pdf = new Dompdf();
     $options = $pdf->getOptions();
     $pdf->set_paper(array(0, 0, 164.44, 842.07), 'portrait');
     $options->set(array(
         'isRemoteEnabled' => true,
         'isHtml5ParserEnabled' => true
     ));
     $pdf->setOptions($options);
     $pdf->loadHtml($template);
    
  • 在渲染之前,定义一个回调函数,并在全局数组中定义一个存储高度的变量,之后,进行渲染并取消pdf对象的设置,现在您拥有文件的主体高度加上100 px。

     /*
     * Workaround to get the body height
     */
     $GLOBALS['bodyHeight'] = 0;
     $pdf->setCallbacks([
         'myCallbacks' => [
             'event' => 'end_frame', 
             'f' => function ($frame) {
                 $node = $frame->get_node();
                 if (strtolower($node->nodeName) === "body") {
                     $padding_box = $frame->get_padding_box();
                     $GLOBALS['bodyHeight'] += $padding_box['h'];
                 }
             }
         ]
     ]);
     $pdf->render();
     unset($pdf);
     $docHeight = $GLOBALS['bodyHeight'] + 100;
    
  • 现在你需要再次创建你的文件,但是现在你有了你需要定义的pdf文件的高度。

     $pdf = new Dompdf();
     $options = $pdf->getOptions();
     $pdf->setPaper([0,0,227, $docHeight]);
    

来源:创建一个具有自动高度

的单页PDF文件