File Coverage

File:blib/lib/Database/BI/Pdf.pm
Coverage:88.8%

linestmtbrancondsubtimecode
1package Database::BI::Pdf;
2
3
1
1
1
152692
1
5
use strict;
4
1
1
1
1
1
17
use warnings;
5
6our $VERSION = '0.025.0';
7
8
1
1
1
1
1
24
use Carp qw(croak);
9
1
1
1
1
1
3
use Encode ();
10
1
1
1
201
34288
11
use PDF::API2;
11
1
1
1
2
1
4
use Scalar::Util ();
12
1
1
1
1
0
8
use Exporter qw(import);
13
1
1
1
131
956
422
use Readonly;
14
15# Why PDF::Table is not used: it was tried (1.007) and takes about 2 ms a row,
16# five times what the layout below costs with PDF::API2 alone (2,000 rows 4 s,
17# against 20,000 rows 8 s), so a 50,000-row PDF would take over a minute.  It
18# also wraps long cells, which makes row heights and page counts unpredictable
19# (this module cuts a cell short with "..." instead), and it has no "Page N of
20# M", which needs the page count before any page is drawn.  The layout is about
21# 60 lines; PDF::API2 does the rest.
22our @EXPORT_OK = qw(table_pdf text_width);
23
24=encoding utf8
25
26 - 49
=head1 NAME

Database::BI::Pdf - A table as a PDF

=head1 SYNOPSIS

    use Database::BI::Pdf qw(table_pdf);
    my $bytes = table_pdf(
        title   => 'sales',
        lines   => [ 'Filters: region is North' ],
        columns => [ 'region', 'amount' ],
        rows    => [ [ 'North', 10 ], [ 'North', 20 ] ],
    );

=head1 DESCRIPTION

Writes a PDF of a heading and a table for views too large for the browser to
lay out.  The PDF is made by L<PDF::API2>; this module only lays the table out.
It uses the PDF's own Helvetica, so no font is embedded.  Text is written in
Windows Latin-1 (WinAnsi): accents and the usual punctuation come out as
written, any other character as C<?>.  A cell wider than its column is cut short with C<...>; nothing wraps.
Each page repeats the header row and says "Page N of M".

=cut
50
51Readonly my $FONT_SIZE  => 8;
52Readonly my $ROW_HEIGHT => 12;
53Readonly my $MARGIN     => 36;
54Readonly my $PAD        => 3;
55Readonly my $MIN_COL    => 24;
56Readonly my $MAX_COL    => 240;
57Readonly my $SAMPLE     => 500;      # rows read to size the columns
58Readonly my @PAPER      => (595, 842);       # A4, points
59
60 - 79
=head1 FUNCTIONS

=head2 text_width

    text_width($text, $size)

The width in points of C<$text> in Helvetica at C<$size>.

=head3 API SPECIFICATION

=head4 INPUT

    $text : string
    $size : number, default 8

=head4 OUTPUT

A number.

=cut
80
81my $measure;    # one Helvetica, to ask for widths
82my %WIDTH_OF;   # its width of each string seen
83
84sub text_width {
85
1046
3079
        my ($text, $size) = @_;
86
1046
919
        $size //= $FONT_SIZE;
87
1046
951
        return 0 unless defined $text;
88
1046
411
        $measure //= PDF::API2->new->font('Helvetica');
89
1046
10934
        %WIDTH_OF = () if keys %WIDTH_OF > 20_000;
90
1046
914
        return ($WIDTH_OF{$text} //= $measure->width(_clean($text))) * $size;
91}
92
93# Text with control characters turned to spaces and anything WinAnsi lacks to "?".
94sub _clean {
95
1443
532
        my ($text) = @_;
96
1443
585
        $text = '' unless defined $text;
97
1443
547
        $text =~ s/[\x00-\x1f\x7f]+/ /g;
98
1443
2
1066
10
        return Encode::decode('cp1252', Encode::encode('cp1252', $text, sub { '?' }));
99}
100
101# $text cut to fit $width points, with "..." when it was cut.
102sub _fit {
103
489
932
        my ($text, $width) = @_;
104
489
176
        $text = _clean($text);
105
489
2947
        return $text if text_width($text) <= $width;
106
1
1
        my $dots = text_width('...');
107
1
27
        return '' if $width <= $dots;
108
1
1
        my $out = '';
109
1
0
        my $used = 0;
110
1
52
        for my $ch (split //, $text) {
111
67
20
                my $w = text_width($ch);
112
67
96
                last if $used + $w + $dots > $width;
113
66
22
                $out .= $ch;
114
66
24
                $used += $w;
115        }
116
1
18
        return $out . '...';
117}
118
119 - 138
=head2 table_pdf

    my $bytes = table_pdf(title => ..., lines => [...], columns => [...], rows => [[...], ...]);

=head3 API SPECIFICATION

=head4 INPUT

    title   : string, optional; large text on the first page
    lines   : arrayref of strings, optional; under the title
    columns : arrayref of names (at least one)
    rows    : arrayref of arrayrefs, one cell per column; may be empty
    footer  : string, optional; bottom left of every page

=head4 OUTPUT

The PDF as bytes.  A table of more than five columns is on landscape A4,
otherwise portrait.  Croaks without columns.

=cut
139
140sub table_pdf {
141
8
90307
        my %a = @_;
142
8
8
7
14
        my @columns = @{ $a{columns} // [] };
143
8
19
        croak 'table_pdf: columns are needed' unless @columns;
144
7
7
5
12
        my @rows   = @{ $a{rows}  // [] };
145
7
7
9
11
        my @lines  = @{ $a{lines} // [] };
146
7
7
        my $title  = $a{title};
147
7
11
        my $footer = $a{footer} // 'Database::BI';
148
149
7
24
        my ($pw, $ph) = @columns > 5 ? @PAPER[1, 0] : @PAPER;
150
7
51
        my $usable = $pw - 2 * $MARGIN;
151
152        # Column widths: what the header and the first rows need, shrunk to fit.
153
7
13
18
324
        my @want = map { text_width($_, $FONT_SIZE) * 1.1 + 2 * $PAD } @columns;
154
7
127
        for my $r (@rows[0 .. ($#rows < $SAMPLE ? $#rows : $SAMPLE - 1)]) {
155
221
113
                for my $i (0 .. $#columns) {
156
464
181
                        my $w = text_width($r->[$i], $FONT_SIZE) + 2 * $PAD;
157
464
14791
                        $want[$i] = $w if $w > $want[$i];
158                }
159        }
160
7
13
13
10
17
23
        for (@want) { $_ = $MAX_COL if $_ > $MAX_COL; $_ = $MIN_COL if $_ < $MIN_COL }
161
7
16
        my $total = 0;
162
7
9
        $total += $_ for @want;
163
7
8
        if ($total > $usable) {
164
0
0
                my $scale = $usable / $total;
165
0
0
0
0
0
0
                @want = map { my $w = $_ * $scale; $w < 8 ? 8 : $w } @want;
166        }
167
7
7
        my @x = ($MARGIN);
168
7
19
        push @x, $x[-1] + $want[$_] for 0 .. $#want - 1;
169
7
5
        my $right = $x[-1] + $want[-1];
170
171        # How many rows each page holds.
172
7
4
        my $head_h = 0;
173
7
13
        $head_h += 20 if defined $title && length $title;
174
7
5
        $head_h += 12 * @lines;
175
7
7
        $head_h += 6 if $head_h;
176
7
6
        my $body_top = $ph - $MARGIN;
177
7
11
        my $bottom   = $MARGIN + 14;
178
7
10
        my $first_cap = int(($body_top - $head_h - $bottom) / $ROW_HEIGHT) - 1; # minus the header row
179
7
15
        my $later_cap = int(($body_top - $bottom) / $ROW_HEIGHT) - 1;
180
7
13
        $first_cap = 1 if $first_cap < 1;
181
7
4
        $later_cap = 1 if $later_cap < 1;
182
183
7
4
        my @pages;      # [ first row index, last row index ]
184
7
4
        my $at = 0;
185
7
2
        my $cap = $first_cap;
186
7
6
        do {
187
10
6
                my $last = $at + $cap - 1;
188
10
9
                $last = $#rows if $last > $#rows;
189
10
4
                push @pages, [ $at, $last ];
190
10
11
                $at = $last + 1;
191
10
11
                $cap = $later_cap;
192        } while ($at <= $#rows);
193
7
4
        my $count = @pages;
194
195
7
19
        my $pdf = PDF::API2->new;
196
7
1933
        $pdf->title($title) if defined $title && length $title;
197
7
45
        my $reg  = $pdf->font('Helvetica');
198
7
47403
        my $bold = $pdf->font('Helvetica-Bold');
199        # One text object a page for each font and size, not one a cell: far faster.
200
7
47269
        my %on;
201        my $text = sub {
202
509
1324
                my ($page, $font, $size, $x, $y, $str) = @_;
203
509
734
                my $t = $on{ join ',', $size, Scalar::Util::refaddr($font) } //= do {
204
34
29
                        my $o = $page->text;
205
34
2494
                        $o->font($font, $size);
206
34
1489
                        $o;
207                };
208
509
315
                $t->matrix(1, 0, 0, 1, $x, $y);
209
509
17299
                $t->text(_clean($str));
210
7
14
        };
211
212
7
8
        for my $p (0 .. $#pages) {
213
10
10
339
9
                my ($lo, $hi) = @{ $pages[$p] };
214
10
16
                my $page = $pdf->page;
215
10
2489
                %on = ();
216
10
13
                $page->mediabox(0, 0, $pw, $ph);
217
10
442
                my $y = $body_top;
218
10
10
                if ($p == 0) {
219
7
12
                        if (defined $title && length $title) {
220
3
3
                                $y -= 14;
221
3
8
                                $text->($page, $bold, 14, $MARGIN, $y, _fit($title, $usable * 1.2 / 1.4));
222
3
342
                                $y -= 6;
223                        }
224
7
7
                        for my $l (@lines) {
225
3
184
                                $y -= 12;
226
3
4
                                $text->($page, $reg, 9, $MARGIN, $y, _fit($l, $usable * 8 / 9));
227                        }
228
7
484
                        $y -= 6 if $head_h;
229                }
230                # The header row: grey band, bold names.
231
10
10
                my $g = $page->graphics;
232
10
554
                $g->fill_color('#e0e0e0');
233
10
492
                $g->rectangle($MARGIN, $y - $ROW_HEIGHT, $right, $y);
234
10
320
                $g->fill;
235
10
89
                $y -= $ROW_HEIGHT;
236
10
18
                for my $i (0 .. $#columns) {
237
19
711
                        $text->($page, $bold, $FONT_SIZE, $x[$i] + $PAD, $y + 3.5, _fit($columns[$i], $want[$i] - 2 * $PAD));
238                }
239
10
582
                my $rules = $page->graphics;
240
10
456
                $rules->stroke_color('#cccccc');
241
10
387
                $rules->line_width(0.5);
242
10
95
                for my $ri ($lo .. $hi) {
243
221
3640
                        last if $ri > $#rows;
244
221
82
                        my $row = $rows[$ri];
245
221
113
                        $y -= $ROW_HEIGHT;
246
221
253
                        for my $i (0 .. $#columns) {
247
464
15436
                                my $v = $row->[$i];
248
464
312
                                next unless defined $v && length $v;
249
464
242
                                $text->($page, $reg, $FONT_SIZE, $x[$i] + $PAD, $y + 3.5, _fit($v, $want[$i] - 2 * $PAD));
250                        }
251
221
13174
                        $rules->move($MARGIN, $y);
252
221
3822
                        $rules->line($right, $y);
253                }
254
10
168
                $rules->stroke;
255
10
81
                $text->($page, $reg, 7, $MARGIN, $MARGIN - 4, $footer);
256
10
1214
                my $pn = sprintf 'Page %d of %d', $p + 1, $count;
257
10
11
                $text->($page, $reg, 7, $right - text_width($pn, 7), $MARGIN - 4, $pn);
258        }
259
7
828
        return $pdf->to_string;
260}
261
262 - 272
=head1 AUTHOR

Nigel Horne C<< <njh@nigelhorne.com> >>

=head1 LICENCE AND COPYRIGHT

Copyright 2026 Nigel Horne.

Usage is subject to the GPL2 licence terms.

=cut
273
2741;