| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace app\common\service\watermark\pdf;
- use Mpdf\Mpdf;
- use Mpdf\Config\ConfigVariables;
- use Mpdf\Config\FontVariables;
- /**
- * 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, $type = 0)
- {
- $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'
- ]);
- $mpdf->autoScriptToLang = true;
- $mpdf->autoLangToFont = true;
- $text = $waterText;
- //文字水印
- $watermarkText = new \Mpdf\WatermarkText($text, 30, 30, '#cccccc', 0.2);
- $mpdf->SetWatermarkText($watermarkText, 0.3);
- $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;
- }
- }
|