我正在尝试使用mPDF 类创建 PDF 文件,我需要它自动调整文档高度,而不是在底部创建空白。
这是两个不同生成的 PDF 的两张图像,内容不同。左图比右图内容更多,因此底部空间更大。
我希望它根本没有空间。到目前为止,这就是我所尝试过的。
public function __construct()
{
/*
* Encoding
* Size (Array(Xmm, Ymm))
* Font-size
* Font-type
* margin_left
* margin_right
* margin_top
* margin_bottom
* margin_header
* margin_footer
* Orientation
*/
$this->mPDF = new mPDF('utf-8', array(56, 1000), 9, 'freesans', 2, 2, 2, 0, 0, 0, 'P');
}
Run Code Online (Sandbox Code Playgroud)
它以 1000 高度开始文档,以便比最初所需的长度更长。
public function write($html, $url)
{
/*
* Writing and remove the content, allows the setAutoTopMargin to work
*
* http://www.mpdf1.com/forum/discussion/621/margin-top-problems/p1
*/
$this->mPDF->WriteHTML($html[0]);
$pageSizeHeight = $this->mPDF->y;
$this->mPDF->page = 0;
$this->mPDF->state = 0;
unset($this->mPDF->pages[0]);
foreach($html as $content)
{
$this->mPDF->addPage('P', '', '', '', '', 2, 2, 2, 0, 0, 0, '', '', '', '', '', '', '', '', '', array(56, $pageSizeHeight));
$this->mPDF->WriteHTML($content);
}
$this->mPDF->Output($url);
}
Run Code Online (Sandbox Code Playgroud)
因此,正如您所看到的,write()在某个时刻调用该函数时,我抓住了Y值,以便可以使用它来设置文档高度。不幸的是,它没有达到我期望的效果,即完全填充文档而没有任何空白。
使用$pageSizeHeight也无济于事,因为它可能适用于一个文档,但不适用于另一个文档,如下所示:
$pageSizeHeight = $this->mPDF->y - 20;
Run Code Online (Sandbox Code Playgroud)
解决了。
我的代码中存在一个问题,即创建了如此多的空间,而且它与 CSS 结构有关。
body { font-size: 80% }
Run Code Online (Sandbox Code Playgroud)
更改为 100% 解决了空白,但我也查看了 mPDF 类,找到了该_setPageSize()函数。
public function write($html, $url)
{
/*
* Writing and remove the content, allows the setAutoTopMargin to work
*
* http://www.mpdf1.com/forum/discussion/621/margin-top-problems/p1
*/
$this->mPDF->WriteHTML($html[0]);
$this->mPDF->page = 0;
$this->mPDF->state = 0;
unset($this->mPDF->pages[0]);
// The $p needs to be passed by reference
$p = 'P';
$this->mPDF->_setPageSize(array(56, $this->mPDF->y), $p);
foreach($html as $content)
{
$this->mPDF->addPage();
$this->mPDF->WriteHTML($content);
}
$this->mPDF->Output($url);
}
Run Code Online (Sandbox Code Playgroud)