-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWire2PDF.module.php
More file actions
939 lines (821 loc) · 32.8 KB
/
Wire2PDF.module.php
File metadata and controls
939 lines (821 loc) · 32.8 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
<?php
namespace ProcessWire;
/**
* Wire2PDF
*
* A combined module replacing WirePDF and Pages2PDF.
* Offers both a PDF generation API (wrapper around mPDF) and
* automatic PDF creation for Pages via URL or hooks.
*
* @property array $templates Enabled templates
* @property string $getVar URL GET variable
* @property string $filename Filename pattern
* @property int $printHeader Print header?
* @property int $printFooter Print footer?
* @property int $cacheTime Cache time in seconds
* @property int $creationMode Creation mode (click vs save)
* @property int $multilanguageSupport Multilanguage support?
* @property string $pageOrientation P or L
* @property string $pageFormat A4, Letter, etc.
* @property float $topMargin
* @property float $rightMargin
* @property float $bottomMargin
* @property float $leftMargin
* @property float $headerMargin
* @property float $footerMargin
* @property string $font Default font
* @property int $fontSize Default font size
* @property string $author PDF Author
* @property string $title PDF Title
* @property string $subject PDF Subject
* @property string $keywords PDF Keywords
* @property string $creator PDF Creator
* @property int $headerFirstPage Show header on first page?
* @property string $cssFile Path to CSS file
* @property string $mode mPDF mode
* @property int $pdfa PDF/A compliance
*/
class Wire2PDF extends WireData implements Module, ConfigurableModule
{
/**
* Folder name where PDF templates are stored inside /site/templates/
*/
const FOLDER_NAME = 'pages2pdf/';
/**
* Generating cache PDF files either on click (when requesting a download) or when saving a page in the admin
*/
const CREATION_MODE_CLICK = 1;
const CREATION_MODE_SAVE = 2;
/**
* @var \Mpdf\Mpdf
*/
protected $mpdfInstance;
/**
* Temporary storage for markup
*/
protected $markupMain = '';
protected $markupHeader = '';
protected $markupFooter = '';
protected $customCssFile = '';
protected $customCss = '';
/**
* Module information
*/
public static function getModuleInfo()
{
return [
'title' => 'Wire2PDF',
'version' => 210,
'summary' => __('Complete replacement for WirePDF and Pages2Pdf. Generates PDFs from pages or via API.', __FILE__),
'author' => 'Markus Thomas',
'autoload' => true,
'singular' => true,
'icon' => 'file-pdf-o',
'requires' => 'ProcessWire>=3.0.0'
];
}
/**
* Default configuration
*/
protected static $defaults = [
// Pages2Pdf Defaults
'templates' => [],
'getVar' => 'pdf', // Changed from 'pages2pdf' to 'pdf' for shorter URL, but configurable
'filename' => '{page.name}-pdf-{page.id}.pdf',
'printHeader' => 1,
'printFooter' => 1,
'cacheTime' => 86400,
'creationMode' => self::CREATION_MODE_CLICK,
'multilanguageSupport' => false,
// WirePDF Defaults
'mode' => 'utf-8',
'pageOrientation' => 'P',
'pageFormat' => 'A4',
'topMargin' => 30,
'rightMargin' => 15,
'bottomMargin' => 20,
'leftMargin' => 15,
'headerMargin' => 5,
'footerMargin' => 10,
'font' => 'Helvetica',
'fontSize' => 12,
'author' => '',
'title' => '',
'subject' => '',
'keywords' => '',
'creator' => 'Wire2PDF',
'headerFirstPage' => 1,
'cssFile' => '',
'pdfa' => 0,
];
/**
* Constructor
*/
public function __construct()
{
foreach (self::$defaults as $key => $value) {
$this->set($key, $value);
}
}
/**
* Initialization
*/
public function init()
{
$autoload = $this->wire('config')->paths->get($this) . 'vendor/autoload.php';
if (file_exists($autoload)) {
require_once($autoload);
}
}
/**
* Ready: Register hooks and check for download request
*/
public function ready()
{
// 1. Check for URL request (Pages2Pdf logic)
$get_var = $this->get('getVar');
$input = $this->wire('input');
if ($page_id = $input->get($get_var)) {
$page = ($page_id == 1) ? $this->wire('page') : $this->wire('pages')->get((int) $page_id);
// Validate page and template
if ($page->id && $page->viewable() && in_array($page->template->name, $this->get('templates'))) {
// Execute download (this will exit the script)
$this->download($page);
}
}
// 2. Register Hooks
$this->pages->addHookAfter('save', $this, 'hookDeletePDF');
if ($this->get('creationMode') == self::CREATION_MODE_SAVE) {
$this->pages->addHookAfter('save', $this, 'hookSavePDF');
}
}
/**
* Install: Copy default templates
*/
public function ___install()
{
$folder = self::FOLDER_NAME;
$templates_path = $this->wire('config')->paths->templates . $folder;
if (!file_exists($templates_path)) {
if (!wireMkdir($templates_path)) {
$this->error(sprintf(__('Could not create directory \'%s\' in \'/site/templates/\'.', __FILE__), $folder));
} else {
// Note: In a real scenario, you would copy these from the module directory.
// Since we are merging, ensure you have a 'default_templates' folder in your module dir.
$path_from = __DIR__ . '/default_templates/';
if (is_dir($path_from)) {
$files = ['_footer.php', '_header.php', 'default.php', 'styles.css'];
foreach ($files as $file) {
@copy($path_from . $file, $templates_path . $file);
}
$this->message(sprintf(__('Installed default PDF templates to %s', __FILE__), $templates_path));
}
}
}
// Create custom font directory
$font_path = $this->wire('config')->paths->assets . 'Wire2PDF/fonts/';
if (!is_dir($font_path)) {
if (!wireMkdir($font_path)) {
$this->error(sprintf(__('Could not create directory \'%s\'. Please create it manually.', __FILE__), $font_path));
} else {
// Add a .htaccess file to prevent direct access if it's in a web-accessible location
@file_put_contents($font_path . '.htaccess', "Deny from all\n");
$this->message(sprintf(__('Created custom font directory at %s', __FILE__), $font_path));
}
}
}
/**
* Unified Download Method
* Handles both Page objects (Pages2Pdf style) and Strings/Files (WirePDF style)
*
* @param mixed $target Page object or Filename string
* @param mixed $option Force download (bool) for Page, or Mode (string) for File
*/
public function ___download($target, $option = null)
{
if ($target instanceof Page) {
// Pages2Pdf Logic
$force = (bool) $option;
$this->downloadPage($target, $force);
} else {
// WirePDF Logic
$filename = $target;
$mode = $option ?: 'D'; // Default to Download
$this->writePDF();
$this->mPDF()->Output($filename, $mode);
}
}
/**
* Save PDF file (WirePDF API)
*
* @param string $filepath
* @return $this
*/
public function save($filepath)
{
$this->writePDF();
$this->mPDF()->Output($filepath, \Mpdf\Output\Destination::FILE);
return $this;
}
/**
* Magic method to proxy calls to mPDF instance (WirePDF API)
*/
public function __call($method, $args)
{
if (method_exists($this->mPDF(), $method)) {
return call_user_func_array([$this->mPDF(), $method], $args);
}
return parent::__call($method, $args);
}
/**
* Set properties (WirePDF API compatibility)
*/
public function set($key, $value)
{
if ($key == 'markupMain')
$this->markupMain = $value;
else if ($key == 'markupHeader')
$this->markupHeader = $value;
else if ($key == 'markupFooter')
$this->markupFooter = $value;
else if ($key == 'cssFile')
$this->customCssFile = $value;
else if ($key == 'css')
$this->customCss = $value;
else
return parent::set($key, $value);
return $this;
}
// ------------------------------------------------------------------------
// Internal PDF Generation (Engine)
// ------------------------------------------------------------------------
/**
* Helper: Process text variables
*/
protected function processTextVariables($text, Page $page)
{
// 1. Module specific variables
$name = $page->name;
$language = $this->determineLanguage();
if ($this->wire('modules')->isInstalled('LanguageSupportPageNames') && $language && $page->localName($language)) {
$name = $page->localName($language);
}
$text = str_replace(
['{page.name}', '{page.id}', '{page.title}'],
[$name, $page->id, $page->title],
$text
);
// 2. Generic ProcessWire fields {field_name}
return html_entity_decode(strip_tags(wirePopulateStringTags($text, $page)), ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
/**
* Get or create mPDF instance
* @return \Mpdf\Mpdf
*/
public function mPDF()
{
if ($this->mpdfInstance)
return $this->mpdfInstance;
if (!class_exists('\Mpdf\Mpdf')) {
$autoload = $this->wire('config')->paths->get($this) . 'vendor/autoload.php';
if (file_exists($autoload)) {
require_once($autoload);
}
}
if (!class_exists('\Mpdf\Mpdf')) {
throw new WireException(__("mPDF library not found.", __FILE__));
}
$tempDir = $this->config->paths->cache . 'Wire2PDF/';
if (!is_dir($tempDir))
wireMkdir($tempDir);
// --- Custom Font Configuration ---
$customFontPath = $this->wire('config')->paths->assets . 'Wire2PDF/fonts/';
$fontDirs = (new \Mpdf\Config\ConfigVariables())->getDefaults()['fontDir'];
$fontData = (new \Mpdf\Config\FontVariables())->getDefaults()['fontdata'];
if (is_dir($customFontPath)) {
$fontDirs[] = $customFontPath;
$customFontFiles = glob($customFontPath . '*.ttf');
if (is_array($customFontFiles)) {
foreach ($customFontFiles as $file) {
// Sanitize font name from filename
$fontname = strtolower(pathinfo(basename($file), PATHINFO_FILENAME));
$fontname = preg_replace('/[^a-z0-9]/', '', $fontname);
if ($fontname) {
// Simple implementation: assumes the filename is the font name and it's a regular style.
$fontData[$fontname] = [
'R' => basename($file),
];
}
}
}
}
$config = [
'mode' => $this->get('mode'),
'format' => $this->get('pageFormat'),
'orientation' => $this->get('pageOrientation'),
'default_font_size' => $this->get('fontSize'),
'default_font' => $this->get('font'),
'margin_left' => $this->get('leftMargin'),
'margin_right' => $this->get('rightMargin'),
'margin_top' => $this->get('topMargin'),
'margin_bottom' => $this->get('bottomMargin'),
'margin_header' => $this->get('headerMargin'),
'margin_footer' => $this->get('footerMargin'),
'tempDir' => $tempDir,
'fontDir' => $fontDirs,
'fontdata' => $fontData,
];
$this->mpdfInstance = new \Mpdf\Mpdf($config);
$this->mpdfInstance->SetAuthor($this->get('author'));
$title = $this->get('title');
$page = $this->wire('page');
if ($page && $page->id) {
if (!$title) {
$title = $page->title;
$title = html_entity_decode(strip_tags($title), ENT_QUOTES | ENT_HTML5, 'UTF-8');
} else {
$title = $this->processTextVariables($title, $page);
}
}
if ($title)
$this->mpdfInstance->SetTitle($title);
$subject = $this->get('subject');
if ($subject && $page && $page->id) {
$subject = $this->processTextVariables($subject, $page);
}
if ($subject)
$this->mpdfInstance->SetSubject($subject);
$keywords = $this->get('keywords');
if ($keywords && $page && $page->id) {
$keywords = $this->processTextVariables($keywords, $page);
}
if ($keywords)
$this->mpdfInstance->SetKeywords($keywords);
if ($this->get('creator'))
$this->mpdfInstance->SetCreator($this->get('creator'));
if ($this->get('pdfa')) {
$this->mpdfInstance->PDFA = true;
$this->mpdfInstance->PDFAauto = true;
}
return $this->mpdfInstance;
}
/**
* Writes content to the PDF (WirePDF logic)
*/
protected function writePDF()
{
$mpdf = $this->mPDF();
// Header
if ($header = $this->getMarkup($this->markupHeader)) {
$mpdf->SetHTMLHeader($header, '', (bool) $this->get('headerFirstPage'));
}
// Footer
if ($footer = $this->getMarkup($this->markupFooter)) {
$mpdf->SetHTMLFooter($footer);
}
// CSS
$css = '';
if ($this->customCssFile && is_file($this->customCssFile)) {
$css = file_get_contents($this->customCssFile);
} elseif ($this->customCss) {
$css = $this->customCss;
}
if ($css) {
$mpdf->WriteHTML($css, \Mpdf\HTMLParserMode::HEADER_CSS);
}
// Main Content
$html = $this->getMarkup($this->markupMain);
if ($html) {
$mpdf->WriteHTML($html, \Mpdf\HTMLParserMode::HTML_BODY);
}
}
/**
* Helper to render markup from string, file or TemplateFile
*/
protected function getMarkup($markup)
{
if ($markup instanceof TemplateFile) {
return $markup->render();
} elseif (is_string($markup) && is_file($markup)) {
$t = new TemplateFile($markup);
return $t->render();
}
return $markup;
}
// ------------------------------------------------------------------------
// Page Logic (Pages2Pdf)
// ------------------------------------------------------------------------
/**
* Download PDF for a page (Pages2Pdf logic)
*/
protected function downloadPage(Page $page, $force = false)
{
$language = $this->determineLanguage();
if ($force || !$this->isCached($page, $language)) {
$this->createPDF($page, $language);
}
$file = $this->getPDFFilePath($page, $language);
if (file_exists($file)) {
wireSendFile($file, ['forceDownload' => true]);
}
}
/**
* Create PDF for a page
*/
protected function createPDF(Page $page, Language $language = null)
{
// Reset mPDF instance for fresh generation
$this->mpdfInstance = null;
// Setup paths
$templates_path = $this->wire('config')->paths->templates . self::FOLDER_NAME;
// Determine Main Template
$template_main = $templates_path . $page->template->name . '.php';
if (!is_file($template_main)) {
$template_main = $templates_path . 'default.php';
}
// Set content
$this->markupMain = $template_main;
if ($this->get('printHeader')) {
$this->markupHeader = $templates_path . '_header.php';
}
if ($this->get('printFooter')) {
$this->markupFooter = $templates_path . '_footer.php';
}
if (is_file($templates_path . 'styles.css')) {
$this->customCssFile = $templates_path . 'styles.css';
}
// Render context
$prevPage = $this->wire('page');
$this->wire('page', $page); // Switch context for template rendering
// Save
$this->save($this->getPDFFilePath($page, $language));
$this->wire('page', $prevPage); // Restore context
}
/**
* Hook: Delete PDF on page save
*/
public function hookDeletePDF(HookEvent $event)
{
$page = $event->arguments[0];
if (!in_array($page->template->name, $this->get('templates')))
return;
$languages = $this->wire('languages') ?: [null];
foreach ($languages as $language) {
$file = $this->getPDFFilePath($page, $language);
if (is_file($file))
unlink($file);
}
}
/**
* Hook: Create PDF on page save
*/
public function hookSavePDF(HookEvent $event)
{
$page = $event->arguments[0];
if (!in_array($page->template->name, $this->get('templates')))
return;
if ($page->is(Page::statusTrash))
return;
if ($this->get('multilanguageSupport') && $this->wire('languages')) {
$currentUserLang = $this->wire('user')->language;
foreach ($this->wire('languages') as $lang) {
$this->wire('user')->language = $lang;
$this->createPDF($page, $lang);
}
$this->wire('user')->language = $currentUserLang;
} else {
$this->createPDF($page);
}
}
/**
* Helper: Get PDF File Path
*/
public function getPDFFilePath(Page $page, Language $language = null)
{
$path = $page->filesManager()->path();
if (!is_dir($path))
wireMkdir($path);
return $path . $this->getPDFFilename($page, $language);
}
/**
* Helper: Get PDF Filename
*/
protected function getPDFFilename(Page $page, Language $language = null)
{
$name = $page->name;
if ($this->wire('modules')->isInstalled('LanguageSupportPageNames') && $language && $page->localName($language)) {
$name = $page->localName($language);
}
$filename = str_replace(
['{page.id}', '{page.name}'],
[$page->id, $name],
$this->get('filename')
);
if ($language && !$language->isDefault()) {
$filename = preg_replace('/\.pdf$/', "-{$language->name}.pdf", $filename);
}
return $filename;
}
/**
* Helper: Check Cache
*/
protected function isCached(Page $page, Language $language = null)
{
$file = $this->getPDFFilePath($page, $language);
if (!is_file($file) || $this->wire('config')->debug)
return false;
return (time() - filemtime($file)) < $this->get('cacheTime');
}
/**
* Helper: Determine Language
*/
protected function determineLanguage()
{
return ($this->get('multilanguageSupport') && $this->wire('languages')) ? $this->wire('user')->language : null;
}
/**
* Helper: Render Link (Pages2Pdf)
*/
public function renderLink(array $options = [])
{
$defaults = [
'title' => 'Print PDF',
'markup' => '<a href="{url}">{title}</a>',
'page_id' => 0
];
$opt = array_merge($defaults, $options);
$page = $opt['page_id'] ? $this->wire('pages')->get((int) $opt['page_id']) : $this->wire('page');
if (!in_array($page->template->name, $this->get('templates')))
return '';
$url = $page->url . "?" . $this->get('getVar') . "=" . $page->id;
return str_replace(['{url}', '{title}'], [$url, $opt['title']], $opt['markup']);
}
/**
* Module Configuration
*/
public static function getModuleConfigInputfields(array $data)
{
$inputfields = new InputfieldWrapper();
$modules = wire('modules');
$config = wire('config');
$input = wire('input');
$sanitizer = wire('sanitizer');
$data = array_merge(self::$defaults, $data);
// --- Custom Font Management ---
$customFontPath = $config->paths->assets . 'Wire2PDF/fonts/';
if (!is_dir($customFontPath)) {
wireMkdir($customFontPath, true);
}
// Handle font uploads
if ($input->requestMethod() == 'POST' && isset($_FILES['font_upload']) && !empty($_FILES['font_upload']['name'][0])) {
// Try to fix permissions if not writable
if (!is_writable($customFontPath)) {
wireChmod($customFontPath);
}
// Check if destination is writable
if (!is_writable($customFontPath)) {
wire('session')->error(sprintf(__('The font upload directory is not writable: %s', __FILE__), $customFontPath));
wire('session')->error(__('Please check directory permissions via FTP (e.g. 755 or 777) or contact your hoster.', __FILE__));
} else {
$uploadedFiles = $_FILES['font_upload'];
$uploadedCount = 0;
$errorMessages = [];
for ($i = 0; $i < count($uploadedFiles['name']); $i++) {
$name = $uploadedFiles['name'][$i];
$tmpName = $uploadedFiles['tmp_name'][$i];
$error = $uploadedFiles['error'][$i];
if ($error !== UPLOAD_ERR_OK) {
if ($error !== UPLOAD_ERR_NO_FILE) { // Ignore empty file inputs
$errorMessages[] = sprintf(__('Error uploading file "%s". PHP upload error code: %d', __FILE__), $name, $error);
}
continue;
}
if (strtolower(pathinfo($name, PATHINFO_EXTENSION)) !== 'ttf') {
$errorMessages[] = sprintf(__('File "%s" is not a .ttf font file.', __FILE__), $name);
continue;
}
$sanitizedName = $sanitizer->filename($name, ['lowercase' => false]);
$destination = $customFontPath . $sanitizedName;
if (move_uploaded_file($tmpName, $destination)) {
$uploadedCount++;
} else {
$errorMessages[] = sprintf(__('Could not move uploaded file "%s" to destination. Please check permissions.', __FILE__), $name);
}
}
if ($uploadedCount > 0) {
wire('session')->message(sprintf(__('Successfully uploaded %d font file(s) to %s', __FILE__), $uploadedCount, $customFontPath));
}
if (count($errorMessages)) {
foreach ($errorMessages as $msg)
wire('session')->error($msg);
}
}
}
// Handle font deletion
if ($input->requestMethod() == 'POST' && $input->post->delete_fonts) {
$deleteFonts = $input->post->delete_fonts;
if (is_array($deleteFonts)) {
$deletedCount = 0;
foreach ($deleteFonts as $filename) {
$filename = $sanitizer->filename($filename);
$file = $customFontPath . $filename;
if (file_exists($file) && strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'ttf') {
if (@unlink($file))
$deletedCount++;
}
}
if ($deletedCount > 0)
wire('session')->message(sprintf(__('Deleted %d font file(s).', __FILE__), $deletedCount));
}
}
// --- Pages2Pdf Settings ---
$fs = $modules->get('InputfieldFieldset');
$fs->label = __('Automatic PDF Generation (formerly Pages2Pdf)', __FILE__);
$f = $modules->get('InputfieldAsmSelect');
$f->name = 'templates';
$f->label = __('Enabled Templates', __FILE__);
$f->description = __('Pages with these templates can be converted to PDF.', __FILE__);
foreach (wire('templates') as $t) {
if (!($t->flags & Template::flagSystem))
$f->addOption($t->name);
}
$f->value = $data['templates'];
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->name = 'getVar';
$f->label = __('URL GET Variable', __FILE__);
$f->value = $data['getVar'];
$f->columnWidth = 50;
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->name = 'filename';
$f->label = __('Filename Pattern', __FILE__);
$f->description = __('Available: {page.name}, {page.id}', __FILE__);
$f->value = $data['filename'];
$f->columnWidth = 50;
$fs->add($f);
$f = $modules->get('InputfieldCheckbox');
$f->name = 'printHeader';
$f->label = __('Print Header', __FILE__);
$f->checked = $data['printHeader'] ? 'checked' : '';
$f->columnWidth = 50;
$fs->add($f);
$f = $modules->get('InputfieldCheckbox');
$f->name = 'printFooter';
$f->label = __('Print Footer', __FILE__);
$f->checked = $data['printFooter'] ? 'checked' : '';
$f->columnWidth = 50;
$fs->add($f);
$f = $modules->get('InputfieldInteger');
$f->name = 'cacheTime';
$f->label = __('Cache Time (seconds)', __FILE__);
$f->value = $data['cacheTime'];
$fs->add($f);
$f = $modules->get('InputfieldRadios');
$f->name = 'creationMode';
$f->label = __('Creation Mode', __FILE__);
$f->addOptions([
self::CREATION_MODE_CLICK => __('On Click (Download)', __FILE__),
self::CREATION_MODE_SAVE => __('On Page Save', __FILE__)
]);
$f->value = $data['creationMode'];
$fs->add($f);
$f = $modules->get('InputfieldCheckbox');
$f->name = 'multilanguageSupport';
$f->label = __('Multilanguage Support', __FILE__);
$f->checked = $data['multilanguageSupport'] ? 'checked' : '';
$fs->add($f);
$inputfields->add($fs);
// --- WirePDF Settings ---
$fs = $modules->get('InputfieldFieldset');
$fs->label = __('PDF Engine Settings (formerly WirePDF)', __FILE__);
// --- Font Settings ---
$fsFonts = $modules->get('InputfieldFieldset');
$fsFonts->label = __('Font Settings', __FILE__);
$fsFonts->description = __('Here you can upload custom .ttf font files. After uploading, they will be available in the "Default Font" dropdown.', __FILE__);
$f = $modules->get('InputfieldMarkup');
$f->label = __('Upload Font Files', __FILE__);
$f->value = "<input type='file' name='font_upload[]' multiple='multiple' accept='.ttf'>" .
"<script>$(document).ready(function() { $('#ModuleEditForm').attr('enctype', 'multipart/form-data'); });</script>";
$f->notes = __('After selecting files, click \'Save\' at the bottom of the page to upload them.', __FILE__);
$fsFonts->add($f);
$fMarkup = $modules->get('InputfieldMarkup');
$fMarkup->label = __('Installed Custom Fonts', __FILE__);
$fontFiles = glob($customFontPath . '*.ttf');
if (is_array($fontFiles) && count($fontFiles)) {
$list = '<ul style="list-style:none; padding-left:0;">';
foreach ($fontFiles as $file) {
$filename = basename($file);
$list .= '<li style="padding: 6px 0; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center;">' .
'<span>' . $sanitizer->entities($filename) . '</span>' .
'<label style="cursor: pointer;" title="' . __('Delete', __FILE__) . '">' .
'<input type="checkbox" name="delete_fonts[]" value="' . $sanitizer->entities($filename) . '"> ' .
'<i class="fa fa-trash" style="margin-left: 6px; font-size: 1.2em;"></i></label></li>';
}
$list .= '</ul>';
$fMarkup->value = $list;
$fMarkup->notes = __('Check the trash icon next to a font and click Save to delete it.', __FILE__);
} else {
$fMarkup->value = '<p>' . __('No custom fonts uploaded yet.', __FILE__) . '</p>';
}
$fsFonts->add($fMarkup);
$f = $modules->get('InputfieldSelect');
$f->name = 'font';
$f->label = __('Default Font', __FILE__);
$f->addOptions([
'DejaVuSans' => 'DejaVuSans (mPDF default)',
]);
$customFontOptions = [];
if (is_array($fontFiles)) {
foreach ($fontFiles as $file) {
$fontname = strtolower(pathinfo(basename($file), PATHINFO_FILENAME));
$fontname = preg_replace('/[^a-z0-9]/', '', $fontname);
if (!$fontname)
continue;
$customFontOptions[$fontname] = pathinfo(basename($file), PATHINFO_FILENAME);
}
if (count($customFontOptions))
$f->addOptions($customFontOptions, __('Custom Fonts', __FILE__));
}
$f->value = $data['font'];
$fsFonts->add($f);
$fs->add($fsFonts);
// --- End Font Settings ---
$f = $modules->get('InputfieldText');
$f->name = 'pageFormat';
$f->label = __('Page Format', __FILE__);
$f->value = $data['pageFormat'];
$f->columnWidth = 50;
$fs->add($f);
$f = $modules->get('InputfieldSelect');
$f->name = 'pageOrientation';
$f->label = __('Orientation', __FILE__);
$f->addOptions(['P' => __('Portrait', __FILE__), 'L' => __('Landscape', __FILE__)]);
$f->value = $data['pageOrientation'];
$f->columnWidth = 50;
$fs->add($f);
$f = $modules->get('InputfieldCheckbox');
$f->name = 'pdfa';
$f->label = __('PDF/A-1b Compliance', __FILE__);
$f->description = __('Enables PDF/A-1b compliance. Forces font embedding and stricter standards.', __FILE__);
$f->checked = $data['pdfa'] ? 'checked' : '';
$fs->add($f);
$margins = [
'leftMargin' => __('Left Margin (mm)', __FILE__),
'topMargin' => __('Top Margin (mm)', __FILE__),
'rightMargin' => __('Right Margin (mm)', __FILE__),
'bottomMargin' => __('Bottom Margin (mm)', __FILE__),
'headerMargin' => __('Header Margin (mm)', __FILE__),
'footerMargin' => __('Footer Margin (mm)', __FILE__)
];
foreach ($margins as $m => $label) {
$f = $modules->get('InputfieldFloat');
$f->name = $m;
$f->label = $label;
$f->value = $data[$m];
$f->columnWidth = 50;
$fs->add($f);
}
$f = $modules->get('InputfieldInteger');
$f->name = 'fontSize';
$f->label = __('Default Font Size (pt). Can be overridden with CSS', __FILE__);
$f->value = $data['fontSize'];
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->name = 'cssFile';
$f->label = __('CSS File', __FILE__);
$f->description = __('Enter path and filename of a CSS file containing default styles to be used by mPDF for the HTML markup', __FILE__);
$f->value = $data['cssFile'];
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->name = 'author';
$f->label = __('PDF Author', __FILE__);
$f->value = $data['author'];
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->name = 'title';
$f->label = __('PDF Title', __FILE__);
$f->description = __('Available variables: {page.name}, {page.title}, {page.id} and any other field like {field_name}', __FILE__);
$f->value = $data['title'];
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->name = 'subject';
$f->label = __('PDF Subject', __FILE__);
$f->description = __('Available variables: {page.name}, {page.title}, {page.id} and any other field like {field_name}', __FILE__);
$f->value = $data['subject'];
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->name = 'keywords';
$f->label = __('PDF Keywords', __FILE__);
$f->description = __('Available variables: {page.name}, {page.title}, {page.id} and any other field like {field_name}', __FILE__);
$f->value = $data['keywords'];
$fs->add($f);
$f = $modules->get('InputfieldText');
$f->name = 'creator';
$f->label = __('PDF Creator', __FILE__);
$f->value = $data['creator'];
$fs->add($f);
$inputfields->add($fs);
return $inputfields;
}
}