xref: /webtrees/app/Report/PdfRenderer.php (revision a8b39ba2d349525974d59077419f7a8ea8802aaa)
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 $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     * Generate footnotes
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     * Clear the Header -PDF
173     *
174     * @return void
175     */
176    public function clearHeader(): void
177    {
178        unset($this->headerElements);
179        $this->headerElements = [];
180    }
181
182    /**
183     * Get the currently used style name -PDF
184     *
185     * @return string
186     */
187    public function getCurrentStyle(): string
188    {
189        return $this->currentStyle;
190    }
191
192    /**
193     * Setup a style for usage -PDF
194     *
195     * @param string $s Style name
196     *
197     * @return void
198     */
199    public function setCurrentStyle(string $s): void
200    {
201        $this->currentStyle = $s;
202        $style              = $this->getStyle($s);
203        $this->tcpdf->SetFont($style['font'], $style['style'], $style['size']);
204    }
205
206    /**
207     * Get the style -PDF
208     *
209     * @param string $s Style name
210     *
211     * @return array
212     */
213    public function getStyle(string $s): array
214    {
215        if (!isset($this->styles[$s])) {
216            $s                = $this->getCurrentStyle();
217            $this->styles[$s] = $s;
218        }
219
220        return $this->styles[$s];
221    }
222
223    /**
224     * Add margin when static horizontal position is used -PDF
225     * RTL supported
226     *
227     * @param float $x Static position
228     *
229     * @return float
230     */
231    public function addMarginX(float $x): float
232    {
233        $m = $this->tcpdf->getMargins();
234        if ($this->tcpdf->getRTL()) {
235            $x += $m['right'];
236        } else {
237            $x += $m['left'];
238        }
239        $this->tcpdf->SetX($x);
240
241        return $x;
242    }
243
244    /**
245     * Get the maximum line width to draw from the curren position -PDF
246     * RTL supported
247     *
248     * @return float
249     */
250    public function getMaxLineWidth(): float
251    {
252        $m = $this->tcpdf->getMargins();
253        if ($this->tcpdf->getRTL()) {
254            return $this->tcpdf->getRemainingWidth() + $m['right'];
255        }
256
257        return $this->tcpdf->getRemainingWidth() + $m['left'];
258    }
259
260    /**
261     * Get the height of the footnote.
262     *
263     * @return float
264     */
265    public function getFootnotesHeight(): float
266    {
267        $h = 0;
268        foreach ($this->printedfootnotes as $element) {
269            $h += $element->getHeight($this);
270        }
271
272        return $h;
273    }
274
275    /**
276     * Returns the the current font size height -PDF
277     *
278     * @return float
279     */
280    public function getCurrentStyleHeight(): float
281    {
282        if ($this->currentStyle === '') {
283            return $this->default_font_size;
284        }
285        $style = $this->getStyle($this->currentStyle);
286
287        return (float) $style['size'];
288    }
289
290    /**
291     * Checks the Footnote and numbers them
292     *
293     * @param ReportPdfFootnote $footnote
294     *
295     * @return ReportPdfFootnote|bool object if already numbered, false otherwise
296     */
297    public function checkFootnote(ReportPdfFootnote $footnote)
298    {
299        $ct  = count($this->printedfootnotes);
300        $val = $footnote->getValue();
301        $i   = 0;
302        while ($i < $ct) {
303            if ($this->printedfootnotes[$i]->getValue() === $val) {
304                // If this footnote already exist then set up the numbers for this object
305                $footnote->setNum($i + 1);
306                $footnote->setAddlink((string) ($i + 1));
307
308                return $this->printedfootnotes[$i];
309            }
310            $i++;
311        }
312        // If this Footnote has not been set up yet
313        $footnote->setNum($ct + 1);
314        $footnote->setAddlink((string) $this->tcpdf->AddLink());
315        $this->printedfootnotes[] = $footnote;
316
317        return false;
318    }
319
320    /**
321     * Used this function instead of AddPage()
322     * This function will make sure that images will not be overwritten
323     *
324     * @return void
325     */
326    public function newPage(): void
327    {
328        if ($this->lastpicpage > $this->tcpdf->getPage()) {
329            $this->tcpdf->setPage($this->lastpicpage);
330        }
331        $this->tcpdf->AddPage();
332    }
333
334    /**
335     * Add a page if needed -PDF
336     *
337     * @param float $height Cell height
338     *
339     * @return bool true in case of page break, false otherwise
340     */
341    public function checkPageBreakPDF(float $height): bool
342    {
343        return $this->tcpdf->checkPageBreak($height);
344    }
345
346    /**
347     * Returns the remaining width between the current position and margins -PDF
348     *
349     * @return float Remaining width
350     */
351    public function getRemainingWidthPDF(): float
352    {
353        return $this->tcpdf->getRemainingWidth();
354    }
355    /**
356     * PDF Setup - ReportPdf
357     *
358     * @return void
359     */
360    public function setup(): void
361    {
362        parent::setup();
363
364        $this->tcpdf = new TcpdfWrapper(
365            $this->orientation,
366            self::UNITS,
367            [$this->page_width, $this->page_height],
368            self::UNICODE,
369            'UTF-8',
370            self::DISK_CACHE
371        );
372
373        $this->tcpdf->SetMargins($this->left_margin, $this->top_margin, $this->right_margin);
374        $this->tcpdf->setHeaderMargin($this->header_margin);
375        $this->tcpdf->setFooterMargin($this->footer_margin);
376        $this->tcpdf->SetAutoPageBreak(true, $this->bottom_margin);
377        $this->tcpdf->setFontSubsetting(self::SUBSETTING);
378        $this->tcpdf->SetCompression(self::COMPRESSION);
379        $this->tcpdf->setRTL($this->rtl);
380        $this->tcpdf->SetCreator(Webtrees::NAME . ' ' . Webtrees::VERSION);
381        $this->tcpdf->SetAuthor($this->rauthor);
382        $this->tcpdf->SetTitle($this->title);
383        $this->tcpdf->SetSubject($this->rsubject);
384        $this->tcpdf->SetKeywords($this->rkeywords);
385        $this->tcpdf->SetHeaderData('', 0, $this->title);
386        $this->tcpdf->setHeaderFont([$this->default_font, '', $this->default_font_size]);
387
388        if ($this->show_generated_by) {
389            // The default style name for Generated by.... is 'genby'
390            $element = new ReportPdfCell(0.0, 10.0, '', 'C', '', 'genby', 1, ReportBaseElement::CURRENT_POSITION, ReportBaseElement::CURRENT_POSITION, 0, 0, '', '', true);
391            $element->addText($this->generated_by);
392            $element->setUrl(Webtrees::URL);
393            $this->addElementToFooter($element);
394        }
395    }
396
397    /**
398     * Run the report.
399     *
400     * @return void
401     */
402    public function run(): void
403    {
404        $this->body();
405        echo $this->tcpdf->Output('doc.pdf', 'S');
406    }
407
408    /**
409     * Create a new Cell object.
410     *
411     * @param float  $width   cell width (expressed in points)
412     * @param float  $height  cell height (expressed in points)
413     * @param string $border  Border style
414     * @param string $align   Text alignment
415     * @param string $bgcolor Background color code
416     * @param string $style   The name of the text style
417     * @param int    $ln      Indicates where the current position should go after the call
418     * @param mixed  $top     Y-position
419     * @param mixed  $left    X-position
420     * @param int    $fill    Indicates if the cell background must be painted (1) or transparent (0). Default value: 1
421     * @param int    $stretch Stretch carachter mode
422     * @param string $bocolor Border color
423     * @param string $tcolor  Text color
424     * @param bool   $reseth
425     *
426     * @return ReportBaseCell
427     */
428    public function createCell(float $width, float $height, string $border, string $align, string $bgcolor, string $style, int $ln, $top, $left, int $fill, int $stretch, string $bocolor, string $tcolor, bool $reseth): ReportBaseCell
429    {
430        return new ReportPdfCell($width, $height, $border, $align, $bgcolor, $style, $ln, $top, $left, $fill, $stretch, $bocolor, $tcolor, $reseth);
431    }
432
433    /**
434     * Create a new TextBox object.
435     *
436     * @param float  $width   Text box width
437     * @param float  $height  Text box height
438     * @param bool   $border
439     * @param string $bgcolor Background color code in HTML
440     * @param bool   $newline
441     * @param float  $left
442     * @param float  $top
443     * @param bool   $pagecheck
444     * @param string $style
445     * @param bool   $fill
446     * @param bool   $padding
447     * @param bool   $reseth
448     *
449     * @return ReportBaseTextbox
450     */
451    public function createTextBox(
452        float $width,
453        float $height,
454        bool $border,
455        string $bgcolor,
456        bool $newline,
457        float $left,
458        float $top,
459        bool $pagecheck,
460        string $style,
461        bool $fill,
462        bool $padding,
463        bool $reseth
464    ): ReportBaseTextbox {
465        return new ReportPdfTextBox($width, $height, $border, $bgcolor, $newline, $left, $top, $pagecheck, $style, $fill, $padding, $reseth);
466    }
467
468    /**
469     * Create a text element.
470     *
471     * @param string $style
472     * @param string $color
473     *
474     * @return ReportBaseText
475     */
476    public function createText(string $style, string $color): ReportBaseText
477    {
478        return new ReportPdfText($style, $color);
479    }
480
481    /**
482     * Create a new Footnote object.
483     *
484     * @param string $style Style name
485     *
486     * @return ReportBaseFootnote
487     */
488    public function createFootnote(string $style): ReportBaseFootnote
489    {
490        return new ReportPdfFootnote($style);
491    }
492
493    /**
494     * Create a new image object.
495     *
496     * @param string $file  Filename
497     * @param float  $x
498     * @param float  $y
499     * @param float  $w     Image width
500     * @param float  $h     Image height
501     * @param string $align L:left, C:center, R:right or empty to use x/y
502     * @param string $ln    T:same line, N:next line
503     *
504     * @return ReportBaseImage
505     */
506    public function createImage(string $file, float $x, float $y, float $w, float $h, string $align, string $ln): ReportBaseImage
507    {
508        return new ReportPdfImage($file, $x, $y, $w, $h, $align, $ln);
509    }
510
511    /**
512     * Create a new image object from Media Object.
513     *
514     * @param MediaFile          $media_file
515     * @param float              $x
516     * @param float              $y
517     * @param float              $w     Image width
518     * @param float              $h     Image height
519     * @param string             $align L:left, C:center, R:right or empty to use x/y
520     * @param string             $ln    T:same line, N:next line
521     * @param FilesystemOperator $data_filesystem
522     *
523     * @return ReportBaseImage
524     */
525    public function createImageFromObject(
526        MediaFile $media_file,
527        float $x,
528        float $y,
529        float $w,
530        float $h,
531        string $align,
532        string $ln,
533        FilesystemOperator $data_filesystem
534    ): ReportBaseImage {
535        return new ReportPdfImage('@' . $media_file->fileContents($data_filesystem), $x, $y, $w, $h, $align, $ln);
536    }
537
538    /**
539     * Create a line.
540     *
541     * @param float $x1
542     * @param float $y1
543     * @param float $x2
544     * @param float $y2
545     *
546     * @return ReportBaseLine
547     */
548    public function createLine(float $x1, float $y1, float $x2, float $y2): ReportBaseLine
549    {
550        return new ReportPdfLine($x1, $y1, $x2, $y2);
551    }
552}
553