ToolController.php
2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use karmabunny\BaconBackends\GdImageBackEnd;
use setasign\Fpdi\Fpdi;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
class ToolController extends Controller
{
/**
* @param array $data
* @param string $message
* @param int $status
* @return string
*/
protected function success($data = [], $message = 'success', $status = 200)
{
$array = compact('status', 'message', 'data');
return json_encode($array, JSON_UNESCAPED_UNICODE);
}
/**
* @param int $status
* @param string $message
* @param array $data
* @return string
*/
protected function error($message = 'error', $status = 400, $data = [])
{
$array = compact('status', 'message', 'data');
return json_encode($array, JSON_UNESCAPED_UNICODE);
}
public function addQrToPdf()
{
$sourceFile = public_path('original.pdf');
$qrText = 'https://www.bing.com';
// 生成二维码图片
$qrImage = public_path('qrcode_temp.png');
$renderer = new ImageRenderer(
new RendererStyle(300, 0),
new GdImageBackEnd() // 使用 GD 后端
);
$writer = new Writer($renderer);
// 生成 PNG 图片数据
$writer->writeFile($qrText, $qrImage);
$pdf = new Fpdi();
$pageCount = $pdf->setSourceFile($sourceFile);
for ($i = 1; $i <= $pageCount; $i++) {
$tpl = $pdf->importPage($i);
$size = $pdf->getTemplateSize($tpl);
$pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
$pdf->useTemplate($tpl);
// ✅ 只在第一页添加二维码
if ($i === 1) {
$qrWidth = 30; // 二维码宽度(单位:mm)
$margin = 5; // 距离边缘间距(mm)
$x = $size['width'] - $qrWidth - $margin;
$y = $margin;
$pdf->Image($qrImage, $x, $y, $qrWidth);
$text = 'Scan to verify the original MTC on official website';
// 设置字体(必须设置,否则不显示)
$pdf->SetFont('Arial', '', 8);
// 计算文字位置
$textY = $y + $qrWidth + 2; // 二维码下方2mm
// 设置光标位置
$pdf->SetXY($x - 1, $textY);
// 固定宽度,自动换行
$pdf->MultiCell($qrWidth + 10, 4, $text, 0, 'L');
}
}
$outputFile = public_path('output.pdf');
$pdf->Output('F', $outputFile);
// 删除临时二维码图片
unlink($qrImage);
return $this->success(['pdf_file' => $outputFile]);
}
}