-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBook.php
More file actions
254 lines (213 loc) · 5.77 KB
/
Book.php
File metadata and controls
254 lines (213 loc) · 5.77 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
<?php
namespace Dandy\Book;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use Mpdf\Config\ConfigVariables;
use Mpdf\Config\FontVariables;
use Mpdf\Mpdf;
class Book
{
/**
* PDF document instance
*/
protected Mpdf $pdf;
/**
* Custom fonts to register
*/
protected array $customFonts = [];
/**
* Create PDF with default configuration
*/
public function __construct(array $config = [])
{
$this->pdf = new Mpdf(
array_merge($this->defaultConfig(), $config['document'] ?? [])
);
$this->pdf->debug = true;
$this->initializePdf();
}
/**
* Set title
*/
public function withTitle(string $title): static
{
$this->pdf->SetTitle($title);
return $this;
}
/**
* Set author
*/
public function withAuthor(string $author): static
{
$this->pdf->SetAuthor($author);
$this->pdf->SetCreator($author);
return $this;
}
/**
* Set custom fonts
*/
public function withFonts(array $fonts): static
{
$this->customFonts = $fonts;
return $this;
}
/**
* Apply theme HTML
*/
public function withTheme(string $themeHtml): static
{
$this->pdf->WriteHTML($themeHtml);
return $this;
}
/**
* Apply theme HTML
*/
public function withColophon(string $html): static
{
$this->pdf->WriteHTML(
Str::of($html)
->replace('[commit]', self::getCurrentGitCommitHash())
->replace('[year]', Date::now()->format('Y'))
->toString()
);
return $this;
}
/**
* Add cover page
*/
public function withCover(string $coverHtml): static
{
if (! empty($coverHtml)) {
$this->pdf->WriteHTML($coverHtml);
$this->addPageBreak();
}
return $this;
}
/**
* Add chapter with title header and optional page break
*/
public function chapter(string $chapterHtml, bool $break = true): static
{
$title = $this->extractTitle($chapterHtml);
if ($title) {
$slug = Str::slug($title);
$this->pdf->defHTMLHeaderByName($slug, <<<HTML
<span style="text-align: center; color: #817d7d; font-size: 10px">
$title
</span>
HTML);
$this->pdf->WriteHTML("<setpageheader name=\"{$slug}\" page=\"E\" value=\"on\" />");
}
$this->pdf->WriteHTML("<div class='chapter'>{$chapterHtml}</div>");
if ($break) {
$this->addPageBreak();
}
return $this;
}
/**
* Set footer HTML
*/
public function setFooter(string $footerHtml): static
{
$this->pdf->SetHTMLFooter($footerHtml);
return $this;
}
/**
* Save PDF to file
*/
public function output(string $path): void
{
$this->pdf->Output($path);
}
/**
* Get total page count
*/
public function getPageCount(): int
{
return $this->pdf->page;
}
/**
* Return the underlying Mpdf instance
*/
public function build(): Mpdf
{
return $this->pdf;
}
/**
* Default PDF configuration array
*/
protected function defaultConfig(): array
{
$baseConfig = (new ConfigVariables())->getDefaults();
$fontConfig = (new FontVariables())->getDefaults();
return [
'mode' => 'utf-8',
'fontDir' => array_merge($baseConfig['fontDir'], [getcwd().'/assets/fonts']),
'fontdata' => $this->prepareFontData($fontConfig['fontdata']),
'SHYlang' => 'ru',
'justifyB4br' => false,
'useKerning' => true,
'h2toc' => ['H1' => 0, 'H2' => 1],
'h2bookmarks' => ['H1' => 0, 'H2' => 1],
];
}
/**
* Prepare font data by merging custom fonts with defaults
*/
protected function prepareFontData(array $defaultFontData): array
{
return collect($defaultFontData)
->merge(
collect($this->customFonts)->mapWithKeys(fn ($file, $name) => [
$name => ['R' => $file],
])
)
->toArray();
}
/**
* Initialize PDF document settings
*/
protected function initializePdf(): void
{
$this->pdf->h2toc = ['H1' => 0, 'H2' => 1];
$this->pdf->h2bookmarks = ['H1' => 0, 'H2' => 1];
$this->pdf->defHTMLHeaderByName('[clear]', '');
$this->pdf->setAutoTopMargin = 'pad';
$this->pdf->setAutoBottomMargin = 'pad';
$this->pdf->use_kwt = true;
}
/**
* Extract the first H1 title from chapter HTML
*/
protected function extractTitle(string $html): ?string
{
if (preg_match('/<h1[^>]*>(.*?)<\/h1>/is', $html, $matches)) {
return trim(
str_replace('­', '', html_entity_decode($matches[1]))
);
}
return null;
}
/**
* Insert a page break into the PDF
*/
protected function addPageBreak(): void
{
$this->pdf->WriteHTML('<div style="page-break-after: always;"></div>');
}
/**
* Attempt to retrieve the current Git commit hash in PHP.
* Note: This method assumes the project is using Git for version control.
*
* @return string|null
*/
public static function getCurrentGitCommitHash(): ?string
{
$gitPath = '.git/';
if (! file_exists($gitPath)) {
return null;
}
$head = trim(substr(file_get_contents($gitPath.'HEAD'), 4));
return Str::of(file_get_contents($gitPath.$head))->trim()->limit(7, '');
}
}