xref: /webtrees/app/Report/PdfRenderer.php (revision a3148b03cff68ac7a179d4636354b8e1c00044ca)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Report;
21
22use Fisharebest\Webtrees\MediaFile;
23use Fisharebest\Webtrees\Webtrees;
24use League\Flysystem\FilesystemOperator;
25
26use function count;
27
28/**
29 * Class PdfRenderer
30 */
31class PdfRenderer extends AbstractRenderer
32{
33    /**
34     * PDF compression - Zlib extension is required
35     *
36     * @var bool const
37     */
38    private const COMPRESSION = true;
39
40    /**
41     * If true reduce the RAM memory usage by caching temporary data on filesystem (slower).
42     *
43     * @var bool const
44     */
45    private const DISK_CACHE = false;
46
47    /**
48     * true means that the input text is unicode (PDF)
49     *
50     * @var bool const
51     */
52    private const UNICODE = true;
53
54    // Font sub-setting in TCPDF is slow.
55    private const SUBSETTING = false;
56
57    public TcpdfWrapper $tcpdf;
58
59    /** @var array<ReportPdfFootnote> Array of elements in the footer notes */
60    public array $printedfootnotes = [];
61
62    // The last cell height
63    public float $lastCellHeight = 0.0;
64
65    // The largest font size within a TextBox to calculate the height
66    public float $largestFontHeight = 0.0;
67
68    // The last pictures page number
69    public int $lastpicpage = 0;
70
71    /**
72     * PDF Header -PDF
73     *
74     * @return void
75     */
76    public function header(): void
77    {
78        foreach ($this->headerElements as $element) {
79            if ($element instanceof ReportBaseElement) {
80                $element->render($this);
81            } elseif ($element === 'footnotetexts') {
82                $this->footnotes();
83            } elseif ($element === 'addpage') {
84                $this->newPage();
85            }
86        }
87    }
88
89    /**
90     * PDF Body -PDF
91     *
92     * @return void
93     */
94    public function body(): void
95    {
96        $this->tcpdf->AddPage();
97
98        foreach ($this->bodyElements as $key => $element) {
99            if ($element instanceof ReportBaseElement) {
100                $element->render($this);
101            } elseif ($element === 'footnotetexts') {
102                $this->footnotes();
103            } elseif ($element === 'addpage') {
104                $this->newPage();
105            }
106        }
107    }
108
109    /**
110     * PDF Footnotes -PDF
111     *
112     * @return void
113     */
114    public function footnotes(): void
115    {
116        foreach ($this->printedfootnotes as $element) {
117            if ($this->tcpdf->GetY() + $element->getFootnoteHeight($this) > $this->tcpdf->getPageHeight()) {
118                $this->tcpdf->AddPage();
119            }
120
121            $element->renderFootnote($this);
122
123            if ($this->tcpdf->GetY() > $this->tcpdf->getPageHeight()) {
124                $this->tcpdf->AddPage();
125            }
126        }
127    }
128
129    /**
130     * PDF Footer -PDF
131     *
132     * @return void
133     */
134    public function footer(): void
135    {
136        foreach ($this->footerElements as $element) {
137            if ($element instanceof ReportBaseElement) {
138                $element->render($this);
139            } elseif ($element === 'footnotetexts') {
140                $this->footnotes();
141            } elseif ($element === 'addpage') {
142                $this->newPage();
143            }
144        }
145    }
146
147    /**
148     * Remove the header.
149     *
150     * @param int $index
151     *
152     * @return void
153     */
154    public function removeHeader(int $index): void
155    {
156        unset($this->headerElements[$index]);
157    }
158
159    /**
160     * Remove the body.
161     *
162     * @param int $index
163     *
164     * @return void
165     */
166    public function removeBody(int $index): void
167    {
168        unset($this->bodyElements[$index]);
169    }
170
171    /**
172     * Remove the footer.
173     *
174     * @param int $index
175     *
176     * @return void
177     */
178    public function removeFooter(int $index): void
179    {
180        unset($this->footerElements[$index]);
181    }
182
183    /**
184     * Clear the Header -PDF
185     *
186     * @return void
187     */
188    public function clearHeader(): void
189    {
190        unset($this->headerElements);
191        $this->headerElements = [];
192    }
193
194    /**
195     * Get the currently used style name -PDF
196     *
197     * @return string
198     */
199    public function getCurrentStyle(): string
200    {
201        return $this->currentStyle;
202    }
203
204    /**
205     * Setup a style for usage -PDF
206     *
207     * @param string $s Style name
208     *
209     * @return void
210     */
211    public function setCurrentStyle(string $s): void
212    {
213        $this->currentStyle = $s;
214        $style              = $this->getStyle($s);
215        $this->tcpdf->SetFont($style['font'], $style['style'], $style['size']);
216    }
217
218    /**
219     * Get the style -PDF
220     *
221     * @param string $s Style name
222     *
223     * @return array
224     */
225    public function getStyle(string $s): array
226    {
227        if (!isset($this->styles[$s])) {
228            $s                = $this->getCurrentStyle();
229            $this->styles[$s] = $s;
230        }
231
232        return $this->styles[$s];
233    }
234
235    /**
236     * Add margin when static horizontal position is used -PDF
237     * RTL supported
238     *
239     * @param float $x Static position
240     *
241     * @return float
242     */
243    public function addMarginX(float $x): float
244    {
245        $m = $this->tcpdf->getMargins();
246        if ($this->tcpdf->getRTL()) {
247            $x += $m['right'];
248        } else {
249            $x += $m['left'];
250        }
251        $this->tcpdf->SetX($x);
252
253        return $x;
254    }
255
256    /**
257     * Get the maximum line width to draw from the curren position -PDF
258     * RTL supported
259     *
260     * @return float
261     */
262    public function getMaxLineWidth(): float
263    {
264        $m = $this->tcpdf->getMargins();
265        if ($this->tcpdf->getRTL()) {
266            return $this->tcpdf->getRemainingWidth() + $m['right'];
267        }
268
269        return $this->tcpdf->getRemainingWidth() + $m['left'];
270    }
271
272    /**
273     * Get the height of the footnote.
274     *
275     * @return float
276     */
277    public function getFootnotesHeight(): float
278    {
279        $h = 0;
280        foreach ($this->printedfootnotes as $element) {
281            $h += $element->getHeight($this);
282        }
283
284        return $h;
285    }
286
287    /**
288     * Returns the the current font size height -PDF
289     *
290     * @return float
291     */
292    public function getCurrentStyleHeight(): float
293    {
294        if ($this->currentStyle === '') {
295            return $this->default_font_size;
296        }
297        $style = $this->getStyle($this->currentStyle);
298
299        return (float) $style['size'];
300    }
301
302    /**
303     * Checks the Footnote and numbers them
304     *
305     * @param ReportPdfFootnote $footnote
306     *
307     * @return ReportPdfFootnote|bool object if already numbered, false otherwise
308     */
309    public function checkFootnote(ReportPdfFootnote $footnote)
310    {
311        $ct  = count($this->printedfootnotes);
312        $val = $footnote->getValue();
313        $i   = 0;
314        while ($i < $ct) {
315            if ($this->printedfootnotes[$i]->getValue() == $val) {
316                // If this footnote already exist then set up the numbers for this object
317                $footnote->setNum($i + 1);
318                $footnote->setAddlink((string) ($i + 1));
319
320                return $this->printedfootnotes[$i];
321            }
322            $i++;
323        }
324        // If this Footnote has not been set up yet
325        $footnote->setNum($ct + 1);
326        $footnote->setAddlink((string) $this->tcpdf->AddLink());
327        $this->printedfootnotes[] = $footnote;
328
329        return false;
330    }
331
332    /**
333     * Used this function instead of AddPage()
334     * This function will make sure that images will not be overwritten
335     *
336     * @return void
337     */
338    public function newPage(): void
339    {
340        if ($this->lastpicpage > $this->tcpdf->getPage()) {
341            $this->tcpdf->setPage($this->lastpicpage);
342        }
343        $this->tcpdf->AddPage();
344    }
345
346    /**
347     * Add a page if needed -PDF
348     *
349     * @param float $height Cell height
350     *
351     * @return bool true in case of page break, false otherwise
352     */
353    public function checkPageBreakPDF(float $height): bool
354    {
355        return $this->tcpdf->checkPageBreak($height);
356    }
357
358    /**
359     * Returns the remaining width between the current position and margins -PDF
360     *
361     * @return float Remaining width
362     */
363    public function getRemainingWidthPDF(): float
364    {
365        return $this->tcpdf->getRemainingWidth();
366    }
367    /**
368     * PDF Setup - ReportPdf
369     *
370     * @return void
371     */
372    public function setup(): void
373    {
374        parent::setup();
375
376        $this->tcpdf = new TcpdfWrapper(
377            $this->orientation,
378            self::UNITS,
379            [$this->page_width, $this->page_height],
380            self::UNICODE,
381            'UTF-8',
382            self::DISK_CACHE
383        );
384
385        $this->tcpdf->SetMargins($this->left_margin, $this->top_margin, $this->right_margin);
386        $this->tcpdf->setHeaderMargin($this->header_margin);
387        $this->tcpdf->setFooterMargin($this->footer_margin);
388        $this->tcpdf->SetAutoPageBreak(true, $this->bottom_margin);
389        $this->tcpdf->setFontSubsetting(self::SUBSETTING);
390        $this->tcpdf->SetCompression(self::COMPRESSION);
391        $this->tcpdf->setRTL($this->rtl);
392        $this->tcpdf->SetCreator(Webtrees::NAME . ' ' . Webtrees::VERSION);
393        $this->tcpdf->SetAuthor($this->rauthor);
394        $this->tcpdf->SetTitle($this->title);
395        $this->tcpdf->SetSubject($this->rsubject);
396        $this->tcpdf->SetKeywords($this->rkeywords);
397        $this->tcpdf->SetHeaderData('', 0, $this->title);
398        $this->tcpdf->setHeaderFont([$this->default_font, '', $this->default_font_size]);
399
400        if ($this->show_generated_by) {
401            // The default style name for Generated by.... is 'genby'
402            $element = new ReportPdfCell(0, 10, 0, 'C', '', 'genby', 1, ReportBaseElement::CURRENT_POSITION, ReportBaseElement::CURRENT_POSITION, 0, 0, '', '', true);
403            $element->addText($this->generated_by);
404            $element->setUrl(Webtrees::URL);
405            $this->addElementToFooter($element);
406        }
407    }
408
409    /**
410     * Run the report.
411     *
412     * @return void
413     */
414    public function run(): void
415    {
416        $this->body();
417        echo $this->tcpdf->Output('doc.pdf', 'S');
418    }
419
420    /**
421     * Create a new Cell object.
422     *
423     * @param int    $width   cell width (expressed in points)
424     * @param int    $height  cell height (expressed in points)
425     * @param mixed  $border  Border style
426     * @param string $align   Text alignement
427     * @param string $bgcolor Background color code
428     * @param string $style   The name of the text style
429     * @param int    $ln      Indicates where the current position should go after the call
430     * @param mixed  $top     Y-position
431     * @param mixed  $left    X-position
432     * @param int    $fill    Indicates if the cell background must be painted (1) or transparent (0). Default value: 1
433     * @param int    $stretch Stretch carachter mode
434     * @param string $bocolor Border color
435     * @param string $tcolor  Text color
436     * @param bool   $reseth
437     *
438     * @return ReportBaseCell
439     */
440    public function createCell(int $width, int $height, $border, string $align, string $bgcolor, string $style, int $ln, $top, $left, int $fill, int $stretch, string $bocolor, string $tcolor, bool $reseth): ReportBaseCell
441    {
442        return new ReportPdfCell($width, $height, $border, $align, $bgcolor, $style, $ln, $top, $left, $fill, $stretch, $bocolor, $tcolor, $reseth);
443    }
444
445    /**
446     * Create a new TextBox object.
447     *
448     * @param float  $width   Text box width
449     * @param float  $height  Text box height
450     * @param bool   $border
451     * @param string $bgcolor Background color code in HTML
452     * @param bool   $newline
453     * @param float  $left
454     * @param float  $top
455     * @param bool   $pagecheck
456     * @param string $style
457     * @param bool   $fill
458     * @param bool   $padding
459     * @param bool   $reseth
460     *
461     * @return ReportBaseTextbox
462     */
463    public function createTextBox(
464        float $width,
465        float $height,
466        bool $border,
467        string $bgcolor,
468        bool $newline,
469        float $left,
470        float $top,
471        bool $pagecheck,
472        string $style,
473        bool $fill,
474        bool $padding,
475        bool $reseth
476    ): ReportBaseTextbox {
477        return new ReportPdfTextBox($width, $height, $border, $bgcolor, $newline, $left, $top, $pagecheck, $style, $fill, $padding, $reseth);
478    }
479
480    /**
481     * Create a text element.
482     *
483     * @param string $style
484     * @param string $color
485     *
486     * @return ReportBaseText
487     */
488    public function createText(string $style, string $color): ReportBaseText
489    {
490        return new ReportPdfText($style, $color);
491    }
492
493    /**
494     * Create a new Footnote object.
495     *
496     * @param string $style Style name
497     *
498     * @return ReportBaseFootnote
499     */
500    public function createFootnote(string $style): ReportBaseFootnote
501    {
502        return new ReportPdfFootnote($style);
503    }
504
505    /**
506     * Create a new image object.
507     *
508     * @param string $file  Filename
509     * @param float  $x
510     * @param float  $y
511     * @param float  $w     Image width
512     * @param float  $h     Image height
513     * @param string $align L:left, C:center, R:right or empty to use x/y
514     * @param string $ln    T:same line, N:next line
515     *
516     * @return ReportBaseImage
517     */
518    public function createImage(string $file, float $x, float $y, float $w, float $h, string $align, string $ln): ReportBaseImage
519    {
520        return new ReportPdfImage($file, $x, $y, $w, $h, $align, $ln);
521    }
522
523    /**
524     * Create a new image object from Media Object.
525     *
526     * @param MediaFile          $media_file
527     * @param float              $x
528     * @param float              $y
529     * @param float              $w     Image width
530     * @param float              $h     Image height
531     * @param string             $align L:left, C:center, R:right or empty to use x/y
532     * @param string             $ln    T:same line, N:next line
533     * @param FilesystemOperator $data_filesystem
534     *
535     * @return ReportBaseImage
536     */
537    public function createImageFromObject(
538        MediaFile $media_file,
539        float $x,
540        float $y,
541        float $w,
542        float $h,
543        string $align,
544        string $ln,
545        FilesystemOperator $data_filesystem
546    ): ReportBaseImage {
547        return new ReportPdfImage('@' . $media_file->fileContents($data_filesystem), $x, $y, $w, $h, $align, $ln);
548    }
549
550    /**
551     * Create a line.
552     *
553     * @param float $x1
554     * @param float $y1
555     * @param float $x2
556     * @param float $y2
557     *
558     * @return ReportBaseLine
559     */
560    public function createLine(float $x1, float $y1, float $x2, float $y2): ReportBaseLine
561    {
562        return new ReportPdfLine($x1, $y1, $x2, $y2);
563    }
564}
565