Cairo.pm

filter: Statementstmt 88.2% 15 / 17 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.3% 21 / 23 CC 1 SCAR 0.5
CC
1
Cov
88%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Cairo/Papers.pm ↑ Summary
1 package PDF::Cairo;
2  
3 =encoding utf8
4  
5 =cut
6  
7 # IMPORTANT! Any methods that actually put ink on the page must set
8 # $self->{_dirtypage}=1; this is used by the PDF::API2 compatibility
9 # page() method to avoid creating extra blank pages.
10  
11 1 ▶use 5.016;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Cairo;
Subroutine BEGIN: called CC=1 SCAR=2.6
17 use Image::CairoSVG;
18 use Module::Path 'module_path';
19 use PDF::Cairo::Util;
20  
21 our $VERSION = "1.04";
22 $VERSION = eval $VERSION;
23  
24 =head1 NAME
25  
26 PDF::Cairo - simple API for creating PDF files using the Cairo library
27  
28 =head1 SYNOPSIS
29  
30 PDF::Cairo is loosely based on the API of L<PDF::API2::Lite>, but uses
31 L<Cairo>, L<Font::FreeType>, and (optionally) L<Pango> to provide
32 better support for modern TrueType and OpenType fonts. Compatibility
33 methods are provided to more easily convert existing scripts.
34  
35 use PDF::Cairo qw(cm);
36 $pdf = PDF::Cairo->new(
37 file => "output.pdf",
38 paper => "a4",
39 landscape => 1,
40 );
41 $font = $pdf->loadfont('Times-Bold');
42 $pdf->move(cm(2), cm(4));
43 $pdf->fillcolor('red');
44 $pdf->setfont($font, 32);
45 $pdf->print("Hamburgefontsiv");
46 $image = $pdf->loadimage("logo.png");
47 $pdf->showimage($image, cm(5), cm(5),
48 scale => 0.5, rotate => 45);
49 $pdf->write;
50  
51 =head1 DESCRIPTION
52  
53 L<Cairo|https://www.cairographics.org> is a cross-platform vector
54 graphics library that is capable of generating high-quality PDF output
55 (as well as PNG, PS, and SVG). Unfortunately, the L<Cairo> Perl module
56 is not well documented or easy to use, especially in combination with
57 L<Font::FreeType> and/or L<Pango>. PDF::Cairo adapts the simple and
58 straightforward interface of L<PDF::API2::Lite>, hiding the quirks of
59 the underlying C libraries. Methods that do not return an explicit
60 value return $self so they can be chained.
61  
62 Many scripts can be ported from L<PDF::API2::Lite> just by updating
63 the module name; the L</LIMITATIONS> section at the end of this manual
64 documents a few exceptions and workarounds.
65  
66 L<PDF::Cairo::Box> is a simple rectangle-manipulation library for
67 quickly dividing up a page, useful for making forms, graph papers,
68 calendars, etc.
69  
70 =cut
71  
72 our (
73 @ISA,
74 @EXPORT,
75 @EXPORT_OK,
76 %EXPORT_TAGS,
77 %rgb,
78 $HAS_IMAGEMAGICK,
79 );
80  
81 BEGIN {
82 require Exporter;
83 @ISA = qw(Exporter);
84 @EXPORT = qw();
85 @EXPORT_OK = qw(in mm cm paper_size regular_polygon);
86 %EXPORT_TAGS = (all => \@EXPORT_OK);
87  
88 %rgb = ();
89 #TODO: allow loading NBS/XKCD/Resene rgb.txt
90 my $file = module_path('PDF::Cairo') || "PDF/Cairo/rgb.txt";
91 $file =~ s/\.pm$/\/rgb.txt/;
92 open(my $In, "<", $file) or
93 die "$0: PDF::Cairo::rgb.txt ($file): $!\n";
94 while (<$In>) {
95 next if /^\s*$|^\s[#!]/;
96 chomp;
97 tr/A-Z/a-z/;
98 my ($r,$g,$b,$name) = split(" ", $_, 4);
99 $rgb{$name} = {};
100 $rgb{$name}->{hex} = sprintf("#%2X%2X%2X", $r, $g, $b);
101 $rgb{$name}->{dec} = [ $r, $g, $b ];
102 $rgb{$name}->{float} = [ $r / 255, $g / 255, $b / 255 ];
103 }
104 CORE::close($In);
105  
106 # If convert is in the path, use it to support non-PNG image
107 # formats in loadimage().
108 my $convtmp = `convert --version 2>&1` || '';
109 $HAS_IMAGEMAGICK = $convtmp =~ /ImageMagick/;
110 }
111  
112 INIT {
113 require PDF::Cairo::Font;
114 require PDF::Cairo::Box;
115 }
116  
117 =head2 Creation
118  
119 =over 4
120  
121 =item B<new> %options
122  
123 =over 4
124  
125 =item paper => $paper_size
126  
127 =item file => $file
128  
129 =item height => $Ypts
130  
131 =item width => $Xpts
132  
133 =item wide|landscape => 1
134  
135 =item tall|portrait => 1
136  
137 =back
138  
139 Creates a new PDF document object with the first page initialized. All
140 arguments are optional. If called without either height/width or paper
141 size, it defaults to US Letter (8.5x11 inches). You must use write(),
142 saveas() or stringify() to output the results.
143  
144 =cut
145  
146 sub new {
147 my $class = shift;
148 die "$0: Cairo module built without PDF support!\n"
149 unless Cairo::HAS_PDF_SURFACE;
150 my $self = {};
151 my %options = @_;
152 $options{paper} ||= "usletter";
153 paper_size($self, %options);
154 $self->{filename} = $options{file}
155 if defined $options{file};
156  
157 # if (defined $self->{filename}) {
158 # BUG! Under some poorly-defined circumstances, Freetype can segfault
159 # in FT_Set_Transform when called from Cairo on a surface created with
160 # this method. Need to re-test after Homebrew catches up with Cairo
161 # 1.17.x.
162 # $self->{surface} = Cairo::PdfSurface->create(
163 # $self->{filename}, $self->{w}, $self->{h}
164 # );
165 # }else{
166 $self->{_streamdata} = '';
167 if ($options{_recording}) {
168 my $bbox = {
169 x => 0,
170 y => 0,
171 width => $self->{w},
172 height => $self->{h}
173 };
174 # unlimited recording needed for SVG support
175 $self->{surface} = Cairo::RecordingSurface->create(
176 "color-alpha", $options{_unlimited} ? undef : $bbox);
177 }else{
178 $self->{surface} = Cairo::PdfSurface->create_for_stream(
179 sub {
180 my ($self, $data) = @_;
181 $self->{_streamdata} .= $data;
182 },
183 $self, $self->{w}, $self->{h},
184 );
185 $self->{_is_stream} = 1;
186 }
187 # }
188 _setup_page_state($self);
189  
190 # compatibility hack!
191 # PDF::API2::Lite doesn't directly support clip()/endpath(),
192 # so I have scripts that call them through the reference to
193 # the underlying PDF::API2 object. This is unnecessary in new
194 # code. ("hybrid" was replaced with "gfx" in early 2005...)
195 #
196 $self->{hybrid} = $self;
197 $self->{gfx} = $self;
198  
199 bless($self, $class);
200 }
201  
202 =item B<newpage> %options
203  
204 Ends the current page and creates a new one with the default graphics
205 state. If called without any arguments, the new page will be the same
206 size as the previous one.
207  
208 =cut
209  
210 sub newpage {
211 my $self = shift;
212 my %options = @_;
213 $self->{context}->show_page;
214 if (@_ > 0) {
215 $self->paper_size(%options);
216 $self->{surface}->set_size($self->{w}, $self->{h});
217 }
218 _setup_page_state($self);
219 return $self;
220 }
221  
222 =item B<write> [$file]
223  
224 Finishes the current PDF file and writes it to $file (either passed as
225 an argument here or to new()). No further drawing operations can be
226 performed.
227  
228 =cut
229  
230 sub write {
231 my $self = shift;
232 my $filename = shift || $self->{filename};
233 if (! defined $filename) {
234 croak "PDF::Cairo::write(): no output file in new() or write()";
235 }
236 # fall through to the standard write-on-close if it's not a stream
237 if ($self->{_is_stream}) {
238 $self->{surface}->flush;
239 $self->{surface}->finish;
240 open(my $Out, '>:raw', $filename)
241 or croak "PDF::Cairo::write($filename): $!";
242 print $Out $self->{_streamdata};
243 CORE::close($Out);
244 }
245 }
246  
247 =item B<pagebox>
248  
249 Creates a PDF::Cairo::Box with width and height set to the size
250 of the current page in points. Does not take into account any
251 coordinate transformations applied to the page.
252  
253 =cut
254  
255 sub pagebox {
256 my $self = shift;
257 return PDF::Cairo::Box->new(width => $self->{w}, height => $self->{h});
258 }
259  
260 =back
261  
262 =head2 Colors
263  
264 Colors can be specified by name as per X11's F<rgb.txt> file (see
265 L<PDF::Cairo::Colors> for a list), or by hex RGB value as #rgb,
266 #rrggbb, or #rrrrggggbbbb.
267  
268 =over 4
269  
270 =item B<fillcolor> $color
271  
272 Set the current fill color.
273  
274 =cut
275  
276 sub fillcolor {
277 my $self = shift;
278 my ($color) = @_;
279 $self->{_fill} = $color;
280 $self->{context}->set_source_rgb(_color($color));
281 return $self;
282 }
283  
284 =item B<strokecolor> $color
285  
286 Set the current stroke color.
287  
288 =cut
289  
290 sub strokecolor {
291 my $self = shift;
292 my ($color) = @_;
293 $self->{_stroke} = $color;
294 $self->{context}->set_source_rgb(_color($color));
295 return $self;
296 }
297  
298 =back
299  
300 =head2 Graphics State Parameters
301  
302 =over 4
303  
304 =item B<save>
305  
306 Saves the current graphics state.
307  
308 =cut
309  
310 sub save {
311 my $self = shift;
312 $self->{context}->save;
313 my $state = {};
314 foreach my $i (qw(_fill _stroke)) {
315 $state->{$i} = $self->{$i};
316 }
317 push(@{$self->{stack}}, $state);
318 return $self;
319 }
320  
321 =item B<restore>
322  
323 Restore the most recently saved graphics state.
324  
325 =cut
326  
327 sub restore {
328 my $self = shift;
329 $self->{context}->restore;
330 my $state = pop(@{$self->{stack}});
331 foreach my $i (qw(_fill _stroke)) {
332 $self->{$i} = $state->{$i};
333 }
334 return $self;
335 }
336  
337 =item B<linewidth> $width
338  
339 Set the current line width.
340  
341 =cut
342  
343 sub linewidth {
344 my $self = shift;
345 $self->{context}->set_line_width(@_);
346 return $self;
347 }
348  
349 =item B<linedash> [$on, $off, ...], $offset
350  
351 Set the line dash style to the array reference of on-off lengths,
352 starting the pattern at $on-off[$offset] (default $offset 0). If
353 called without any arguments, a solid line will be drawn.
354  
355 =cut
356  
357 sub linedash {
358 my $self = shift;
359 my @dashes = ();
360 my $offset = 0;
361 if (ref $_[0] eq "ARRAY") {
362 my $tmp = shift;
363 @dashes = @$tmp;
364 $offset = shift if @_;
365 }elsif (defined $_[0] and $_[0] =~ /^-/) {
366 # PDF::API2 long form
367 my %options = @_;
368 @dashes = @{$options{-pattern}}
369 if defined $options{-pattern};
370 $offset = $options{-shift}
371 if defined $options{-shift};
372 }else{
373 # PDF::API2 short form
374 @dashes = @_;
375 }
376 $self->{context}->set_dash($offset, @dashes);
377 return $self;
378 }
379  
380 =item B<linecap> $style
381  
382 Set the line cap style to 'butt' (default), 'round', or 'square'.
383  
384 =cut
385  
386 sub linecap {
387 my $self = shift;
388 my $style = shift;
389 $style = qw(butt line square)[$style]
390 if $style =~ /^[012]$/;
391 $self->{context}->set_line_cap($style);
392 return $self;
393 }
394  
395 =item B<linejoin> $style
396  
397 Set the line join style to 'miter' (default), 'round', or 'bevel'.
398  
399 =cut
400  
401 sub linejoin {
402 my $self = shift;
403 my $style = shift;
404 $style = qw(miter round bevel)[$style]
405 if $style =~ /^[012]$/;
406 $self->{context}->set_line_join($style);
407 return $self;
408 }
409  
410 =item B<miterlimit> $limit
411  
412 Set the miter limit; if the current line join style is set to 'miter',
413 the miter limit is used to determine whether the lines should be
414 joined with a bevel instead of a miter. Cairo divides the length of
415 the miter by the line width. If the result is greater than the miter
416 limit, the style is converted to a bevel.
417  
418 The default miter limit value is 10.0, which will convert joins with
419 interior angles less than 11 degrees to bevels instead of miters. For
420 reference, a miter limit of 2.0 makes the miter cutoff at 60 degrees,
421 and a miter limit of 1.414 makes the cutoff at 90 degrees.
422  
423 A miter limit for a desired angle can be computed as: miter limit =
424 1/sin(angle/2)
425  
426 =cut
427  
428 sub miterlimit {
429 my $self = shift;
430 $self->{context}->set_miter_limit(@_);
431 return $self;
432 }
433  
434 =item B<tolerance> $flatness
435  
436 Set the flatness tolerance (maximum distance in device pixels between
437 the mathematically correct path and a polygon approximation). Cairo's
438 default is 0.1, while PDF's is undefined and device-specific. Rarely
439 used, unless you know the characteristics of the device where you'll
440 eventually print your PDF file.
441  
442 =cut
443  
444 sub tolerance {
445 my $self = shift;
446 $self->{context}->set_tolerance(@_);
447 return $self;
448 }
449  
450 =back
451  
452 =head2 Coordinate Transformations
453  
454 =over 4
455  
456 =item B<translate> $Xdelta, $Ydelta
457  
458 Translate the origin of the coordinate system.
459  
460 =cut
461  
462 sub translate {
463 my $self = shift;
464 my ($dx, $dy) = @_;
465 $self->{context}->translate($dx, -1 * $dy);
466 return $self;
467 }
468  
469 =item B<rotate> $degrees
470  
471 Rotate the coordinate system counterclockwise. Use a negative
472 argument to rotate clockwise.
473  
474 =cut
475  
476 sub rotate {
477 my $self = shift;
478 my ($degrees) = @_;
479 $self->{context}->rotate(-1 * _rad($degrees));
480 return $self;
481 }
482  
483 =item B<scale> $Xscale, [$Yscale]
484  
485 Scale the coordinate system. If only one argument is passed, scale
486 both X and Y.
487  
488 =cut
489  
490 sub scale {
491 my $self = shift;
492 my ($sx, $sy) = @_;
493 $sy = $sx unless defined $sy;
494 $self->{context}->scale($sx, $sy);
495 return $self;
496 }
497  
498 =item B<skew> $sa, $sb
499  
500 Skews the coordinate system by $sa degrees (counter-clockwise) from
501 the x axis and $sb degrees (clockwise) from the y axis.
502  
503 =cut
504  
505 # As per https://www.cairographics.org/cookbook/matrix_transform/,
506 # an X-skew is:
507 # init(1,0,tan($sa_radians),1,0,0)
508 # a Y-skew is:
509 # init(1,tan($sb_radians),0,1,0,0)
510 # Multiply them together, then call transform() on the results.
511 #
512 sub skew {
513 my $self = shift;
514 my ($sa, $sb) = @_;
515 my $y_skew = Cairo::Matrix->init(
516 1, -1 * sin(_rad($sa)) / cos(_rad($sa)),
517 0, 1,
518 0, 0,
519 );
520 my $x_skew = Cairo::Matrix->init(
521 1, 0,
522 -1 * sin(_rad($sb)) / cos(_rad($sb)), 1,
523 0, 0,
524 );
525 $self->{context}->transform(Cairo::Matrix::multiply($y_skew, $x_skew));
526 return $self;
527 }
528  
529 =back
530  
531 =head2 Path Construction
532  
533 =over 4
534  
535 =item B<move> $x, $y
536  
537 Begin a new (sub)path at ($x, $y).
538  
539 =cut
540  
541 sub move {
542 my $self = shift;
543 my ($x, $y) = @_;
544 $self->{context}->move_to($x, -1 * $y);
545 return $self;
546 }
547  
548 =item B<rel_move> $dx, $dy
549  
550 Begin a new (sub)path offset from the current position by ($dx, $dy).
551  
552 =cut
553  
554 sub rel_move {
555 my $self = shift;
556 my ($dx, $dy) = @_;
557 $self->{context}->rel_move_to($dx, -1 * $dy);
558 return $self;
559 }
560  
561 =item B<line> $x, $y
562  
563 Adds a line to the path from the current point to ($x, $y).
564  
565 =cut
566  
567 sub line {
568 my $self = shift;
569 my ($x, $y) = @_;
570 $self->{context}->line_to($x, -1 * $y);
571 return $self;
572 }
573  
574 =item B<rel_line> $dx, $dy
575  
576 Adds a line to the path from the current point to a point that is
577 offset from the current point by ($dx,$dy).
578  
579 =cut
580  
581 sub rel_line {
582 my $self = shift;
583 my ($dx, $dy) = @_;
584 $self->{context}->rel_line_to($dx, -1 * $dy);
585 return $self;
586 }
587  
588 =item B<curve> $cx1, $cy1, $cx2, $cy2, $x, $y
589  
590 Extends the path in a curve from the current point to ($x, $y), using
591 the two specified points to create a cubic Bézier curve, and updates
592 the current position to be the new point.
593  
594 =cut
595  
596 sub curve {
597 my $self = shift;
598 my ($cx1, $cy1, $cx2, $cy2, $x, $y) = @_;
599 $self->{context}->curve_to($cx1, -1 * $cy1, $cx2, -1 * $cy2, $x, -1 * $y);
600 return $self;
601 }
602  
603 =item B<rel_curve> $dx1,$dy1, $dx2,$dy2, $dx3,$dy3
604  
605 Adds a cubic Bézier spline to the path from the current point to a
606 point offset from the current point by dx3 , dy3 ), using points
607 offset by (dx1 , dy1 ) and (dx2 , dy2 ) as the control points. After
608 this call the current point will be offset by (dx3 , dy3 ).
609  
610 =cut
611  
612 sub rel_curve {
613 my $self = shift;
614 my ($dx1, $dy1, $dx2, $dy2, $dx3, $dy3) = @_;
615 $self->{context}->rel_curve_to($dx1, -1 * $dy1, $dx2, -1 * $dy2,
616 $dx3, -1 * $dy3);
617 return $self;
618 }
619  
620 =item B<arc> $x, $y, $a, $b, $alpha, $beta, $move
621  
622 Extends the path along an arc of an ellipse centered at ($x, $y). The
623 major and minor axes of the ellipse are $a and $b, respectively, and
624 the arc moves from $alpha degrees to $beta degrees, counterclockwise.
625 The current position is then set to the endpoint of the arc.
626  
627 Set $move to a true value if this arc is the beginning of a new
628 path instead of the continuation of an existing path.
629  
630 =cut
631  
632 # Note: angles increase *clockwise* in Cairo space, but
633 # counter-clockwise in PDF space.
634 #
635 sub arc {
636 my $self = shift;
637 my ($x, $y, $a, $b, $alpha, $beta, $move) = @_;
638 $self->{context}->new_sub_path if $move;
639 my $tmp = $self->{context}->get_matrix;
640 $self->{context}->translate($x, -1 * $y);
641 $self->scale(1, $b/$a);
642 if ($alpha > $beta) {
643 $self->{context}->arc(0, 0, $a, -_rad($alpha), -_rad($beta));
644 }else{
645 $self->{context}->arc_negative(0, 0, $a, -_rad($alpha), -_rad($beta));
646 }
647 $self->{context}->set_matrix($tmp);
648 return $self;
649 }
650  
651 =item B<poly> $x1,$y1, $x2,$y2, ...
652  
653 Equivalent to move($x1, $y1) followed by a series of line($xn, $yn).
654  
655 =cut
656  
657 sub poly {
658 my $self = shift;
659 my ($x, $y) = splice(@_, 0, 2);
660 $self->move($x, $y);
661 while (@_) {
662 my ($x, $y) = splice(@_, 0, 2);
663 $self->line($x, $y)
664 if defined $y;
665 }
666 return $self;
667 }
668  
669 =item B<rel_poly> $dx1,$dy1, $dx2,$dy2, ...
670  
671 Equivalent to rel_move($dx1, $dy1) followed by a series of
672 rel_line($dxn, $dyn).
673  
674 =cut
675  
676 sub rel_poly {
677 my $self = shift;
678 my ($x, $y) = splice(@_, 0, 2);
679 $self->rel_move($x, $y);
680 while (@_) {
681 my ($x, $y) = splice(@_, 0, 2);
682 $self->rel_line($x, $y)
683 if defined $y;
684 }
685 return $self;
686 }
687  
688 =item B<close>
689  
690 Adds a line segment to the path from the current point to the
691 beginning of the current sub-path (the most recent point passed to
692 move()), and closes this sub-path.
693  
694 =cut
695  
696 sub close {
697 my $self = shift;
698 $self->{context}->close_path;
699 return $self;
700 }
701  
702 =back
703  
704 =head2 Closed Shapes
705  
706 =over 4
707  
708 =item B<circle> $x, $y, $radius
709  
710 Creates a circular path centered on ($x, $y) with radius $radius.
711  
712 =cut
713  
714 sub circle {
715 my $self = shift;
716 my ($x, $y, $radius) = @_;
717 $self->{context}->new_sub_path;
718 $self->{context}->arc($x, -1 * $y, $radius, 0, _rad(360));
719 $self->{context}->close_path;
720 return $self;
721 }
722  
723 =item B<ellipse> $x, $y, $xRadius, $yRadius
724  
725 Creates an elliptical path centered on ($x, $y), with major and
726 minor axes specified by $a and $b, respectively.
727  
728 =cut
729  
730 sub ellipse {
731 my $self = shift;
732 my ($x, $y, $a, $b) = @_;
733 my $tmp = $self->{context}->get_matrix;
734 $self->{context}->translate($x, -1 * $y);
735 $self->scale(1, $b/$a);
736 $self->{context}->new_sub_path;
737 $self->{context}->arc(0, 0, $a, 0, _rad(360));
738 $self->{context}->close_path;
739 $self->{context}->set_matrix($tmp);
740 return $self;
741 }
742  
743 =item B<polygon> $x, $y, $scale, $sides, %options
744  
745 =over 4
746  
747 =item edge => 1
748  
749 =item inradius => 1
750  
751 =back
752  
753 Creates a regular polygon path with $sides sides centered on ($x, $y)
754 with circumradius length $scale. The bottom edge of the polygon is
755 horizontal. If either the edge or inradius option is provided, set
756 that length to $scale instead of the circumradius.
757  
758 =cut
759  
760 sub polygon {
761 my $self = shift;
762 my ($cx, $cy, $scale, $sides, %options) = @_;
763 croak "PDF::Cairo::polygon: $sides < 3" if $sides < 3;
764 croak "PDF::Cairo::polygon: $sides must be an integer"
765 unless $sides == int($sides);
766 my $poly = regular_polygon($sides);
767 my @points = map(@$_, @{$poly->{points}});
768 $self->save;
769 $self->translate($cx, $cy);
770 if ($options{edge}) {
771 $self->scale($scale / $poly->{edge});
772 }elsif ($options{inradius}) {
773 $self->scale($scale / $poly->{inradius});
774 }else{
775 # circumradius
776 $self->scale($scale);
777 }
778 $self->poly(@points);
779 $self->close;
780 $self->restore;
781 return $self;
782 }
783  
784 =item B<rect> $x, $y, $width, $height
785  
786 Draws a rectangle starting at ($x, $y) with $width and $height.
787 Can also pass a single argument containing an array reference.
788  
789 =cut
790  
791 sub rect {
792 my $self = shift;
793 my ($x, $y, $w, $h) = @_;
794 ($x, $y, $w, $h) = @$x if ref $x eq 'ARRAY';
795 $self->{context}->rectangle($x, -1 * $y, $w, -1 * $h);
796 return $self;
797 }
798  
799 =item B<rel_rect> $dx, $dy, $width, $height
800  
801 Draws a rectangle offset from the current point by ($dx, $dy), with
802 $width and $height. Can also pass a single argument containing an
803 array reference.
804  
805 =cut
806  
807 sub rel_rect {
808 my $self = shift;
809 my ($dx, $dy, $w, $h) = @_;
810 ($dx, $dy, $w, $h) = @$dx if ref $dx eq 'ARRAY';
811 if ($self->{context}->has_current_point) {
812 my $tmp = $self->{context}->get_matrix;
813 my ($x, $y) = $self->{context}->get_current_point;
814 $self->translate($x, - $y);
815 $self->rect($dx, $dy, $w, $h);
816 $self->{context}->set_matrix($tmp);
817 }else{
818 croak "PDF::Cairo::rel_rect: no current point";
819 }
820 return $self;
821 }
822  
823 =back
824  
825 =head2 Path Painting
826  
827 =over 4
828  
829 =item B<fill> [evenodd => 1], [preserve => 1]
830  
831 Fills the current path with the current fillcolor. The path is cleared
832 unless you pass the preserve option. If a non-zero argument is
833 provided, use the even-odd rule instead of the default non-zero
834 winding rule.
835  
836 =cut
837  
838 sub fill {
839 my $self = shift;
840 my %options = @_;
841 $options{evenodd} = $_[0] if @_ == 1;
842 $self->{context}->set_source_rgb(_color($self->{_fill}));
843 my $current_fill = $self->{context}->get_fill_rule;
844 $self->{context}->set_fill_rule('even_odd') if $options{evenodd};
845 if ($options{preserve}) {
846 $self->{context}->fill_preserve;
847 }else{
848 $self->{context}->fill;
849 }
850 $self->{context}->set_fill_rule($current_fill) if $options{evenodd};
851 $self->{_dirtypage} = 1;
852 return $self;
853 }
854  
855 =item B<stroke> [preserve => 1]
856  
857 Strokes the current path with the current linewidth and strokecolor.
858 The path is cleared unless you pass the preserve option.
859  
860 =cut
861  
862 sub stroke {
863 my $self = shift;
864 my %options = @_;
865 $self->{context}->set_source_rgb(_color($self->{_stroke}));
866 if ($options{preserve}) {
867 $self->{context}->stroke_preserve;
868 }else{
869 $self->{context}->stroke;
870 }
871 $self->{_dirtypage} = 1;
872 return $self;
873 }
874  
875 =item B<fillstroke> [evenodd => 1]
876  
877 Fills and then strokes the current path, exactly as if fill() and
878 stroke() were called in order without clearing the path in between. If
879 a non-zero argument is provided, use the even-odd rule instead of the
880 default non-zero winding rule.
881  
882 =cut
883  
884 sub fillstroke {
885 my $self = shift;
886 my %options = @_;
887 $options{evenodd} = $_[0] if @_ == 1;
888 $self->{context}->set_source_rgb(_color($self->{_fill}));
889 my $current_fill = $self->{context}->get_fill_rule;
890 $self->{context}->set_fill_rule('even_odd') if $options{evenodd};
891 $self->{context}->fill_preserve;
892 $self->{context}->set_fill_rule($current_fill) if $options{evenodd};
893 $self->{context}->set_source_rgb(_color($self->{_stroke}));
894 $self->{context}->stroke;
895 $self->{_dirtypage} = 1;
896 return $self;
897 }
898  
899 =item B<strokefill> [evenodd => 1]
900  
901 Strokes and then fills the current path, exactly as if stroke() and
902 fill() were called in order without clearing the path in between. If
903 a non-zero argument is provided, use the even-odd rule instead of the
904 default non-zero winding rule.
905  
906 =cut
907  
908 sub strokefill {
909 my $self = shift;
910 my %options = @_;
911 $options{evenodd} = $_[0] if @_ == 1;
912 $self->{context}->set_source_rgb(_color($self->{_stroke}));
913 $self->{context}->stroke_preserve;
914 $self->{context}->set_source_rgb(_color($self->{_fill}));
915 my $current_fill = $self->{context}->get_fill_rule;
916 $self->{context}->set_fill_rule('even_odd') if $options{evenodd};
917 $self->{context}->fill;
918 $self->{context}->set_fill_rule($current_fill) if $options{evenodd};
919 $self->{_dirtypage} = 1;
920 return $self;
921 }
922  
923 =item B<clip> [evenodd => 1], [preserve => 1]
924  
925 Intersects the current path with the current clipping path. The path
926 is cleared unless you pass the preserve option. If the evenodd
927 argument is passed, use the even-odd rule instead of the default
928 non-zero winding rule.
929  
930 Note that this differs from PDF::API2, where you must call endpath()
931 to clear the path after clip().
932  
933 =cut
934  
935 sub clip {
936 my $self = shift;
937 my %options = @_;
938 $options{evenodd} = $_[0] if @_ == 1;
939 my $current_fill = $self->{context}->get_fill_rule;
940 $self->{context}->set_fill_rule('even_odd') if $options{evenodd};
941 if ($options{preserve}) {
942 $self->{context}->clip_preserve;
943 }else{
944 $self->{context}->clip;
945 }
946 $self->{context}->set_fill_rule($current_fill) if $options{evenodd};
947 $self->{_dirtypage} = 1;
948 return $self;
949 }
950  
951 =back
952  
953 =head2 Text
954  
955 =over 4
956  
957 =item B<loadfont> $font, [$index|$metrics]
958  
959 Load $font from disk with FreeType, returning a PDF::Cairo::Font
960 object. If the file is not found in the current directory, the font
961 path will be searched. If $font doesn't look like a file name, it will
962 be matched against the PDF::API2 'core' and 'cjk' font names, and
963 Fontconfig will be used to find something compatible.
964  
965 For multi-font container formats (TTC, OTC, DFONT), $index can be
966 supplied to select one of the other fonts; for PostScript PFB fonts,
967 the location of an AFM metrics file can be supplied, or it will search
968 the font path to find one with a matching name (case-insensitive).
969  
970 =cut
971  
972 sub loadfont {
973 my $self = shift;
974 my $face = join(",", @_);
975 return PDF::Cairo::Font->new($self, $face);
976 }
977  
978 =item B<setfont> $fontref, $size
979  
980 Set the current font and size.
981  
982 =cut
983  
984 sub setfont {
985 my $self = shift;
986 my ($font, $size) = @_;
987 $self->{context}->set_font_face($font->{face})
988 if ref $font and $font->{face} ne $self->{context}->get_font_face;
989 $self->{context}->set_font_size($size);
990 return $self;
991 }
992  
993 =item B<setfontsize> $size
994  
995 Set the size of the current font.
996  
997 =cut
998  
999 sub setfontsize {
1000 my $self = shift;
1001 my $size = shift;
1002 $self->{context}->set_font_size($size);
1003 return $self;
1004 }
1005  
1006 =item B<print> $text, %options
1007  
1008 =over 4
1009  
1010 =item align => 'left|right|center'
1011  
1012 =item valign => 'baseline|top|center'
1013  
1014 =item shift => $vertical_shift
1015  
1016 =back
1017  
1018 Display text at current position, with current font and fillcolor. If
1019 the first argument is a font reference, the PDF::API2::Lite
1020 compatibility version of print() will be used instead.
1021  
1022 The current position will be moved to the end of the displayed text.
1023 Any vertical shift will not affect the baseline of subsequent calls
1024 to print().
1025  
1026 =cut
1027  
1028 sub print {
1029 my $self = shift;
1030 if (ref $_[0]) {
1031 $self->_api2_print(@_);
1032 }else{
1033 my ($text, %options) = @_;
1034 my $extents = $self->{context}->text_extents($text);
1035 my $width = $extents->{width};
1036 my $height = $extents->{height};
1037 my ($dx, $dy) = (0, 0);
1038 $options{align} ||= "left";
1039 if ($options{align} eq "center") {
1040 $dx -= $width / 2;
1041 }elsif ($options{align} eq "right") {
1042 $dx -= $width;
1043 }
1044 # TODO: add "bottom", distinct from default baseline
1045 $options{valign} ||= "baseline";
1046 if ($options{valign} eq "center") {
1047 $dy += $height / 2;
1048 }elsif ($options{valign} eq "top") {
1049 $dy += $height;
1050 }
1051 if ($dx or $dy) {
1052 my ($x, $y) = $self->{context}->get_current_point;
1053 $self->{context}->move_to($x + $dx, $y + $dy);
1054 }
1055 $self->{context}->set_source_rgb(_color($self->{_fill}));
1056 $self->rel_move(0, $options{shift})
1057 if $options{shift};
1058 $self->{context}->show_text($text);
1059 $self->rel_move(0, -$options{shift})
1060 if $options{shift};
1061 # note this leaves the current point offset by the alignment
1062 # which means calling print() again without moving first
1063 # will match the baseline. I think this is a feature.
1064 }
1065 $self->{_dirtypage} = 1;
1066 return $self;
1067 }
1068  
1069 =item B<textpath> $text
1070  
1071 Add the outlines of the glyphs in $text to the current path, using
1072 the current font and size.
1073  
1074 =cut
1075  
1076 sub textpath {
1077 my $self = shift;
1078 my $text = shift;
1079 $self->{context}->text_path($text);
1080 return $self;
1081 }
1082  
1083 =back
1084  
1085 =head2 Raster Images
1086  
1087 =over 4
1088  
1089 =item B<loadimage> $file
1090  
1091 Load a PNG-format image from $file. Returns a Cairo image surface that
1092 can be placed any number of times with showimage(); height() and
1093 width() methods are available to determine appropriate scaling values.
1094  
1095 If L<ImageMagick|https://imagemagick.org/>'s F<convert> command is
1096 available, it will be used to convert other image formats into PNG.
1097  
1098 =cut
1099  
1100 sub loadimage {
1101 my $self = shift;
1102 my $file = shift;
1103 if ($HAS_IMAGEMAGICK) {
1104 my $fh;
1105 my @convert = qw(convert -density 72);
1106 if (!open($fh, '-|:raw', @convert, $file, 'png:-')) {
1107 croak "loadimage($file): $!\n";
1108 }
1109 my $result = Cairo::ImageSurface->create_from_png_stream(
1110 sub {
1111 my ($fh, $length) = @_;
1112 my $buffer;
1113 read($fh, $buffer, $length);
1114 return $buffer;
1115 }, $fh,
1116 );
1117 CORE::close($fh);
1118 return $result;
1119 }else{
1120 my $result = Cairo::ImageSurface->create_from_png($file);
1121 croak "loadimage($file) failed (not a PNG and convert not available?)"
1122 unless $result->status eq 'success';
1123 return $result;
1124 }
1125 }
1126  
1127 =item B<showimage> $image, $x, $y, %options
1128  
1129 =over 4
1130  
1131 =item align => 'left|center|right'
1132  
1133 =item valign => 'top|center|bottom'
1134  
1135 =item center => 1
1136  
1137 =item scale => $scale
1138  
1139 =item size => [ $width, $height ]
1140  
1141 =item x_scale => $scale
1142  
1143 =item y_scale => $scale
1144  
1145 =item rotate => $degrees
1146  
1147 =back
1148  
1149 Display $image with its lower-left corner at ($x, $y), scaled at 100%
1150 in the current user coordinate unless one of the scaling options is
1151 supplied.
1152  
1153 =cut
1154  
1155 sub showimage {
1156 my $self = shift;
1157 my $image_surface = shift;
1158 my $x = shift;
1159 my $y = shift;
1160 my %options = @_;
1161 my ($x_scale, $y_scale) = (1, 1);
1162 if ($options{scale}) {
1163 $x_scale = $options{scale};
1164 $y_scale = $options{scale};
1165 }
1166 if ($options{x_scale}) {
1167 $x_scale = $options{x_scale};
1168 }
1169 if ($options{y_scale}) {
1170 $y_scale = $options{y_scale};
1171 }
1172 if ($options{size}) {
1173 my ($w, $h) = @{$options{size}};
1174 $x_scale = $w / $image_surface->get_width;
1175 $y_scale = $h / $image_surface->get_height;
1176 }
1177 my $height = $image_surface->get_height * $y_scale;
1178 my $width = $image_surface->get_width * $x_scale;
1179 $self->save;
1180 $self->translate($x, $y + $height);
1181  
1182 if (defined $options{rotate}) {
1183 # calculate the rotated position of lower-left corner and
1184 # translate the origin so that the rotation comes from there.
1185 my $a = -1 * _rad($options{rotate});
1186 $self->translate($height * sin($a), $height * (cos($a) - 1));
1187 $self->rotate($options{rotate});
1188 }
1189  
1190 # align image to other than bottom-left
1191 # this must happen after rotation but before scaling
1192 my ($tx, $ty) = (0, 0);
1193 if ($options{center}) {
1194 $options{align} = "center";
1195 $options{valign} = "center";
1196 }
1197 $options{align} ||= "left";
1198 if ($options{align} eq "center") {
1199 $tx = - $width / 2;
1200 }elsif ($options{align} eq "right") {
1201 $tx = - $width;
1202 }
1203 $options{valign} ||= "bottom";
1204 if ($options{valign} eq "center") {
1205 $ty = $height / 2;
1206 }elsif ($options{valign} eq "top") {
1207 $ty = $height;
1208 }
1209 if ($tx or $ty) {
1210 my ($x, $y) = $self->{context}->get_current_point;
1211 $self->{context}->translate($tx, $ty);
1212 }
1213  
1214 if ($x_scale != 1 or $y_scale != 1) {
1215 $self->scale($x_scale, $y_scale);
1216 }
1217 $self->{context}->set_source_surface($image_surface, 0, 0);
1218 $self->{context}->paint;
1219 $self->restore;
1220 return $self;
1221 }
1222  
1223 =back
1224  
1225 =head2 Advanced and Experimental
1226  
1227 =over 4
1228  
1229 =item B<loadsvg> $file|$string
1230  
1231 Create an object with recording() containing an SVG image rendered
1232 with L<Image::CairoSVG>, with the lower-left corner at (0,0). It can
1233 be rendered with place() as many times as you want. height() and
1234 width() methods are available to determine appropriate scaling values.
1235  
1236 Note that Image::CairoSVG only supports path operators, and ignores
1237 filters, fonts, and text, so many complex SVG files will not render
1238 as expected.
1239  
1240 =cut
1241  
1242 # renders the SVG *twice*; first to find its bounding box, then
1243 # with the origin translated vertically so it matches the PDF
1244 # coordinate system.
1245 #
1246 sub loadsvg {
1247 my $class = shift;
1248 my $svg = shift;
1249 my $rectmp = PDF::Cairo->recording(_unlimited => 1);
1250 my $image = Image::CairoSVG->new (context => $rectmp->{context});
1251 $image->render($svg);
1252 my @ink = $rectmp->{surface}->ink_extents;
1253  
1254 my $recording = PDF::Cairo->recording(width => $ink[2], height => $ink[3]);
1255 $recording->translate(0, $ink[3]);
1256 $image = Image::CairoSVG->new (context => $recording->{context});
1257 $image->render($svg);
1258 $recording->{surface}->flush;
1259 return $recording;
1260 }
1261  
1262 =item B<path> ['move|line|curve|close', [$x, $y, ...], ...]
1263  
1264 Appends an array of move/line/curve/close operations to the current
1265 path. This is done with Cairo's append_path() method, so it's more
1266 efficient than calling each method one-by-one.
1267  
1268 If no arguments are passed, returns the current path in this
1269 format, and then clears the path.
1270  
1271 =cut
1272  
1273 sub path {
1274 my $self = shift;
1275 if (@_) {
1276 $self->_appendpath(@_);
1277 }else{
1278 $self->_getpath;
1279 }
1280 }
1281  
1282 sub _appendpath {
1283 my $self = shift;
1284 my @path;
1285 while (@_) {
1286 my $op = shift;
1287 my $val = shift;
1288 if ($op eq 'move') {
1289 my ($x, $y) = @$val;
1290 push(@path, { type => 'move-to', points => [ [$x, -$y] ] });
1291 }elsif ($op eq 'line') {
1292 my ($x, $y) = @$val;
1293 push(@path, { type => 'line-to', points => [ [$x, -$y] ] });
1294 }elsif ($op eq 'curve') {
1295 my ($cx1, $cy1, $cx2, $cy2, $x, $y) = @$val;
1296 push(@path, { type => 'curve-to', points => [
1297 [$cx1, -$cy1],
1298 [$cx2, -$cy2],
1299 [$x, -$y],
1300 ]});
1301 }elsif ($op eq 'close') {
1302 push(@path, { type => 'close-path', points => [] });
1303 }else{
1304 croak "PDF::Cairo::_appendpath: unknown operator '$op'";
1305 }
1306 }
1307 $self->{context}->append_path(\@path);
1308 return $self;
1309 }
1310  
1311 sub _getpath {
1312 my $self = shift;
1313 my @path;
1314 foreach my $op (@{$self->{context}->copy_path}) {
1315 my $key = $op->{type};
1316 my $val = $op->{points};
1317 $key =~ s/-.*$//;
1318 my @points;
1319 foreach my $pt (@$val) {
1320 my ($x, $y) = @$pt;
1321 push(@points, $x, - $y);
1322 }
1323 push(@path, $key, \@points);
1324 }
1325 $self->{context}->new_path;
1326 return @path;
1327 }
1328  
1329 =item B<place> $recording, $x,$y, %options
1330  
1331 =over 4
1332  
1333 =item clip => [ $width, $height]
1334  
1335 =item dx => $offset_x
1336  
1337 =item dy => $offset_y
1338  
1339 =item align => 'left|center|right'
1340  
1341 =item valign => 'top|center|bottom'
1342  
1343 =item center => 1
1344  
1345 =item scale => $scale
1346  
1347 =item size => [ $width, $height ]
1348  
1349 =item x_scale => $scale
1350  
1351 =item y_scale => $scale
1352  
1353 =item rotate => $degrees
1354  
1355 =back
1356  
1357 Places the recording object $recording with its lower-left corner at
1358 ($x,$y). If the clip argument is provided, the recording is clipped
1359 to that width/height before rendering. If $dx or $dy is provided, the
1360 recording will be offset by those amounts before rendering. This can
1361 be used to do things like tile a large image across multiple pages.
1362  
1363 =cut
1364  
1365 sub place {
1366 my $self = shift;
1367 croak "PDF::Cairo::place: first argument must be a recording/svg/image"
1368 unless defined $_[0];
1369 # pass raster images to showimage
1370 return $self->showimage(@_)
1371 if ref $_[0] eq 'Cairo::ImageSurface';
1372 my $recording = shift;
1373 croak "PDF:Cairo::place: first argument must be a recording object"
1374 unless ref $recording->{surface} eq 'Cairo::RecordingSurface';
1375 my $width = $recording->{w};
1376 my $height = $recording->{h};
1377 my $x = shift || 0;
1378 my $y = shift || 0;
1379 my %options = @_;
1380  
1381 my $dx = defined $options{dx} ? $options{dx} : 0;
1382 my $dy = defined $options{dy} ? $options{dy} : 0;
1383 my ($x_scale, $y_scale) = (1, 1);
1384 if ($options{scale}) {
1385 $x_scale = $options{scale};
1386 $y_scale = $options{scale};
1387 }
1388 if ($options{x_scale}) {
1389 $x_scale = $options{x_scale};
1390 }
1391 if ($options{y_scale}) {
1392 $y_scale = $options{y_scale};
1393 }
1394 if ($options{size}) {
1395 my ($w, $h) = @{$options{size}};
1396 $x_scale = $w / $width;
1397 $y_scale = $h / $height;
1398 }
1399 $self->save;
1400 $self->translate($x, $y) if $x or $y;
1401 if (defined $options{rotate}) {
1402 $self->rotate($options{rotate});
1403 }
1404  
1405 # align image to other than bottom-left
1406 # this must happen after rotation but before scaling
1407 my ($tx, $ty) = (0, 0);
1408 if ($options{center}) {
1409 $options{align} = "center";
1410 $options{valign} = "center";
1411 }
1412 $options{align} ||= "left";
1413 if ($options{align} eq "center") {
1414 $tx = - $width * $x_scale / 2;
1415 }elsif ($options{align} eq "right") {
1416 $tx = - $width * $x_scale;
1417 }
1418 $options{valign} ||= "bottom";
1419 if ($options{valign} eq "center") {
1420 $ty = $height * $y_scale / 2;
1421 }elsif ($options{valign} eq "top") {
1422 $ty = $height * $y_scale;
1423 }
1424 if ($tx or $ty) {
1425 my ($x, $y) = $self->{context}->get_current_point;
1426 $self->{context}->translate($tx, $ty);
1427 }
1428  
1429 if ($x_scale != 1 or $y_scale != 1) {
1430 $self->scale($x_scale, $y_scale);
1431 }
1432 if (defined $options{clip}) {
1433 $self->rect(0, 0, @{$options{clip}});
1434 $self->clip;
1435 }
1436 $recording->{surface}->flush;
1437 $self->{context}->set_source_surface($recording->{surface},
1438 -$dx, -$recording->{h} + $dy);
1439 $self->{context}->paint;
1440 $self->restore;
1441 return $self;
1442 }
1443  
1444 =item B<recording> %options
1445  
1446 =over 4
1447  
1448 =item paper => $paper_size
1449  
1450 =item height => $Ypts
1451  
1452 =item width => $Xpts
1453  
1454 =item wide|landscape => 1
1455  
1456 =item tall|portrait => 1
1457  
1458 =back
1459  
1460 Creates a new PDF::Cairo recording object. You can draw on it
1461 normally, but can only access the results with place(). Options are
1462 the same as new(). height() and width() methods are available to
1463 determine appropriate scaling values.
1464  
1465 =cut
1466  
1467 # Create a recording surface.
1468 #
1469 sub recording {
1470 my $class = shift;
1471 my %options = @_;
1472 return PDF::Cairo->new(_recording => 1, %options);
1473 }
1474  
1475 #only really useful for recording/svg surfaces, so otherwise not documented
1476 #
1477 sub height {
1478 my $self = shift;
1479 return $self->{h};
1480 }
1481 sub width {
1482 my $self = shift;
1483 return $self->{w};
1484 }
1485  
1486 =back
1487  
1488 =head2 Utility Functions
1489  
1490 These are imported from L<PDF::Cairo::Util> so you don't have to
1491 explicitly use that module in every script.
1492  
1493 =over 4
1494  
1495 =item B<cm> $centimeters
1496  
1497 Converts the arguments from centimeters to points. Importable.
1498  
1499 =cut
1500  
1501 sub cm {
1502 return PDF::Cairo::Util::cm(@_);
1503 }
1504  
1505 =item B<in> $inches
1506  
1507 Converts the arguments from inches to points. Importable.
1508  
1509 =cut
1510  
1511 sub in {
1512 return PDF::Cairo::Util::in(@_);
1513 }
1514  
1515 =item B<mm> $millimeters
1516  
1517 Converts the arguments from millimeters to points. Importable.
1518  
1519 =cut
1520  
1521 sub mm {
1522 return PDF::Cairo::Util::mm(@_);
1523 }
1524  
1525 =item B<paper_size> %options
1526  
1527 =over 4
1528  
1529 =item paper => $paper_size
1530  
1531 =item wide|landscape => 1
1532  
1533 =item tall|portrait => 1
1534  
1535 =back
1536  
1537 Return size in points of a paper type. The default is "US Letter"
1538 (8.5x11 inches). The wide/tall options can be used to ensure that the
1539 orientation of the page is as expected. Importable.
1540  
1541 The supported paper sizes are listed in L<PDF::Cairo::Papers>.
1542  
1543 =cut
1544  
1545 # can either be called as a method or a function;
1546 # returns ($width, $height) in points
1547 #
1548 sub paper_size {
1549 return PDF::Cairo::Util::paper_size(@_);
1550 }
1551  
1552 =item B<regular_polygon> $sides
1553  
1554 Calculate the vertices of a regular polygon with $sides sides with
1555 radius 1, along with the relative lengths of the inradius and edge.
1556  
1557 Returns a hashref:
1558  
1559 {
1560 points => [ [$x0, $y0], ... ],
1561 edge => $edge_length,
1562 inradius => $inradius_length,
1563 radius => 1,
1564 }
1565  
1566 Calling the polygon($cx, $cy, $radius, $sides) method is equivalent to:
1567  
1568 $poly = regular_polygon($sides);
1569 @points = map(@$_, @{$poly->{points}});
1570 $pdf->save;
1571 $pdf->translate($cx, $cy);
1572 $pdf->scale($radius);
1573 $pdf->poly(@points);
1574 $pdf->close;
1575 $pdf->restore;
1576  
1577 =cut
1578  
1579 sub regular_polygon {
1580 return PDF::Cairo::Util::regular_polygon(@_);
1581 }
1582  
1583 =back
1584  
1585 =head2 PDF::API2 Compatibility
1586  
1587 =over 4
1588  
1589 =item B<addFontDirs> $directory, ...
1590  
1591 Append one or more directories to the font search path. Returns
1592 the current font path.
1593  
1594 =cut
1595  
1596 sub addFontDirs {
1597 shift if ref $_[0]; # not a method call, but allow the error
1598 PDF::Cairo::Font::append_font_path(@_);
1599 return PDF::Cairo::Font::get_font_path();
1600 }
1601  
1602 =item B<clip> $use_even_odd
1603  
1604 Additional way to specify even-odd fill rule for clip().
1605  
1606 =item B<cjkfont> $font
1607  
1608 Load something vaguely appropriate for the requested PDF::API2
1609 CJK font name. See PDF::Cairo::Font for recommended alternatives.
1610  
1611 =cut
1612  
1613 sub cjkfont {
1614 loadfont(@_);
1615 }
1616  
1617 =item B<corefont> $fontname
1618  
1619 Load the closest match to a PDF::API2 core font, as described in
1620 PDF::Cairo::Font.
1621  
1622 =cut
1623  
1624 sub corefont {
1625 loadfont(@_);
1626 }
1627  
1628 =item B<endpath>
1629  
1630 Ends current (sub)path without close(). Generally only used after
1631 clip(), so it's effectively a no-op in PDF::Cairo.
1632  
1633 =cut
1634  
1635 sub endpath {
1636 my $self = shift;
1637 $self->{context}->new_path;
1638 return $self;
1639 }
1640  
1641 =item B<fill> $use_even_odd
1642  
1643 Additional way to specify even-odd fill rule for fill().
1644  
1645 =item B<fillstroke> $use_even_odd
1646  
1647 Additional way to specify even-odd fill rule for fillstroke().
1648  
1649 =item B<image> $image, $x, $y, ($width, $height) | [$scale]
1650  
1651 Wrapper for showimage().
1652  
1653 =cut
1654  
1655 sub image {
1656 my $self = shift;
1657 my $image_surface = shift;
1658 my $x = shift;
1659 my $y = shift;
1660 if (defined $_[1]) {
1661 $self->showimage($image_surface, $x, $y, size => [ @_ ]);
1662 }elsif (defined $_[0]) {
1663 $self->showimage($image_surface, $x, $y, scale => $_[0]);
1664 }else{
1665 $self->showimage($image_surface, $x, $y)
1666 }
1667 return $self;
1668 }
1669  
1670 =item B<image_gif> $file
1671  
1672 Alias for loadimage(); requires ImageMagick F<convert> program.
1673  
1674 =cut
1675  
1676 sub image_gif {
1677 loadimage(@_);
1678 }
1679  
1680 =item B<image_jpg> $file
1681  
1682 Alias for loadimage(); requires ImageMagick F<convert> program.
1683  
1684 =cut
1685  
1686 sub image_jpg {
1687 loadimage(@_);
1688 }
1689  
1690 =item B<image_png> $file
1691  
1692 Alias for loadimage().
1693  
1694 =cut
1695  
1696 sub image_png {
1697 loadimage(@_);
1698 }
1699  
1700 =item B<image_pnm> $file
1701  
1702 Alias for loadimage(); requires ImageMagick F<convert> program.
1703  
1704 =cut
1705  
1706 sub image_pnm {
1707 loadimage(@_);
1708 }
1709  
1710 =item B<image_tiff> $file
1711  
1712 Alias for loadimage(); requires ImageMagick F<convert> program.
1713  
1714 =cut
1715  
1716 sub image_tiff {
1717 loadimage(@_);
1718 }
1719  
1720 =item B<linedash> $length
1721  
1722 =item B<linedash> $dash1, $gap1, ...
1723  
1724 =item B<linedash> -pattern => [$dash1, $gap1, ...], -shift => $offset
1725  
1726 Additional ways to pass arguments to linedash().
1727  
1728 =item B<page> [$width, $height]
1729  
1730 Emulates the behavior of PDF::API2::Lite's page() method, which starts
1731 a new page, defaulting to the size of the previous page if there was
1732 one. Note that this does not accept the four-argument form with the
1733 coordinates of the lower-left and upper-right corners.
1734  
1735 =cut
1736  
1737 sub page {
1738 my $self = shift;
1739 my ($w, $h) = @_;
1740 if ($self->{_dirtypage}) {
1741 $self->newpage(width => $w, height => $h);
1742 }else{
1743 $self->paper_size(width => $w, height => $h);
1744 $self->{surface}->set_size($self->{w}, $self->{h});
1745 _setup_page_state($self);
1746 }
1747 return $self;
1748 }
1749  
1750 =item B<print> $font, $size, $x, $y, $rotation, $justification, @text
1751  
1752 Sadly necessary, since I use it all the time with PDF::API2::Lite.
1753  
1754 =cut
1755  
1756 sub _api2_print {
1757 my $self = shift;
1758 my ($font, $size, $x, $y, $rotation, $justification, @text) = @_;
1759 croak "PDF::Cairo::print: requires text argument"
1760 unless defined $text[0];
1761 my $text = join(' ', @text);
1762 $self->{context}->set_font_face($font->{face});
1763 $self->{context}->set_font_size($size);
1764 my $width = $self->{context}->text_extents($text)->{width};
1765 if ($justification == 1) {
1766 $x -= $width / 2;
1767 }elsif ($justification == 2) {
1768 $x -= $width;
1769 }
1770 $self->move($x, $y);
1771 my $tmp = $self->{context}->get_matrix;
1772 $self->rotate($rotation);
1773 $self->{context}->set_source_rgb(_color($self->{_fill}));
1774 $self->{context}->show_text($text);
1775 $self->{context}->set_matrix($tmp);
1776 $self->{_dirtypage} = 1;
1777 return $self;
1778 }
1779  
1780 =item B<psfont> $font
1781  
1782 Load a Type 1 font from disk using FreeType. If a matching
1783 AFM file is found in the font path, it will also be loaded.
1784  
1785 =cut
1786  
1787 sub psfont {
1788 loadfont(@_);
1789 }
1790  
1791 =item B<rectxy> $x1, $x1, $x2, $y2
1792  
1793 Draw a rectangle with opposite corners at ($x1, $y1) and ($x2, $y2).
1794  
1795 =cut
1796  
1797 sub rectxy {
1798 my $self = shift;
1799 my ($x1, $y1, $x2, $y2) = @_;
1800 $self->rect($x1, $y1, $x2-$x1, $y2-$y1);
1801 return $self;
1802 }
1803  
1804 =item B<restorestate>
1805  
1806 Alias for restore().
1807  
1808 =cut
1809  
1810 sub restorestate {
1811 restore(@_);
1812 }
1813  
1814 =item B<saveas> $file
1815  
1816 Finishes the current PDF file and saves it to $file. No further
1817 drawing operations can be performed.
1818  
1819 =cut
1820  
1821 sub saveas {
1822 my $self = shift;
1823 my $filename = shift;
1824 if ($self->{_is_stream}) {
1825 $self->{surface}->flush;
1826 $self->{surface}->finish;
1827 open(my $Out, '>:raw', $filename)
1828 or die "$0: PDF::Cairo::saveas($filename): $!\n";
1829 print $Out $self->{_streamdata};
1830 CORE::close($Out);
1831 }else{
1832 croak "saveas() only works if you didn't set a filename in new()\n";
1833 }
1834 }
1835  
1836 =item B<savestate>
1837  
1838 Alias for save().
1839  
1840 =cut
1841  
1842 sub savestate {
1843 save(@_);
1844 }
1845  
1846 =item B<stringify>
1847  
1848 Finishes the current PDF file and returns it as a scalar. No further
1849 drawing operations can be performed.
1850  
1851 =cut
1852  
1853 sub stringify {
1854 my $self = shift;
1855 if ($self->{_is_stream}) {
1856 $self->{surface}->flush;
1857 $self->{surface}->finish;
1858 return $self->{_streamdata};
1859 }else{
1860 croak "stringify() only works if you didn't set a filename in new()\n";
1861 }
1862 }
1863  
1864 =item B<transform> %options
1865  
1866 =over 4
1867  
1868 =item -translate => [$x, $y]
1869  
1870 =item -rotate => $degrees
1871  
1872 =item -scale => [$sx, $sy]
1873  
1874 =item -skew => [$sa, $sb]
1875  
1876 =back
1877  
1878 Perform multiple coordinate transforms at once, in PDF-canonical
1879 order.
1880  
1881 =cut
1882  
1883 # always thought it was odd that PDF::API2::Lite didn't have the
1884 # individual transformations, even though PDF::API2::Content does.
1885 #
1886 sub transform {
1887 my $self = shift;
1888 my %options = @_;
1889 $self->translate(@{$options{-translate}})
1890 if $options{-translate};
1891 $self->rotate(@{$options{-rotate}})
1892 if $options{-rotate};
1893 $self->scale(@{$options{-scale}})
1894 if $options{-scale};
1895 $self->skew(@{$options{-skew}})
1896 if $options{-skew};
1897 return $self;
1898 }
1899  
1900 =item B<ttfont> $font
1901  
1902 Load a TrueType/OpenType font from disk using FreeType.
1903  
1904 =cut
1905  
1906 sub ttfont {
1907 loadfont(@_);
1908 }
1909  
1910 =back
1911  
1912 =head2 PDF::API2::Lite Text Compatibility
1913  
1914 These methods should not be used in new code, and are present solely
1915 to simplify converting existing scripts that use L<PDF::API2::Lite>.
1916 Use L<PDF::Cairo::Layout> instead. Honestly, in over 15 years of using
1917 PDF::API2::Lite, I never once used these methods.
1918  
1919 Note that this is the I<Lite> version, which exposes only a subset
1920 of the functionality in L<PDF::API2::Content>.
1921  
1922 =over 4
1923  
1924 =item B<textstart>
1925  
1926 Starts a block of text with the baseline set to (0, 0). You must
1927 translate the origin to get the text to appear anywhere else.
1928  
1929 =cut
1930  
1931 sub textstart {
1932 my $self = shift;
1933 $self->{_api2text} = {
1934 lead => 0,
1935 lines => 0,
1936 first => 1,
1937 };
1938 return $self;
1939 }
1940  
1941 =item B<textfont> $font, $size
1942  
1943 Set the current font to $font at $size.
1944  
1945 =cut
1946  
1947 sub textfont {
1948 my $self = shift;
1949 croak("PDF::Cairo::textfont: Must use textstart() first")
1950 unless defined $self->{_api2text};
1951 my ($font, $size) = @_;
1952 croak("PDF::Cairo::textfont(font_ref, font_size)")
1953 unless $size > 0;
1954 $self->setfont($font, $size);
1955 return $self;
1956 }
1957  
1958 =item B<textlead> $leading
1959  
1960 Set the spacing between lines to $leading (default is 0, which
1961 prints all lines on top of each other).
1962  
1963 =cut
1964  
1965 sub textlead {
1966 my $self = shift;
1967 $self->{_api2text}->{lead} = shift;
1968 return $self;
1969 }
1970  
1971 =item B<text> $string
1972  
1973 Display text at current position, with the current font and fillcolor.
1974 The current position will be moved to the end of the displayed text.
1975  
1976 =cut
1977  
1978 sub text {
1979 my $self = shift;
1980 if ($self->{_api2text}->{first} == 1) {
1981 $self->{_api2text}->{first} = 0;
1982 $self->move(0, 0);
1983 }
1984 $self->print(shift);
1985 return $self;
1986 }
1987  
1988 =item B<nl>
1989  
1990 Move to the beginning of the next line of text (0, -$leading * ($lines - 1)).
1991  
1992 =cut
1993  
1994 sub nl {
1995 my $self = shift;
1996 my $api2 = $self->{_api2text};
1997 $api2->{line}++;
1998 $self->move(0, -1 * $api2->{line} * $api2->{lead});
1999 return $self;
2000 }
2001  
2002 =item B<textend>
2003  
2004 End the current text block.
2005  
2006 =cut
2007  
2008 sub textend {
2009 my $self = shift;
2010 $self->{_api2text} = undef;
2011 return $self;
2012 }
2013  
2014 =back
2015  
2016 =cut
2017  
2018 # internal functions
2019  
2020 # convert color names and hex numbers to floating-point RGB
2021 #
2022 sub _color {
2023 my ($color) = @_;
2024 my ($r, $g, $b);
2025 if ($color =~ /^#/) {
2026 my $l = int((length($color) - 1) / 3);
2027 ($r, $g, $b) = map(hex($_)/(16**$l - 1),
2028 $color =~ /^#(.{$l})(.{$l})(.{$l})$/);
2029 }elsif ($color =~ /^[0-9.]+$/) {
2030 ($r, $g, $b) = ($color, $color, $color);
2031 }else{
2032 $color =~ tr/A-Z/a-z/;
2033 $color =~ tr/ //d;
2034 ($r, $g, $b) = @{$rgb{$color}->{float}};
2035 }
2036 return ($r, $g, $b);
2037 }
2038  
2039 sub _rad {
2040 return $_[0] * 0.01745329252;
2041 }
2042  
2043 sub _setup_page_state {
2044 my ($self) = @_;
2045 $self->{context} = Cairo::Context->create($self->{surface})
2046 unless defined $self->{context};
2047 # show_page() doesn't reset a lot of things...
2048 $self->{context}->new_path;
2049 $self->{context}->set_source_rgb(0, 0, 0);
2050 $self->{context}->set_line_width(1);
2051 $self->{context}->identity_matrix;
2052 $self->{context}->reset_clip;
2053 $self->{context}->set_dash(0);
2054 $self->{context}->set_fill_rule('winding');
2055 $self->{context}->translate(0, $self->{h});
2056  
2057 # save/restore stack to track separate fill/stroke colors
2058 # (Cairo has only one active color).
2059 $self->{stack} = [];
2060 $self->{_fill} = "black";
2061 $self->{_stroke} = "black";
2062  
2063 # keep compatibility methods from creating extra blank pages
2064 $self->{_dirtypage} = 0;
2065 }
2066  
2067 =head1 LIMITATIONS
2068  
2069 =over 4
2070  
2071 =item * libcairo version must be 1.10.0 or greater to support
2072 recording surfaces, which this module makes extensive use of. Future
2073 versions will require 1.16.0 or greater to support metadata, outlines,
2074 hyperlinks, page labels, etc.
2075  
2076 =item * The fillcolor/strokecolor methods do not currently support the
2077 various %cmyk, &hsl, !hsv options for setting color values. (TODO)
2078  
2079 =item * All images are converted to PNG before embedding in the
2080 output. This is a limitation of the Cairo library.
2081  
2082 =item * Vector images placed with loadimage() are rasterized with
2083 ImageMagick's C<convert> command.
2084  
2085 =item * Cairo only supports one active color at a time, not separate
2086 stroke and fill colors. I maintain a separate save/restore stack to
2087 work around this, and hopefully I haven't missed any edge cases.
2088  
2089 =item * No built-in support for the standard PDF fonts. All fonts will
2090 be embedded in the output, and unless you load a specific font file
2091 from disk, what you get when you specify a font name like
2092 "Helvetica-Bold" will depend on your computer's L<Fontconfig>
2093 settings.
2094  
2095 =item * On a Mac, Fontconfig will only search a short list of well-known
2096 directories, which does not include the locations used by font managers
2097 like Typekit and FontExplorer Pro.
2098  
2099 =back
2100  
2101 =head1 AUTHOR
2102  
2103 J Greely, C<< <jgreely at cpan.org> >>
2104  
2105 =head1 SEE ALSO
2106  
2107 L<PDF::API2>, L<PDF::Builder>, L<Cairo>, L<Font::FreeType>, L<Pango>,
2108 L<Fontconfig|http://fontconfig.org>, L<ImageMagick|https://imagemagick.org/>
2109  
2110 Pages 187-192 of
2111 L<Adobe PPD Specifications|http://partners.adobe.com/asn/developer/pdfs/tn/5003.PPD_Spec_v4.3.pdf>
2112  
2113 =head1 BUGS
2114  
2115 Please report any bugs or feature requests to C<bug-pdf-cairo at rt.cpan.org>, or through
2116 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=PDF-Cairo>. I will be notified, and then you'll
2117 automatically be notified of progress on your bug as I make changes.
2118  
2119  
2120  
2121  
2122 =head1 SUPPORT
2123  
2124 You can find documentation for this module with the perldoc command.
2125  
2126 perldoc PDF::Cairo
2127  
2128  
2129 You can also look for information at:
2130  
2131 =over 4
2132  
2133 =item * RT: CPAN's request tracker (report bugs here)
2134  
2135 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=PDF-Cairo>
2136  
2137 =item * AnnoCPAN: Annotated CPAN documentation
2138  
2139 L<http://annocpan.org/dist/PDF-Cairo>
2140  
2141 =item * CPAN Ratings
2142  
2143 L<https://cpanratings.perl.org/d/PDF-Cairo>
2144  
2145 =item * Search CPAN
2146  
2147 L<https://metacpan.org/release/PDF-Cairo>
2148  
2149 =back
2150  
2151  
2152 =head1 ACKNOWLEDGEMENTS
2153  
2154  
2155 =head1 LICENSE AND COPYRIGHT
2156  
2157 This software is Copyright (c) 2019 by J Greely.
2158  
2159 This is free software, licensed under:
2160  
2161 MIT License
2162  
2163 =cut
2164  
2165 # quick hack to add width/height methods to images and recordings
2166 #
2167 sub Cairo::ImageSurface::height {
2168 my $self = shift;
2169 $self->get_height;
2170 }
2171 sub Cairo::ImageSurface::width {
2172 my $self = shift;
2173 $self->get_width;
2174 }
2175  
2176 1; # End of PDF::Cairo
« Cairo/Papers.pm ↑ Summary