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/Layout.pm ↑ Summary Cairo/Colors.pm »
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.03";
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  
1024 =cut
1025  
1026 sub print {
1027 my $self = shift;
1028 if (ref $_[0]) {
1029 $self->_api2_print(@_);
1030 }else{
1031 my ($text, %options) = @_;
1032 my $extents = $self->{context}->text_extents($text);
1033 my $width = $extents->{width};
1034 my $height = $extents->{height};
1035 my ($dx, $dy) = (0, 0);
1036 $options{align} ||= "left";
1037 if ($options{align} eq "center") {
1038 $dx -= $width / 2;
1039 }elsif ($options{align} eq "right") {
1040 $dx -= $width;
1041 }
1042 # TODO: add "bottom", distinct from default baseline
1043 $options{valign} ||= "baseline";
1044 if ($options{valign} eq "center") {
1045 $dy += $height / 2;
1046 }elsif ($options{valign} eq "top") {
1047 $dy += $height;
1048 }
1049 if ($options{shift}) {
1050 $dy += $options{shift};
1051 }
1052 if ($dx or $dy) {
1053 my ($x, $y) = $self->{context}->get_current_point;
1054 $self->{context}->move_to($x + $dx, $y + $dy);
1055 }
1056 $self->{context}->set_source_rgb(@{$rgb{$self->{_fill}}->{float}});
1057 $self->{context}->show_text($text);
1058 # note this leaves the current point offset by the alignment
1059 # which means calling print() again without moving first
1060 # will match the baseline. I think this is a feature.
1061 }
1062 $self->{_dirtypage} = 1;
1063 return $self;
1064 }
1065  
1066 =item B<textpath> $text
1067  
1068 Add the outlines of the glyphs in $text to the current path, using
1069 the current font and size.
1070  
1071 =cut
1072  
1073 sub textpath {
1074 my $self = shift;
1075 my $text = shift;
1076 $self->{context}->text_path($text);
1077 return $self;
1078 }
1079  
1080 =back
1081  
1082 =head2 Raster Images
1083  
1084 =over 4
1085  
1086 =item B<loadimage> $file
1087  
1088 Load a PNG-format image from $file. Returns a Cairo image surface that
1089 can be placed any number of times with showimage(); height() and
1090 width() methods are available to determine appropriate scaling values.
1091  
1092 If L<ImageMagick|https://imagemagick.org/>'s F<convert> command is
1093 available, it will be used to convert other image formats into PNG.
1094  
1095 =cut
1096  
1097 sub loadimage {
1098 my $self = shift;
1099 my $file = shift;
1100 if ($HAS_IMAGEMAGICK) {
1101 my $fh;
1102 my @convert = qw(convert -density 72);
1103 if (!open($fh, '-|:raw', @convert, $file, 'png:-')) {
1104 croak "loadimage($file): $!\n";
1105 }
1106 my $result = Cairo::ImageSurface->create_from_png_stream(
1107 sub {
1108 my ($fh, $length) = @_;
1109 my $buffer;
1110 read($fh, $buffer, $length);
1111 return $buffer;
1112 }, $fh,
1113 );
1114 CORE::close($fh);
1115 return $result;
1116 }else{
1117 my $result = Cairo::ImageSurface->create_from_png($file);
1118 croak "loadimage($file) failed (not a PNG and convert not available?)"
1119 unless $result->status eq 'success';
1120 return $result;
1121 }
1122 }
1123  
1124 =item B<showimage> $image, $x, $y, %options
1125  
1126 =over 4
1127  
1128 =item align => 'left|center|right'
1129  
1130 =item valign => 'top|center|bottom'
1131  
1132 =item center => 1
1133  
1134 =item scale => $scale
1135  
1136 =item size => [ $width, $height ]
1137  
1138 =item x_scale => $scale
1139  
1140 =item y_scale => $scale
1141  
1142 =item rotate => $degrees
1143  
1144 =back
1145  
1146 Display $image with its lower-left corner at ($x, $y), scaled at 100%
1147 in the current user coordinate unless one of the scaling options is
1148 supplied.
1149  
1150 =cut
1151  
1152 sub showimage {
1153 my $self = shift;
1154 my $image_surface = shift;
1155 my $x = shift;
1156 my $y = shift;
1157 my %options = @_;
1158 my ($x_scale, $y_scale) = (1, 1);
1159 if ($options{scale}) {
1160 $x_scale = $options{scale};
1161 $y_scale = $options{scale};
1162 }
1163 if ($options{x_scale}) {
1164 $x_scale = $options{x_scale};
1165 }
1166 if ($options{y_scale}) {
1167 $y_scale = $options{y_scale};
1168 }
1169 if ($options{size}) {
1170 my ($w, $h) = @{$options{size}};
1171 $x_scale = $w / $image_surface->get_width;
1172 $y_scale = $h / $image_surface->get_height;
1173 }
1174 my $height = $image_surface->get_height * $y_scale;
1175 my $width = $image_surface->get_width * $x_scale;
1176 $self->save;
1177 $self->translate($x, $y + $height);
1178  
1179 if (defined $options{rotate}) {
1180 # calculate the rotated position of lower-left corner and
1181 # translate the origin so that the rotation comes from there.
1182 my $a = -1 * _rad($options{rotate});
1183 $self->translate($height * sin($a), $height * (cos($a) - 1));
1184 $self->rotate($options{rotate});
1185 }
1186  
1187 # align image to other than bottom-left
1188 # this must happen after rotation but before scaling
1189 my ($tx, $ty) = (0, 0);
1190 if ($options{center}) {
1191 $options{align} = "center";
1192 $options{valign} = "center";
1193 }
1194 $options{align} ||= "left";
1195 if ($options{align} eq "center") {
1196 $tx = - $width / 2;
1197 }elsif ($options{align} eq "right") {
1198 $tx = - $width;
1199 }
1200 $options{valign} ||= "bottom";
1201 if ($options{valign} eq "center") {
1202 $ty = $height / 2;
1203 }elsif ($options{valign} eq "top") {
1204 $ty = $height;
1205 }
1206 if ($tx or $ty) {
1207 my ($x, $y) = $self->{context}->get_current_point;
1208 $self->{context}->translate($tx, $ty);
1209 }
1210  
1211 if ($x_scale != 1 or $y_scale != 1) {
1212 $self->scale($x_scale, $y_scale);
1213 }
1214 $self->{context}->set_source_surface($image_surface, 0, 0);
1215 $self->{context}->paint;
1216 $self->restore;
1217 return $self;
1218 }
1219  
1220 =back
1221  
1222 =head2 Advanced and Experimental
1223  
1224 =over 4
1225  
1226 =item B<loadsvg> $file|$string
1227  
1228 Create an object with recording() containing an SVG image rendered
1229 with L<Image::CairoSVG>, with the lower-left corner at (0,0). It can
1230 be rendered with place() as many times as you want.
1231  
1232 Note that Image::CairoSVG only supports path operators, and ignores
1233 filters, fonts, and text, so many complex SVG files will not render
1234 as expected.
1235  
1236 =cut
1237  
1238 # renders the SVG *twice*; first to find its bounding box, then
1239 # with the origin translated vertically so it matches the PDF
1240 # coordinate system.
1241 #
1242 sub loadsvg {
1243 my $class = shift;
1244 my $svg = shift;
1245 my $rectmp = PDF::Cairo->recording(_unlimited => 1);
1246 my $image = Image::CairoSVG->new (context => $rectmp->{context});
1247 $image->render($svg);
1248 my @ink = $rectmp->{surface}->ink_extents;
1249  
1250 my $recording = PDF::Cairo->recording(width => $ink[2], height => $ink[3]);
1251 $recording->translate(0, $ink[3]);
1252 $image = Image::CairoSVG->new (context => $recording->{context});
1253 $image->render($svg);
1254 $recording->{surface}->flush;
1255 return $recording;
1256 }
1257  
1258 =item B<path> ['move|line|curve|close', [$x, $y, ...], ...]
1259  
1260 Appends an array of move/line/curve/close operations to the current
1261 path. This is done with Cairo's append_path() method, so it's more
1262 efficient than calling each method one-by-one.
1263  
1264 If no arguments are passed, returns the current path in this
1265 format, and then clears the path.
1266  
1267 =cut
1268  
1269 sub path {
1270 my $self = shift;
1271 if (@_) {
1272 $self->_appendpath(@_);
1273 }else{
1274 $self->_getpath;
1275 }
1276 }
1277  
1278 sub _appendpath {
1279 my $self = shift;
1280 my @path;
1281 while (@_) {
1282 my $op = shift;
1283 my $val = shift;
1284 if ($op eq 'move') {
1285 my ($x, $y) = @$val;
1286 push(@path, { type => 'move-to', points => [ [$x, -$y] ] });
1287 }elsif ($op eq 'line') {
1288 my ($x, $y) = @$val;
1289 push(@path, { type => 'line-to', points => [ [$x, -$y] ] });
1290 }elsif ($op eq 'curve') {
1291 my ($cx1, $cy1, $cx2, $cy2, $x, $y) = @$val;
1292 push(@path, { type => 'curve-to', points => [
1293 [$cx1, -$cy1],
1294 [$cx2, -$cy2],
1295 [$x, -$y],
1296 ]});
1297 }elsif ($op eq 'close') {
1298 push(@path, { type => 'close-path', points => [] });
1299 }else{
1300 croak "PDF::Cairo::_appendpath: unknown operator '$op'";
1301 }
1302 }
1303 $self->{context}->append_path(\@path);
1304 return $self;
1305 }
1306  
1307 sub _getpath {
1308 my $self = shift;
1309 my @path;
1310 foreach my $op (@{$self->{context}->copy_path}) {
1311 my $key = $op->{type};
1312 my $val = $op->{points};
1313 $key =~ s/-.*$//;
1314 my @points;
1315 foreach my $pt (@$val) {
1316 my ($x, $y) = @$pt;
1317 push(@points, $x, - $y);
1318 }
1319 push(@path, $key, \@points);
1320 }
1321 $self->{context}->new_path;
1322 return @path;
1323 }
1324  
1325 =item B<place> $recording, $x,$y, %options
1326  
1327 =over 4
1328  
1329 =item clip => [ $width, $height]
1330  
1331 =item dx => $offset_x
1332  
1333 =item dy => $offset_y
1334  
1335 =item align => 'left|center|right'
1336  
1337 =item valign => 'top|center|bottom'
1338  
1339 =item center => 1
1340  
1341 =item scale => $scale
1342  
1343 =item size => [ $width, $height ]
1344  
1345 =item x_scale => $scale
1346  
1347 =item y_scale => $scale
1348  
1349 =item rotate => $degrees
1350  
1351 =back
1352  
1353 Places the recording object $recording with its lower-left corner at
1354 ($x,$y). If the clip argument is provided, the recording is clipped
1355 to that width/height before rendering. If $dx or $dy is provided, the
1356 recording will be offset by those amounts before rendering. This can
1357 be used to do things like tile a large image across multiple pages.
1358  
1359 =cut
1360  
1361 sub place {
1362 my $self = shift;
1363 croak "PDF::Cairo::place: first argument must be a recording/svg/image"
1364 unless defined $_[0];
1365 # pass raster images to showimage
1366 return $self->showimage(@_)
1367 if ref $_[0] eq 'Cairo::ImageSurface';
1368 my $recording = shift;
1369 croak "PDF:Cairo::place: first argument must be a recording object"
1370 unless ref $recording->{surface} eq 'Cairo::RecordingSurface';
1371 my $width = $recording->{w};
1372 my $height = $recording->{h};
1373 my $x = shift || 0;
1374 my $y = shift || 0;
1375 my %options = @_;
1376  
1377 my $dx = defined $options{dx} ? $options{dx} : 0;
1378 my $dy = defined $options{dy} ? $options{dy} : 0;
1379 my ($x_scale, $y_scale) = (1, 1);
1380 if ($options{scale}) {
1381 $x_scale = $options{scale};
1382 $y_scale = $options{scale};
1383 }
1384 if ($options{x_scale}) {
1385 $x_scale = $options{x_scale};
1386 }
1387 if ($options{y_scale}) {
1388 $y_scale = $options{y_scale};
1389 }
1390 if ($options{size}) {
1391 my ($w, $h) = @{$options{size}};
1392 $x_scale = $w / $width;
1393 $y_scale = $h / $height;
1394 }
1395 $self->save;
1396 $self->translate($x, $y) if $x or $y;
1397 if (defined $options{rotate}) {
1398 $self->rotate($options{rotate});
1399 }
1400  
1401 # align image to other than bottom-left
1402 # this must happen after rotation but before scaling
1403 my ($tx, $ty) = (0, 0);
1404 if ($options{center}) {
1405 $options{align} = "center";
1406 $options{valign} = "center";
1407 }
1408 $options{align} ||= "left";
1409 if ($options{align} eq "center") {
1410 $tx = - $width * $x_scale / 2;
1411 }elsif ($options{align} eq "right") {
1412 $tx = - $width * $x_scale;
1413 }
1414 $options{valign} ||= "bottom";
1415 if ($options{valign} eq "center") {
1416 $ty = $height * $y_scale / 2;
1417 }elsif ($options{valign} eq "top") {
1418 $ty = $height * $y_scale;
1419 }
1420 if ($tx or $ty) {
1421 my ($x, $y) = $self->{context}->get_current_point;
1422 $self->{context}->translate($tx, $ty);
1423 }
1424  
1425 if ($x_scale != 1 or $y_scale != 1) {
1426 $self->scale($x_scale, $y_scale);
1427 }
1428 if (defined $options{clip}) {
1429 $self->rect(0, 0, @{$options{clip}});
1430 $self->clip;
1431 }
1432 $recording->{surface}->flush;
1433 $self->{context}->set_source_surface($recording->{surface},
1434 -$dx, -$recording->{h} + $dy);
1435 $self->{context}->paint;
1436 $self->restore;
1437 return $self;
1438 }
1439  
1440 =item B<recording> %options
1441  
1442 =over 4
1443  
1444 =item paper => $paper_size
1445  
1446 =item height => $Ypts
1447  
1448 =item width => $Xpts
1449  
1450 =item wide|landscape => 1
1451  
1452 =item tall|portrait => 1
1453  
1454 =back
1455  
1456 Creates a new PDF::Cairo recording object. You can draw on it
1457 normally, but can only access the results with place(). Options are
1458 the same as new(). height() and width() methods are available to
1459 determine appropriate scaling values.
1460  
1461 =cut
1462  
1463 # Create a recording surface.
1464 #
1465 sub recording {
1466 my $class = shift;
1467 my %options = @_;
1468 return PDF::Cairo->new(_recording => 1, %options);
1469 }
1470  
1471 =back
1472  
1473 =head2 Utility Functions
1474  
1475 These are imported from L<PDF::Cairo::Util> so you don't have to
1476 explicitly use that module in every script.
1477  
1478 =over 4
1479  
1480 =item B<cm> $centimeters
1481  
1482 Converts the arguments from centimeters to points. Importable.
1483  
1484 =cut
1485  
1486 sub cm {
1487 return PDF::Cairo::Util::cm(@_);
1488 }
1489  
1490 =item B<in> $inches
1491  
1492 Converts the arguments from inches to points. Importable.
1493  
1494 =cut
1495  
1496 sub in {
1497 return PDF::Cairo::Util::in(@_);
1498 }
1499  
1500 =item B<mm> $millimeters
1501  
1502 Converts the arguments from millimeters to points. Importable.
1503  
1504 =cut
1505  
1506 sub mm {
1507 return PDF::Cairo::Util::mm(@_);
1508 }
1509  
1510 =item B<paper_size> %options
1511  
1512 =over 4
1513  
1514 =item paper => $paper_size
1515  
1516 =item wide|landscape => 1
1517  
1518 =item tall|portrait => 1
1519  
1520 =back
1521  
1522 Return size in points of a paper type. The default is "US Letter"
1523 (8.5x11 inches). The wide/tall options can be used to ensure that the
1524 orientation of the page is as expected. Importable.
1525  
1526 The supported paper sizes are listed in L<PDF::Cairo::Papers>.
1527  
1528 =cut
1529  
1530 # can either be called as a method or a function;
1531 # returns ($width, $height) in points
1532 #
1533 sub paper_size {
1534 return PDF::Cairo::Util::paper_size(@_);
1535 }
1536  
1537 =item B<regular_polygon> $sides
1538  
1539 Calculate the vertices of a regular polygon with $sides sides with
1540 radius 1, along with the relative lengths of the inradius and edge.
1541  
1542 Returns a hashref:
1543  
1544 {
1545 points => [ [$x0, $y0], ... ],
1546 edge => $edge_length,
1547 inradius => $inradius_length,
1548 radius => 1,
1549 }
1550  
1551 Calling the polygon($cx, $cy, $radius, $sides) method is equivalent to:
1552  
1553 $poly = regular_polygon($sides);
1554 @points = map(@$_, @{$poly->{points}});
1555 $pdf->save;
1556 $pdf->translate($cx, $cy);
1557 $pdf->scale($radius);
1558 $pdf->poly(@points);
1559 $pdf->close;
1560 $pdf->restore;
1561  
1562 =cut
1563  
1564 sub regular_polygon {
1565 return PDF::Cairo::Util::regular_polygon(@_);
1566 }
1567  
1568 =back
1569  
1570 =head2 PDF::API2 Compatibility
1571  
1572 =over 4
1573  
1574 =item B<addFontDirs> $directory, ...
1575  
1576 Append one or more directories to the font search path. Returns
1577 the current font path.
1578  
1579 =cut
1580  
1581 sub addFontDirs {
1582 shift if ref $_[0]; # not a method call, but allow the error
1583 PDF::Cairo::Font::append_font_path(@_);
1584 return PDF::Cairo::Font::get_font_path();
1585 }
1586  
1587 =item B<clip> $use_even_odd
1588  
1589 Additional way to specify even-odd fill rule for clip().
1590  
1591 =item B<cjkfont> $font
1592  
1593 Load something vaguely appropriate for the requested PDF::API2
1594 CJK font name. See PDF::Cairo::Font for recommended alternatives.
1595  
1596 =cut
1597  
1598 sub cjkfont {
1599 loadfont(@_);
1600 }
1601  
1602 =item B<corefont> $fontname
1603  
1604 Load the closest match to a PDF::API2 core font, as described in
1605 PDF::Cairo::Font.
1606  
1607 =cut
1608  
1609 sub corefont {
1610 loadfont(@_);
1611 }
1612  
1613 =item B<endpath>
1614  
1615 Ends current (sub)path without close(). Generally only used after
1616 clip(), so it's effectively a no-op in PDF::Cairo.
1617  
1618 =cut
1619  
1620 sub endpath {
1621 my $self = shift;
1622 $self->{context}->new_path;
1623 return $self;
1624 }
1625  
1626 =item B<fill> $use_even_odd
1627  
1628 Additional way to specify even-odd fill rule for fill().
1629  
1630 =item B<fillstroke> $use_even_odd
1631  
1632 Additional way to specify even-odd fill rule for fillstroke().
1633  
1634 =item B<image> $image, $x, $y, ($width, $height) | [$scale]
1635  
1636 Wrapper for showimage().
1637  
1638 =cut
1639  
1640 sub image {
1641 my $self = shift;
1642 my $image_surface = shift;
1643 my $x = shift;
1644 my $y = shift;
1645 if (defined $_[1]) {
1646 $self->showimage($image_surface, $x, $y, size => [ @_ ]);
1647 }elsif (defined $_[0]) {
1648 $self->showimage($image_surface, $x, $y, scale => $_[0]);
1649 }else{
1650 $self->showimage($image_surface, $x, $y)
1651 }
1652 return $self;
1653 }
1654  
1655 =item B<image_gif> $file
1656  
1657 Alias for loadimage(); requires ImageMagick F<convert> program.
1658  
1659 =cut
1660  
1661 sub image_gif {
1662 loadimage(@_);
1663 }
1664  
1665 =item B<image_jpg> $file
1666  
1667 Alias for loadimage(); requires ImageMagick F<convert> program.
1668  
1669 =cut
1670  
1671 sub image_jpg {
1672 loadimage(@_);
1673 }
1674  
1675 =item B<image_png> $file
1676  
1677 Alias for loadimage().
1678  
1679 =cut
1680  
1681 sub image_png {
1682 loadimage(@_);
1683 }
1684  
1685 =item B<image_pnm> $file
1686  
1687 Alias for loadimage(); requires ImageMagick F<convert> program.
1688  
1689 =cut
1690  
1691 sub image_pnm {
1692 loadimage(@_);
1693 }
1694  
1695 =item B<image_tiff> $file
1696  
1697 Alias for loadimage(); requires ImageMagick F<convert> program.
1698  
1699 =cut
1700  
1701 sub image_tiff {
1702 loadimage(@_);
1703 }
1704  
1705 =item B<linedash> $length
1706  
1707 =item B<linedash> $dash1, $gap1, ...
1708  
1709 =item B<linedash> -pattern => [$dash1, $gap1, ...], -shift => $offset
1710  
1711 Additional ways to pass arguments to linedash().
1712  
1713 =item B<page> [$width, $height]
1714  
1715 Emulates the behavior of PDF::API2::Lite's page() method, which starts
1716 a new page, defaulting to the size of the previous page if there was
1717 one. Note that this does not accept the four-argument form with the
1718 coordinates of the lower-left and upper-right corners.
1719  
1720 =cut
1721  
1722 sub page {
1723 my $self = shift;
1724 my ($w, $h) = @_;
1725 if ($self->{_dirtypage}) {
1726 $self->newpage(width => $w, height => $h);
1727 }else{
1728 $self->paper_size(width => $w, height => $h);
1729 $self->{surface}->set_size($self->{w}, $self->{h});
1730 _setup_page_state($self);
1731 }
1732 return $self;
1733 }
1734  
1735 =item B<print> $font, $size, $x, $y, $rotation, $justification, @text
1736  
1737 Sadly necessary, since I use it all the time with PDF::API2::Lite.
1738  
1739 =cut
1740  
1741 sub _api2_print {
1742 my $self = shift;
1743 my ($font, $size, $x, $y, $rotation, $justification, @text) = @_;
1744 croak "PDF::Cairo::print: requires text argument"
1745 unless defined $text[0];
1746 my $text = join(' ', @text);
1747 $self->{context}->set_font_face($font->{face});
1748 $self->{context}->set_font_size($size);
1749 my $width = $self->{context}->text_extents($text)->{width};
1750 if ($justification == 1) {
1751 $x -= $width / 2;
1752 }elsif ($justification == 2) {
1753 $x -= $width;
1754 }
1755 $self->move($x, $y);
1756 my $tmp = $self->{context}->get_matrix;
1757 $self->rotate($rotation);
1758 $self->{context}->set_source_rgb(@{$rgb{$self->{_fill}}->{float}});
1759 $self->{context}->show_text($text);
1760 $self->{context}->set_matrix($tmp);
1761 $self->{_dirtypage} = 1;
1762 return $self;
1763 }
1764  
1765 =item B<psfont> $font
1766  
1767 Load a Type 1 font from disk using FreeType. If a matching
1768 AFM file is found in the font path, it will also be loaded.
1769  
1770 =cut
1771  
1772 sub psfont {
1773 loadfont(@_);
1774 }
1775  
1776 =item B<rectxy> $x1, $x1, $x2, $y2
1777  
1778 Draw a rectangle with opposite corners at ($x1, $y1) and ($x2, $y2).
1779  
1780 =cut
1781  
1782 sub rectxy {
1783 my $self = shift;
1784 my ($x1, $y1, $x2, $y2) = @_;
1785 $self->rect($x1, $y1, $x2-$x1, $y2-$y1);
1786 return $self;
1787 }
1788  
1789 =item B<restorestate>
1790  
1791 Alias for restore().
1792  
1793 =cut
1794  
1795 sub restorestate {
1796 restore(@_);
1797 }
1798  
1799 =item B<saveas> $file
1800  
1801 Finishes the current PDF file and saves it to $file. No further
1802 drawing operations can be performed.
1803  
1804 =cut
1805  
1806 sub saveas {
1807 my $self = shift;
1808 my $filename = shift;
1809 if ($self->{_is_stream}) {
1810 $self->{surface}->flush;
1811 $self->{surface}->finish;
1812 open(my $Out, '>:raw', $filename)
1813 or die "$0: PDF::Cairo::saveas($filename): $!\n";
1814 print $Out $self->{_streamdata};
1815 CORE::close($Out);
1816 }else{
1817 croak "saveas() only works if you didn't set a filename in new()\n";
1818 }
1819 }
1820  
1821 =item B<savestate>
1822  
1823 Alias for save().
1824  
1825 =cut
1826  
1827 sub savestate {
1828 save(@_);
1829 }
1830  
1831 =item B<stringify>
1832  
1833 Finishes the current PDF file and returns it as a scalar. No further
1834 drawing operations can be performed.
1835  
1836 =cut
1837  
1838 sub stringify {
1839 my $self = shift;
1840 if ($self->{_is_stream}) {
1841 $self->{surface}->flush;
1842 $self->{surface}->finish;
1843 return $self->{_streamdata};
1844 }else{
1845 croak "stringify() only works if you didn't set a filename in new()\n";
1846 }
1847 }
1848  
1849 =item B<transform> %options
1850  
1851 =over 4
1852  
1853 =item -translate => [$x, $y]
1854  
1855 =item -rotate => $degrees
1856  
1857 =item -scale => [$sx, $sy]
1858  
1859 =item -skew => [$sa, $sb]
1860  
1861 =back
1862  
1863 Perform multiple coordinate transforms at once, in PDF-canonical
1864 order.
1865  
1866 =cut
1867  
1868 # always thought it was odd that PDF::API2::Lite didn't have the
1869 # individual transformations, even though PDF::API2::Content does.
1870 #
1871 sub transform {
1872 my $self = shift;
1873 my %options = @_;
1874 $self->translate(@{$options{-translate}})
1875 if $options{-translate};
1876 $self->rotate(@{$options{-rotate}})
1877 if $options{-rotate};
1878 $self->scale(@{$options{-scale}})
1879 if $options{-scale};
1880 $self->skew(@{$options{-skew}})
1881 if $options{-skew};
1882 return $self;
1883 }
1884  
1885 =item B<ttfont> $font
1886  
1887 Load a TrueType/OpenType font from disk using FreeType.
1888  
1889 =cut
1890  
1891 sub ttfont {
1892 loadfont(@_);
1893 }
1894  
1895 =back
1896  
1897 =head2 PDF::API2::Lite Text Compatibility
1898  
1899 These methods should not be used in new code, and are present solely
1900 to simplify converting existing scripts that use L<PDF::API2::Lite>.
1901 Use L<PDF::Cairo::Layout> instead. Honestly, in over 15 years of using
1902 PDF::API2::Lite, I never once used these methods.
1903  
1904 Note that this is the I<Lite> version, which exposes only a subset
1905 of the functionality in L<PDF::API2::Content>.
1906  
1907 =over 4
1908  
1909 =item B<textstart>
1910  
1911 Starts a block of text with the baseline set to (0, 0). You must
1912 translate the origin to get the text to appear anywhere else.
1913  
1914 =cut
1915  
1916 sub textstart {
1917 my $self = shift;
1918 $self->{_api2text} = {
1919 lead => 0,
1920 lines => 0,
1921 first => 1,
1922 };
1923 return $self;
1924 }
1925  
1926 =item B<textfont> $font, $size
1927  
1928 Set the current font to $font at $size.
1929  
1930 =cut
1931  
1932 sub textfont {
1933 my $self = shift;
1934 croak("PDF::Cairo::textfont: Must use textstart() first")
1935 unless defined $self->{_api2text};
1936 my ($font, $size) = @_;
1937 croak("PDF::Cairo::textfont(font_ref, font_size)")
1938 unless $size > 0;
1939 $self->setfont($font, $size);
1940 return $self;
1941 }
1942  
1943 =item B<textlead> $leading
1944  
1945 Set the spacing between lines to $leading (default is 0, which
1946 prints all lines on top of each other).
1947  
1948 =cut
1949  
1950 sub textlead {
1951 my $self = shift;
1952 $self->{_api2text}->{lead} = shift;
1953 return $self;
1954 }
1955  
1956 =item B<text> $string
1957  
1958 Display text at current position, with the current font and fillcolor.
1959 The current position will be moved to the end of the displayed text.
1960  
1961 =cut
1962  
1963 sub text {
1964 my $self = shift;
1965 if ($self->{_api2text}->{first} == 1) {
1966 $self->{_api2text}->{first} = 0;
1967 $self->move(0, 0);
1968 }
1969 $self->print(shift);
1970 return $self;
1971 }
1972  
1973 =item B<nl>
1974  
1975 Move to the beginning of the next line of text (0, -$leading * ($lines - 1)).
1976  
1977 =cut
1978  
1979 sub nl {
1980 my $self = shift;
1981 my $api2 = $self->{_api2text};
1982 $api2->{line}++;
1983 $self->move(0, -1 * $api2->{line} * $api2->{lead});
1984 return $self;
1985 }
1986  
1987 =item B<textend>
1988  
1989 End the current text block.
1990  
1991 =cut
1992  
1993 sub textend {
1994 my $self = shift;
1995 $self->{_api2text} = undef;
1996 return $self;
1997 }
1998  
1999 =back
2000  
2001 =cut
2002  
2003 # internal functions
2004  
2005 # convert color names and hex numbers to floating-point RGB
2006 #
2007 sub _color {
2008 my ($color) = @_;
2009 my ($r, $g, $b);
2010 if ($color =~ /^#/) {
2011 my $l = int((length($color) - 1) / 3);
2012 ($r, $g, $b) = map(hex($_)/(16**$l - 1),
2013 $color =~ /^#(.{$l})(.{$l})(.{$l})$/);
2014 }elsif ($color =~ /^[0-9.]+$/) {
2015 ($r, $g, $b) = ($color, $color, $color);
2016 }else{
2017 $color =~ tr/A-Z/a-z/;
2018 $color =~ tr/ //d;
2019 ($r, $g, $b) = @{$rgb{$color}->{float}};
2020 }
2021 return ($r, $g, $b);
2022 }
2023  
2024 sub _rad {
2025 return $_[0] * 0.01745329252;
2026 }
2027  
2028 sub _setup_page_state {
2029 my ($self) = @_;
2030 $self->{context} = Cairo::Context->create($self->{surface})
2031 unless defined $self->{context};
2032 # show_page() doesn't reset a lot of things...
2033 $self->{context}->new_path;
2034 $self->{context}->set_source_rgb(0, 0, 0);
2035 $self->{context}->set_line_width(1);
2036 $self->{context}->identity_matrix;
2037 $self->{context}->reset_clip;
2038 $self->{context}->set_dash(0);
2039 $self->{context}->set_fill_rule('winding');
2040 $self->{context}->translate(0, $self->{h});
2041  
2042 # save/restore stack to track separate fill/stroke colors
2043 # (Cairo has only one active color).
2044 $self->{stack} = [];
2045 $self->{_fill} = "black";
2046 $self->{_stroke} = "black";
2047  
2048 # keep compatibility methods from creating extra blank pages
2049 $self->{_dirtypage} = 0;
2050 }
2051  
2052 =head1 LIMITATIONS
2053  
2054 =over 4
2055  
2056 =item * The fillcolor/strokecolor methods do not currently support the
2057 various %cmyk, &hsl, !hsv options for setting color values. (TODO)
2058  
2059 =item * All images are converted to PNG before embedding in the
2060 output. This is a limitation of the Cairo library.
2061  
2062 =item * Vector images placed with loadimage() are rasterized with
2063 ImageMagick's C<convert> command.
2064  
2065 =item * Cairo only supports one active color at a time, not separate
2066 stroke and fill colors. I maintain a separate save/restore stack to
2067 work around this, and hopefully I haven't missed any edge cases.
2068  
2069 =item * No built-in support for the standard PDF fonts. All fonts will
2070 be embedded in the output, and unless you load a specific font file
2071 from disk, what you get when you specify a font name like
2072 "Helvetica-Bold" will depend on your computer's L<Fontconfig>
2073 settings.
2074  
2075 =item * On a Mac, Fontconfig will only search a short list of well-known
2076 directories, which does not include the locations used by font managers
2077 like Typekit and FontExplorer Pro.
2078  
2079 =back
2080  
2081 =head1 AUTHOR
2082  
2083 J Greely, C<< <jgreely at cpan.org> >>
2084  
2085 =head1 SEE ALSO
2086  
2087 L<PDF::API2>, L<PDF::Builder>, L<Cairo>, L<Font::FreeType>, L<Pango>,
2088 L<Fontconfig|http://fontconfig.org>, L<ImageMagick|https://imagemagick.org/>
2089  
2090 Pages 187-192 of
2091 L<Adobe PPD Specifications|http://partners.adobe.com/asn/developer/pdfs/tn/5003.PPD_Spec_v4.3.pdf>
2092  
2093 =head1 BUGS
2094  
2095 Please report any bugs or feature requests to C<bug-pdf-cairo at rt.cpan.org>, or through
2096 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=PDF-Cairo>. I will be notified, and then you'll
2097 automatically be notified of progress on your bug as I make changes.
2098  
2099  
2100  
2101  
2102 =head1 SUPPORT
2103  
2104 You can find documentation for this module with the perldoc command.
2105  
2106 perldoc PDF::Cairo
2107  
2108  
2109 You can also look for information at:
2110  
2111 =over 4
2112  
2113 =item * RT: CPAN's request tracker (report bugs here)
2114  
2115 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=PDF-Cairo>
2116  
2117 =item * AnnoCPAN: Annotated CPAN documentation
2118  
2119 L<http://annocpan.org/dist/PDF-Cairo>
2120  
2121 =item * CPAN Ratings
2122  
2123 L<https://cpanratings.perl.org/d/PDF-Cairo>
2124  
2125 =item * Search CPAN
2126  
2127 L<https://metacpan.org/release/PDF-Cairo>
2128  
2129 =back
2130  
2131  
2132 =head1 ACKNOWLEDGEMENTS
2133  
2134  
2135 =head1 LICENSE AND COPYRIGHT
2136  
2137 This software is Copyright (c) 2019 by J Greely.
2138  
2139 This is free software, licensed under:
2140  
2141 MIT License
2142  
2143 =cut
2144  
2145 # quick hack to add width/height methods to images and recordings
2146 #
2147 sub Cairo::ImageSurface::height {
2148 my $self = shift;
2149 $self->get_height;
2150 }
2151 sub Cairo::ImageSurface::width {
2152 my $self = shift;
2153 $self->get_width;
2154 }
2155 sub Cairo::RecordingSurface::height {
2156 my $self = shift;
2157 $self->{h};
2158 }
2159 sub Cairo::RecordingSurface::width {
2160 my $self = shift;
2161 $self->{w};
2162 }
2163  
2164 1; # End of PDF::Cairo
« Cairo/Layout.pm ↑ Summary Cairo/Colors.pm »