前些天看到看云的pdf的文档,突然联想到自己写的网站的技术文档、能不能做出导出pdf功能。于是就找到了mpdf这个类库,下载量也比较高!

composer require mpdf/mpdf

当时用于测试demo的代码案例

PDF下载可用wget命令下载这个文件列子v8js.pdf

多页面取出单页处理

<?php

/* pdf_creator.php */

require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new \Mpdf\Mpdf();

// set the sourcefile
// $mpdf->SetImportUse(); // <--- not needed for mPDF version 8.0+
$mpdf->setSourceFile(__DIR__ . '/v8js.pdf'); // absolute path to pdf file

// import page 1
$tplIdx = $mpdf->importPage(1);

// use the imported page and place it at point 10,10 with a width of 200 mm   (This is the image of the included pdf)
$mpdf->useTemplate($tplIdx, 10, 10, 200);

// now write some text above the imported page
$mpdf->SetTextColor(0, 0, 255);
$mpdf->SetFont('Arial', 'B', 8);
$mpdf->SetXY(95, 16);
$mpdf->Write(0, 'Mindfire');
$mpdf->Output('newpdf.pdf');

多页pdf在其中添加签名或者其它元素(可用于电子合同签名)

<?php
/* pdf_creator.php */

require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new \Mpdf\Mpdf([
  'mode' => 'UTF-8', 'format' => 'A4', 'default_font_size' => 20]);
$mpdf->autoScriptToLang = true;//支持中文设置
$mpdf->autoLangToFont = true;//支持中文设置
// set the sourcefile
// $mpdf->SetImportUse(); // <--- not needed for mPDF version 8.0+
$pageCount=$mpdf->setSourceFile(__DIR__ . '/v8js.pdf'); // absolute path to pdf file
//echo count($pageCount).PHP_EOL;
var_dump($pageCount);
// import page 1
$tplIdx = $mpdf->importPage(2);

for($i = 1; $i <= $pageCount; $i++) {
  $pageId = $mpdf->ImportPage($i);
  $s = $mpdf->getTemplatesize($pageId);
  $mpdf->AddPage($s['orientation']);
  $mpdf->useImportedPage($pageId);
  if($i===2){
//    $mpdf->useTemplate($tplIdx, 10, 10, 200);
//    $mpdf->useImportedPage($pageId);
// now write some text above the imported page
    $mpdf->SetTextColor(0, 0, 0);
    $mpdf->SetFont('Arial', 'B', 8);
    $mpdf->Write(10, '893797758@qq.com');
    $mpdf->SetXY(105, 20);
    $img="<b>启东</b>";
    $mpdf->WriteHTML($img);

//$mpdf->Output('newpdf.pdf');
  }
//  $mpdf->useImportedPage($pageId);
}

// use the imported page and place it at point 10,10 with a width of 200 mm   (This is the image of the included pdf)
//$mpdf->useTemplate($tplIdx, 10, 10, 200);
//// now write some text above the imported page
//$mpdf->SetTextColor(0, 0, 0);
//$mpdf->SetFont('Arial', 'B', 8);
//$mpdf->SetXY(95, 16);
////$img="<b>启东</b>";
////$mpdf->WriteHTML($img);
//$mpdf->Write(10, '启东');
$mpdf->Output('newpdf.pdf');
Last modification:April 26, 2022
如果觉得我的文章对你有用,请随意赞赏