php使用mpdf实现html转pdf

使用composer安装mpdf,选择适合自己的版本:

https://packagist.org/packages/mpdf/mpdf

手册:

http://mpdf.github.io/

本文使用的mpdf版本:7.0

基本使用:

$mpdf = new Mpdf();
$mpdf->WriteHTML('内容');
//自动分析录入内容字体 不设置会导致乱码
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
//输出到页面
$mpdf->Output();
//生成文件
$mpdf->Output('生成文件的路径');

页眉页脚:

//html页眉页脚 可以控制更详细的样式
$mpdf->SetHTMLHeader('<div>页眉</div>');
$mpdf->SetHTMLFooter('<div>页脚</div>');

//页眉
$mpdf->SetHeader('页眉');
$mpdf->SetFooter('页脚');
$mpdf->defaultheaderline = 0;//页眉线宽度
$mpdf->defaultfooterline = 0;//页脚线宽度

页码:

//{PAGENO}当前页码 {nb}总页数
$mpdf->SetHTMLFooter('<div>{PAGENO}/{nb}</div>');

水印:

//文字水印
$mpdf->SetWatermarkText('文字水印',0.2);//水印内容 透明度
$mpdf->watermark_font = 'GB';//设置字体
$mpdf->watermarkAngle = '45';//旋转角度
$mpdf->showWatermarkText = true;//开启文字水印
//关于文字水印字体大小 我使用的mpdf版本中,官方好像在调用watermark方法时好像给写死了,如有需要可以搜索watermark方法自己调整 //图片水印 图片路径可以是网络路径
$mpdf->SetWatermarkImage('图片路径',0.4,[100,100],[0,0]);//图片路径 透明度 水印大小 水印位置 $mpdf->showWatermarkImage = true;//开启图片水印

遇到的问题:

1.水印无法平铺,解决办法:

文字水印:

找到 Mpdf.php 中的 watermark 方法,

$this->Text($wx, $wy, $texte, $OTLdata, $textvar); 修改为: 

    //平铺文字水印
    $this->Text(-50, 200, $texte, $OTLdata, $textvar);

    $this->Text(0, 150, $texte, $OTLdata, $textvar);
    $this->Text(0, 250, $texte, $OTLdata, $textvar);

    $this->Text(50, 100, $texte, $OTLdata, $textvar);
    $this->Text(50, 200, $texte, $OTLdata, $textvar);
    $this->Text(50, 300, $texte, $OTLdata, $textvar);

    $this->Text(100, 50, $texte, $OTLdata, $textvar);
    $this->Text(100, 150, $texte, $OTLdata, $textvar);
    $this->Text(100, 250, $texte, $OTLdata, $textvar);

    $this->Text(150, 0, $texte, $OTLdata, $textvar);
    $this->Text(150, 100, $texte, $OTLdata, $textvar);
    $this->Text(150, 200, $texte, $OTLdata, $textvar);

    $this->Text(200, 50, $texte, $OTLdata, $textvar);
    $this->Text(200, 150, $texte, $OTLdata, $textvar);

    $this->Text(250, 100, $texte, $OTLdata, $textvar);

图片水印:

找到 Mpdf.php 中的 Image 方法,修改的代码标黄了,大概就是位置支持了二维数组,有需要可以自己改,这里仅供参考:

function Image($file, $x, $y, $w = 0, $h = 0, $type = '', $link = '', $paint = true, $constrain = true, $watermark = false, $shownoimg = true, $allowvector = true)
    {
        $orig_srcpath = $file;
        $this->GetFullPath($file);

        $info = $this->imageProcessor->getImage($file, true, $allowvector, $orig_srcpath);
        if (!$info && $paint) {
            $info = $this->imageProcessor->getImage($this->noImageFile);
            if ($info) {
                $file = $this->noImageFile;
                $w = ($info['w'] * (25.4 / $this->dpi));  // 14 x 16px
                $h = ($info['h'] * (25.4 / $this->dpi));  // 14 x 16px
            }
        }
        if (!$info) {
            return false;
        }
        // Automatic width and height calculation if needed
        if ($w == 0 and $h == 0) {
            /* -- IMAGES-WMF -- */
            if ($info['type'] == 'wmf') {
                // WMF units are twips (1/20pt)
                // divide by 20 to get points
                // divide by k to get user units
                $w = abs($info['w']) / (20 * Mpdf::SCALE);
                $h = abs($info['h']) / (20 * Mpdf::SCALE);
            } else {             /* -- END IMAGES-WMF -- */
                if ($info['type'] == 'svg') {
                    // returned SVG units are pts
                    // divide by k to get user units (mm)
                    $w = abs($info['w']) / Mpdf::SCALE;
                    $h = abs($info['h']) / Mpdf::SCALE;
                } else {
                    // Put image at default image dpi
                    $w = ($info['w'] / Mpdf::SCALE) * (72 / $this->img_dpi);
                    $h = ($info['h'] / Mpdf::SCALE) * (72 / $this->img_dpi);
                }
            }
        }
        if ($w == 0) {
            $w = abs($h * $info['w'] / $info['h']);
        }
        if ($h == 0) {
            $h = abs($w * $info['h'] / $info['w']);
        }

        /* -- WATERMARK -- */
        if ($watermark) {
            $maxw = $this->w;
            $maxh = $this->h;
            // Size = D PF or array
            if (is_array($this->watermark_size)) {
                $w = $this->watermark_size[0];
                $h = $this->watermark_size[1];
            } elseif (!is_string($this->watermark_size)) {
                $maxw -= $this->watermark_size * 2;
                $maxh -= $this->watermark_size * 2;
                $w = $maxw;
                $h = abs($w * $info['h'] / $info['w']);
                if ($h > $maxh) {
                    $h = $maxh;
                    $w = abs($h * $info['w'] / $info['h']);
                }
            } elseif ($this->watermark_size == 'F') {
                if ($this->ColActive) {
                    $maxw = $this->w - ($this->DeflMargin + $this->DefrMargin);
                } else {
                    $maxw = $this->pgwidth;
                }
                $maxh = $this->h - ($this->tMargin + $this->bMargin);
                $w = $maxw;
                $h = abs($w * $info['h'] / $info['w']);
                if ($h > $maxh) {
                    $h = $maxh;
                    $w = abs($h * $info['w'] / $info['h']);
                }
            } elseif ($this->watermark_size == 'P') { // Default P
                $w = $maxw;
                $h = abs($w * $info['h'] / $info['w']);
                if ($h > $maxh) {
                    $h = $maxh;
                    $w = abs($h * $info['w'] / $info['h']);
                }
            }
            // Automatically resize to maximum dimensions of page if too large
            if ($w > $maxw) {
                $w = $maxw;
                $h = abs($w * $info['h'] / $info['w']);
            }
            if ($h > $maxh) {
                $h = $maxh;
                $w = abs($h * $info['w'] / $info['h']);
            }
            // Position
            $pos_list = [];
            $outstring_list = [];
            if (isset($this->watermark_pos[0]) && is_array($this->watermark_pos[0])) {
                foreach ($this->watermark_pos as $k => $v) {
                    $pos_list[] = ['x'=>$v[0],'y'=>$v[1]];
                }
                $x = $this->watermark_pos[0];
                $y = $this->watermark_pos[1];
            } elseif (is_array($this->watermark_pos)) {
                $x = $this->watermark_pos[0];
                $y = $this->watermark_pos[1];
            } elseif ($this->watermark_pos == 'F') { // centred on printable area
                if ($this->ColActive) { // *COLUMNS*
                    if (($this->mirrorMargins) && (($this->page) % 2 == 0)) {
                        $xadj = $this->DeflMargin - $this->DefrMargin;
                    } // *COLUMNS*
                    else {
                        $xadj = 0;
                    } // *COLUMNS*
                    $x = ($this->DeflMargin - $xadj + ($this->w - ($this->DeflMargin + $this->DefrMargin)) / 2) - ($w / 2); // *COLUMNS*
                } // *COLUMNS*
                else {  // *COLUMNS*
                    $x = ($this->lMargin + ($this->pgwidth) / 2) - ($w / 2);
                } // *COLUMNS*
                $y = ($this->tMargin + ($this->h - ($this->tMargin + $this->bMargin)) / 2) - ($h / 2);
            } else { // default P - centred on whole page
                $x = ($this->w / 2) - ($w / 2);
                $y = ($this->h / 2) - ($h / 2);
            }
            /* -- IMAGES-WMF -- */
            if ($pos_list) {
                if ($info['type'] == 'wmf') {
                    $sx = $w * Mpdf::SCALE / $info['w'];
                    $sy = -$h * Mpdf::SCALE / $info['h'];
                    foreach ($pos_list as $k => $v) {
                        $outstring_list[] = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $v['x'] * Mpdf::SCALE - $sx * $info['x'], (($this->h - $v['y']) * Mpdf::SCALE) - $sy * $info['y'], $info['i']);
                    }
                } else {            /* -- END IMAGES-WMF -- */
                    if ($info['type'] == 'svg') {
                        $sx = $w * Mpdf::SCALE / $info['w'];
                        $sy = -$h * Mpdf::SCALE / $info['h'];
                        foreach ($pos_list as $k => $v) {
                            $outstring_list[] = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $v['x'] * Mpdf::SCALE - $sx * $info['x'], (($this->h - $v['y']) * Mpdf::SCALE) - $sy * $info['y'], $info['i']);
                        }
                    } else {
                        foreach ($pos_list as $k => $v) {
                            $outstring_list[] = sprintf("q %.3F 0 0 %.3F %.3F %.3F cm /I%d Do Q", $w * Mpdf::SCALE, $h * Mpdf::SCALE, $v['x'] * Mpdf::SCALE, ($this->h - ($v['y'] + $h)) * Mpdf::SCALE, $info['i']);
                        }
                    }
                }
            } else {
                if ($info['type'] == 'wmf') {
                    $sx = $w * Mpdf::SCALE / $info['w'];
                    $sy = -$h * Mpdf::SCALE / $info['h'];
                    $outstring = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $x * Mpdf::SCALE - $sx * $info['x'], (($this->h - $y) * Mpdf::SCALE) - $sy * $info['y'], $info['i']);
                } else {            /* -- END IMAGES-WMF -- */
                    if ($info['type'] == 'svg') {
                        $sx = $w * Mpdf::SCALE / $info['w'];
                        $sy = -$h * Mpdf::SCALE / $info['h'];
                        $outstring = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $x * Mpdf::SCALE - $sx * $info['x'], (($this->h - $y) * Mpdf::SCALE) - $sy * $info['y'], $info['i']);
                    } else {
                        $outstring = sprintf("q %.3F 0 0 %.3F %.3F %.3F cm /I%d Do Q", $w * Mpdf::SCALE, $h * Mpdf::SCALE, $x * Mpdf::SCALE, ($this->h - ($y + $h)) * Mpdf::SCALE, $info['i']);
                    }
                }
            }

            if ($this->watermarkImgBehind) {
                $outstring = $this->watermarkImgAlpha . "\n" . $outstring . "\n" . $this->SetAlpha(1, 'Normal', true) . "\n";
                $this->pages[$this->page] = preg_replace('/(___BACKGROUND___PATTERNS' . $this->uniqstr . ')/', "\n" . $outstring . "\n" . '\\1', $this->pages[$this->page]);
            } else {
                if ($outstring_list) {
                    foreach ($outstring_list as $k => $v) {
                        $this->_out($v);
                    }
                } else {
                    $this->_out($outstring);
                }
            }

            return 0;
        } // end of IF watermark
        /* -- END WATERMARK -- */

        if ($constrain) {
            // Automatically resize to maximum dimensions of page if too large
            if (isset($this->blk[$this->blklvl]['inner_width']) && $this->blk[$this->blklvl]['inner_width']) {
                $maxw = $this->blk[$this->blklvl]['inner_width'];
            } else {
                $maxw = $this->pgwidth;
            }
            if ($w > $maxw) {
                $w = $maxw;
                $h = abs($w * $info['h'] / $info['w']);
            }
            if ($h > $this->h - ($this->tMargin + $this->bMargin + 1)) {  // see below - +10 to avoid drawing too close to border of page
                $h = $this->h - ($this->tMargin + $this->bMargin + 1);
                if ($this->fullImageHeight) {
                    $h = $this->fullImageHeight;
                }
                $w = abs($h * $info['w'] / $info['h']);
            }


            // Avoid drawing out of the paper(exceeding width limits).
            // if ( ($x + $w) > $this->fw ) {
            if (($x + $w) > $this->w) {
                $x = $this->lMargin;
                $y += 5;
            }

            $changedpage = false;
            $oldcolumn = $this->CurrCol;
            // Avoid drawing out of the page.
            if ($y + $h > $this->PageBreakTrigger and ! $this->InFooter and $this->AcceptPageBreak()) {
                $this->AddPage($this->CurOrientation);
                // Added to correct for OddEven Margins
                $x = $x + $this->MarginCorrection;
                $y = $this->tMargin; // mPDF 5.7.3
                $changedpage = true;
            }
            /* -- COLUMNS -- */
            // COLS
            // COLUMN CHANGE
            if ($this->CurrCol != $oldcolumn) {
                $y = $this->y0;
                $x += $this->ChangeColumn * ($this->ColWidth + $this->ColGap);
                $this->x += $this->ChangeColumn * ($this->ColWidth + $this->ColGap);
            }
            /* -- END COLUMNS -- */
        } // end of IF constrain

        /* -- IMAGES-WMF -- */
        if ($info['type'] == 'wmf') {
            $sx = $w * Mpdf::SCALE / $info['w'];
            $sy = -$h * Mpdf::SCALE / $info['h'];
            $outstring = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $x * Mpdf::SCALE - $sx * $info['x'], (($this->h - $y) * Mpdf::SCALE) - $sy * $info['y'], $info['i']);
        } else {         /* -- END IMAGES-WMF -- */
            if ($info['type'] == 'svg') {
                $sx = $w * Mpdf::SCALE / $info['w'];
                $sy = -$h * Mpdf::SCALE / $info['h'];
                $outstring = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $x * Mpdf::SCALE - $sx * $info['x'], (($this->h - $y) * Mpdf::SCALE) - $sy * $info['y'], $info['i']);
            } else {
                $outstring = sprintf("q %.3F 0 0 %.3F %.3F %.3F cm /I%d Do Q", $w * Mpdf::SCALE, $h * Mpdf::SCALE, $x * Mpdf::SCALE, ($this->h - ($y + $h)) * Mpdf::SCALE, $info['i']);
            }
        }

        if ($paint) {
            $this->_out($outstring);
            if ($link) {
                $this->Link($x, $y, $w, $h, $link);
            }

            // Avoid writing text on top of the image. // THIS WAS OUTSIDE THE if ($paint) bit!!!!!!!!!!!!!!!!
            $this->y = $y + $h;
        }

        // Return width-height array
        $sizesarray['WIDTH'] = $w;
        $sizesarray['HEIGHT'] = $h;
        $sizesarray['X'] = $x; // Position before painting image
        $sizesarray['Y'] = $y; // Position before painting image
        $sizesarray['OUTPUT'] = $outstring;

        $sizesarray['IMAGE_ID'] = $info['i'];
        $sizesarray['itype'] = $info['type'];
        $sizesarray['set-dpi'] = (isset($info['set-dpi']) ? $info['set-dpi'] : 0);
        return $sizesarray;
    }

 

2.生成的pdf是“非标准格式”,解决办法:

$mpdf->useAdobeCJK = true;
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;

 

3.不支持元素display属性变化,不支持position定位

4.一个只包含中文符号的html标签(并非中文文字乱码),中文符号会变成乱码,我这里换成了7.1以上的版本,并且 new Mpdf(['mode' => 'zh-cn']) 设置了'mode' => 'zh-cn',解决了这个问题

 

更多使用方法请到使用手册查询

posted @ 2021-12-02 10:42  一剑还  阅读(2827)  评论(0编辑  收藏  举报