| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- <?php
- namespace app\common\service\watermark\pdf;
- use Mpdf\Mpdf;
- use Mpdf\Config\ConfigVariables;
- use Mpdf\Config\FontVariables;
- use TCPDF;
- /**
- * Class Pdf
- *
- * @Author: Yeshihao
- * @DateTime: 2024/11/28 11:17
- * @package app\common\service\watermark\pdf
- */
- class Pdf
- {
- // public function waterMark($filePath, $waterText, $type = 0)
- // {
- // $pdf = new Fpdi();
- // $pdf->AddFont('msyh', '', 'msyh.ttf', true); //简体中文可正常显示
- // $pdf->SetFont('msyh', '', 40);
- //
- // $pageCount = $pdf->setSourceFile($filePath);
- //
- // for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
- //$templateId = $pdf->importPage($pageNo);
- // $pdf->AddPage();
- // $pdf->useTemplate($templateId, ['adjustPageSize' => true]);
- //$size = $pdf->getTemplateSize($templateId);
- // $center_x = $size['width'] / 2;
- // $center_y = $size['height'] / 2;
- // $pdf->SetXY($center_x, $center_y);
- // //文字水印
- // $pdf->SetTextColor(200, 200, 200);
- // $pdf->Write(0, $waterText);
- // }
- //
- // $pdf->Output('F', $filePath); //下载修改后的PDF
- // }
- /**
- * [waterMark]
- * 打印水印
- *
- * @Author: Yeshihao
- * @DateTime: 2024/11/28 13:39
- * @param $filePath
- * @param $waterText
- * @param int $type
- * @return bool
- * @throws \Mpdf\MpdfException
- * @throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException
- * @throws \setasign\Fpdi\PdfParser\PdfParserException
- * @throws \setasign\Fpdi\PdfParser\Type\PdfTypeException
- */
- public function waterMark($filePath, $waterText, $alpha = 30, $type = 0, $waterText2 = '', $pageWidth = 210, $pageHeight = 297)
- {
- $defaultConfig = (new ConfigVariables())->getDefaults();
- $fontDirs = $defaultConfig['fontDir'];
- $defaultFontConfig = (new FontVariables())->getDefaults();
- $fontData = $defaultFontConfig['fontdata'];
- $mpdf = new Mpdf(['mode' => '+aCJK',
- 'fontDir' => array_merge($fontDirs, [__DIR__.'/fonts']),
- 'fontdata' => $fontData + ['msyh' => ['R' => 'msyh.ttf',],],
- 'default_font' => 'msyh',
- 'format' => [$pageWidth ?: 210, $pageHeight ?: 297],
- ]);
- $mpdf->autoScriptToLang = true;
- $mpdf->autoLangToFont = true;
- $text = $waterText.$waterText2;
- //文字水印
- $alpha = number_format((100 - $alpha) / 100, 2);
- $watermarkText = new \Mpdf\WatermarkText($text, 30, 30, '#cccccc', $alpha);
- $mpdf->SetWatermarkText($watermarkText, $alpha);
- $mpdf->showWatermarkText = true;
- $mpdf->watermarkAngle = '45';
- $pageCount = $mpdf->SetSourceFile($filePath); //读取原始文件页数
- for ($i = 1; $i <= $pageCount; $i++) {
- $import_page = $mpdf->ImportPage($i);
- $mpdf->UseTemplate($import_page);
- if ($i < $pageCount)
- $mpdf->AddPage();
- }
- $mpdf->Output($filePath, 'F');// 下载修改后的PDF
- return true;
- }
- }
|