/
writer.rb
2734 lines (2437 loc) · 94.3 KB
/
writer.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#--
# PDF::Writer for Ruby.
# http://rubyforge.org/projects/ruby-pdf/
# Copyright 2003 - 2005 Austin Ziegler.
#
# Licensed under a MIT-style licence. See LICENCE in the main distribution
# for full licensing information.
#
# $Id$
#++
require 'thread'
require 'open-uri'
require 'transaction/simple'
require 'pdf/core_ext/mutex'
require 'color'
# A class to provide the core functionality to create a PDF document
# without any requirement for additional modules.
module PDF
class Writer
# The version of PDF::Writer.
VERSION = '1.2.0'
# Escape the text so that it's safe for insertion into the PDF
# document.
def self.escape(text)
text.gsub(/\\/, '\\\\\\\\').
gsub(/\(/, '\\(').
gsub(/\)/, '\\)').
gsub(/</, '<').
gsub(/>/, '>').
gsub(/&/, '&')
end
end
end
require 'pdf/math'
require 'pdf/writer/lang'
require 'pdf/writer/lang/en'
begin
require 'zlib'
PDF::Writer::Compression = true
rescue LoadError
warn PDF::Writer::Lang[:no_zlib_no_compress]
PDF::Writer::Compression = false
end
require 'pdf/writer/arc4'
require 'pdf/writer/fontmetrics'
require 'pdf/writer/object'
require 'pdf/writer/object/action'
require 'pdf/writer/object/annotation'
require 'pdf/writer/object/catalog'
require 'pdf/writer/object/contents'
require 'pdf/writer/object/destination'
require 'pdf/writer/object/encryption'
require 'pdf/writer/object/font'
require 'pdf/writer/object/fontdescriptor'
require 'pdf/writer/object/fontencoding'
require 'pdf/writer/object/image'
require 'pdf/writer/object/info'
require 'pdf/writer/object/outlines'
require 'pdf/writer/object/outline'
require 'pdf/writer/object/page'
require 'pdf/writer/object/pages'
require 'pdf/writer/object/procset'
require 'pdf/writer/object/viewerpreferences'
require 'pdf/writer/ohash'
require 'pdf/writer/strokestyle'
require 'pdf/writer/graphics'
require 'pdf/writer/graphics/imageinfo'
require 'pdf/writer/state'
class PDF::Writer
# The system font path. The sytem font path will be determined
# differently for each operating system.
#
# Win32:: Uses ENV['SystemRoot']/Fonts as the system font path. There is
# an extension that will handle this better, but until and
# unless it is distributed with the standard Ruby Windows
# installer, PDF::Writer will not depend upon it.
# OS X:: The fonts are found in /System/Library/Fonts.
# Linux:: The font path list will be found (usually) in
# /etc/fonts/fonts.conf or /usr/etc/fonts/fonts.conf. This XML
# file will be parsed (using REXML) to provide the value for
# FONT_PATH.
FONT_PATH = []
class << self
require 'rexml/document'
# Parse the fonts.conf XML file.
def parse_fonts_conf(filename)
doc = REXML::Document.new(File.open(filename, "rb")).root rescue nil
if doc
path = REXML::XPath.match(doc, '//dir').map do |el|
el.text.gsub($/, '')
end
doc = nil
else
path = []
end
path
end
private :parse_fonts_conf
end
case RUBY_PLATFORM
when /mswin32/o
# Windows font path. This is not the most reliable method.
FONT_PATH << File.join(ENV['SystemRoot'], 'Fonts')
when /darwin/o
# Macintosh font path.
FONT_PATH << '/System/Library/Fonts'
else
FONT_PATH.push(*parse_fonts_conf('/etc/fonts/fonts.conf'))
FONT_PATH.push(*parse_fonts_conf('//usr/etc/fonts/fonts.conf'))
end
FONT_PATH.uniq!
include PDF::Writer::Graphics
# Contains all of the PDF objects, ready for final assembly. This is of
# no interest to external consumers.
attr_reader :objects #:nodoc:
# The ARC4 encryption object. This is of no interest to external
# consumers.
attr_reader :arc4 #:nodoc:
# The string that will be used to encrypt this PDF document.
attr_accessor :encryption_key
# The number of PDF objects in the document
def size
@objects.size
end
# Generate an ID for a new PDF object.
def generate_id
@mutex.synchronize { @current_id += 1 }
end
private :generate_id
# Generate a new font ID.
def generate_font_id
@mutex.synchronize { @current_font_id += 1 }
end
private :generate_font_id
class << self
# Create the document with prepress options. Uses the same options as
# PDF::Writer.new (<tt>:paper</tt>, <tt>:orientation</tt>, and
# <tt>:version</tt>). It also supports the following options:
#
# <tt>:left_margin</tt>:: The left margin.
# <tt>:right_margin</tt>:: The right margin.
# <tt>:top_margin</tt>:: The top margin.
# <tt>:bottom_margin</tt>:: The bottom margin.
# <tt>:bleed_size</tt>:: The size of the bleed area in points.
# Default 12.
# <tt>:mark_length</tt>:: The length of the prepress marks in
# points. Default 18.
#
# The prepress marks are added to the loose objects and will appear on
# all pages.
def prepress(options = { })
pdf = self.new(options)
bleed_size = options[:bleed_size] || 12
mark_length = options[:mark_length] || 18
pdf.left_margin = options[:left_margin] if options[:left_margin]
pdf.right_margin = options[:right_margin] if options[:right_margin]
pdf.top_margin = options[:top_margin] if options[:top_margin]
pdf.bottom_margin = options[:bottom_margin] if options[:bottom_margin]
# This is in an "odd" order because the y-coordinate system in PDF
# is from bottom to top.
tx0 = pdf.pages.media_box[0] + pdf.left_margin
ty0 = pdf.pages.media_box[3] - pdf.top_margin
tx1 = pdf.pages.media_box[2] - pdf.right_margin
ty1 = pdf.pages.media_box[1] + pdf.bottom_margin
bx0 = tx0 - bleed_size
by0 = ty0 - bleed_size
bx1 = tx1 + bleed_size
by1 = ty1 + bleed_size
pdf.pages.trim_box = [ tx0, ty0, tx1, ty1 ]
pdf.pages.bleed_box = [ bx0, by0, bx1, by1 ]
all = pdf.open_object
pdf.save_state
kk = Color::CMYK.new(0, 0, 0, 100)
pdf.stroke_color! kk
pdf.fill_color! kk
pdf.stroke_style! StrokeStyle.new(0.3)
pdf.prepress_clip_mark(tx1, ty0, 0, mark_length, bleed_size) # Upper Right
pdf.prepress_clip_mark(tx0, ty0, 90, mark_length, bleed_size) # Upper Left
pdf.prepress_clip_mark(tx0, ty1, 180, mark_length, bleed_size) # Lower Left
pdf.prepress_clip_mark(tx1, ty1, -90, mark_length, bleed_size) # Lower Right
mid_x = pdf.pages.media_box[2] / 2.0
mid_y = pdf.pages.media_box[3] / 2.0
pdf.prepress_center_mark(mid_x, ty0, 0, mark_length, bleed_size) # Centre Top
pdf.prepress_center_mark(tx0, mid_y, 90, mark_length, bleed_size) # Centre Left
pdf.prepress_center_mark(mid_x, ty1, 180, mark_length, bleed_size) # Centre Bottom
pdf.prepress_center_mark(tx1, mid_y, -90, mark_length, bleed_size) # Centre Right
pdf.restore_state
pdf.close_object
pdf.add_object(all, :all)
yield pdf if block_given?
pdf
end
# Convert a measurement in centimetres to points, which are the
# default PDF userspace units.
def cm2pts(x)
(x / 2.54) * 72
end
# Convert a measurement in millimetres to points, which are the
# default PDF userspace units.
def mm2pts(x)
(x / 25.4) * 72
end
# Convert a measurement in inches to points, which are the default PDF
# userspace units.
def in2pts(x)
x * 72
end
end
# Convert a measurement in centimetres to points, which are the default
# PDF userspace units.
def cm2pts(x)
PDF::Writer.cm2pts(x)
end
# Convert a measurement in millimetres to points, which are the default
# PDF userspace units.
def mm2pts(x)
PDF::Writer.mm2pts(x)
end
# Convert a measurement in inches to points, which are the default PDF
# userspace units.
def in2pts(x)
PDF::Writer.in2pts(x)
end
# Standard page size names. One of these may be provided to
# PDF::Writer.new as the <tt>:paper</tt> parameter.
#
# Page sizes supported are:
#
# * 4A0, 2A0
# * A0, A1 A2, A3, A4, A5, A6, A7, A8, A9, A10
# * B0, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10
# * C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10
# * RA0, RA1, RA2, RA3, RA4
# * SRA0, SRA1, SRA2, SRA3, SRA4
# * LETTER
# * LEGAL
# * FOLIO
# * EXECUTIVE
PAGE_SIZES = { # :value {...}:
"4A0" => [0, 0, 4767.87, 6740.79], "2A0" => [0, 0, 3370.39, 4767.87],
"A0" => [0, 0, 2383.94, 3370.39], "A1" => [0, 0, 1683.78, 2383.94],
"A2" => [0, 0, 1190.55, 1683.78], "A3" => [0, 0, 841.89, 1190.55],
"A4" => [0, 0, 595.28, 841.89], "A5" => [0, 0, 419.53, 595.28],
"A6" => [0, 0, 297.64, 419.53], "A7" => [0, 0, 209.76, 297.64],
"A8" => [0, 0, 147.40, 209.76], "A9" => [0, 0, 104.88, 147.40],
"A10" => [0, 0, 73.70, 104.88], "B0" => [0, 0, 2834.65, 4008.19],
"B1" => [0, 0, 2004.09, 2834.65], "B2" => [0, 0, 1417.32, 2004.09],
"B3" => [0, 0, 1000.63, 1417.32], "B4" => [0, 0, 708.66, 1000.63],
"B5" => [0, 0, 498.90, 708.66], "B6" => [0, 0, 354.33, 498.90],
"B7" => [0, 0, 249.45, 354.33], "B8" => [0, 0, 175.75, 249.45],
"B9" => [0, 0, 124.72, 175.75], "B10" => [0, 0, 87.87, 124.72],
"C0" => [0, 0, 2599.37, 3676.54], "C1" => [0, 0, 1836.85, 2599.37],
"C2" => [0, 0, 1298.27, 1836.85], "C3" => [0, 0, 918.43, 1298.27],
"C4" => [0, 0, 649.13, 918.43], "C5" => [0, 0, 459.21, 649.13],
"C6" => [0, 0, 323.15, 459.21], "C7" => [0, 0, 229.61, 323.15],
"C8" => [0, 0, 161.57, 229.61], "C9" => [0, 0, 113.39, 161.57],
"C10" => [0, 0, 79.37, 113.39], "RA0" => [0, 0, 2437.80, 3458.27],
"RA1" => [0, 0, 1729.13, 2437.80], "RA2" => [0, 0, 1218.90, 1729.13],
"RA3" => [0, 0, 864.57, 1218.90], "RA4" => [0, 0, 609.45, 864.57],
"SRA0" => [0, 0, 2551.18, 3628.35], "SRA1" => [0, 0, 1814.17, 2551.18],
"SRA2" => [0, 0, 1275.59, 1814.17], "SRA3" => [0, 0, 907.09, 1275.59],
"SRA4" => [0, 0, 637.80, 907.09], "LETTER" => [0, 0, 612.00, 792.00],
"LEGAL" => [0, 0, 612.00, 1008.00], "FOLIO" => [0, 0, 612.00, 936.00],
"EXECUTIVE" => [0, 0, 521.86, 756.00]
}
# Creates a new PDF document as a writing canvas. It accepts three named
# parameters:
#
# <tt>:paper</tt>:: Specifies the size of the default page in
# PDF::Writer. This may be a four-element array
# of coordinates specifying the lower-left
# <tt>(xll, yll)</tt> and upper-right <tt>(xur,
# yur)</tt> corners, a two-element array of
# width and height in centimetres, or a page
# name as defined in PAGE_SIZES.
# <tt>:orientation</tt>:: The orientation of the page, either long
# (:portrait) or wide (:landscape). This may be
# used to swap the width and the height of the
# page.
# <tt>:version</tt>:: The feature set available to the document is
# limited by the PDF version. Setting this
# version restricts the feature set available to
# PDF::Writer. PDF::Writer currently supports
# PDF version 1.3 features and does not yet
# support advanced features from PDF 1.4, 1.5,
# or 1.6.
def initialize(options = {})
paper = options[:paper] || "LETTER"
orientation = options[:orientation] || :portrait
version = options[:version] || PDF_VERSION_13
@mutex = Mutex.new
@current_id = @current_font_id = 0
# Start the document
@objects = []
@callbacks = []
@font_families = {}
@fonts = {}
@stack = []
@state_stack = StateStack.new
@loose_objects = []
@current_text_state = ""
@options = {}
@destinations = {}
@add_loose_objects = {}
@images = []
@word_space_adjust = nil
@current_stroke_style = PDF::Writer::StrokeStyle.new(1)
@page_numbering = nil
@arc4 = nil
@encryption = nil
@file_identifier = nil
@columns = {}
@columns_on = false
@insert_mode = nil
@catalog = PDF::Writer::Object::Catalog.new(self)
@outlines = PDF::Writer::Object::Outlines.new(self)
@pages = PDF::Writer::Object::Pages.new(self)
@current_node = @pages
@procset = PDF::Writer::Object::Procset.new(self)
@info = PDF::Writer::Object::Info.new(self)
@page = PDF::Writer::Object::Page.new(self)
@current_text_render_style = 0
@first_page = @page
@version = version
# Initialize the default font families.
init_font_families
@font_size = 10
@pageset = [@pages.first_page]
if paper.kind_of?(Array)
if paper.size == 4
size = paper # Coordinate Array
else
size = [0, 0, PDF::Writer.cm2pts(paper[0]), PDF::Writer.cm2pts(paper[1])]
# Paper size in centimeters has been passed
end
else
size = PAGE_SIZES[paper.upcase].dup
end
size[3], size[2] = size[2], size[3] if orientation == :landscape
@pages.media_box = size
@page_width = size[2] - size[0]
@page_height = size[3] - size[1]
@y = @page_height
# Also set the margins to some reasonable defaults -- 1.27 cm, 36pt,
# or 0.5 inches.
margins_pt(36)
# Set the current writing position to the top of the first page
@y = absolute_top_margin
# Get the ID of the page that was created during the instantiation
# process.
fill_color! Color::RGB::Black
stroke_color! Color::RGB::Black
yield self if block_given?
end
PDF_VERSION_13 = '1.3'
PDF_VERSION_14 = '1.4'
PDF_VERSION_15 = '1.5'
PDF_VERSION_16 = '1.6'
# The version of PDF to which this document conforms. Should be one of
# PDF_VERSION_13, PDF_VERSION_14, PDF_VERSION_15, or PDF_VERSION_16.
attr_reader :version
# The document catalog object (PDF::Writer::Object::Catalog). The
# options in the catalog should be set with PDF::Writer#open_here,
# PDF::Writer#viewer_preferences, and PDF::Writer#page_mode.
#
# This is of little interest to external clients.
attr_accessor :catalog #:nodoc:
# The PDF::Writer::Object::Pages object. This is of little interest to
# external clients.
attr_accessor :pages #:nodoc:
# The PDF::Writer::Object::Procset object. This is of little interest to
# external clients.
attr_accessor :procset #:nodoc:
# Sets the document to compressed (+true+) or uncompressed (+false+).
# Defaults to uncompressed. This can ONLY be set once and should be set
# as early as possible in the document creation process.
attr_accessor :compressed
def compressed=(cc) #:nodoc:
@compressed = cc if @compressed.nil?
end
# Returns +true+ if the document is compressed.
def compressed?
@compressed == true
end
# The set of known labelled destinations. All destinations are of class
# PDF::Writer::Object::Destination. This is of little interest to
# external clients.
attr_reader :destinations #:nodoc:
# The PDF::Writer::Object::Info info object. This is used to provide
# certain metadata.
attr_reader :info
# The current page for writing. This is of little interest to external
# clients.
attr_accessor :current_page #:nodoc:
# Returns the current contents object to which raw PDF instructions may
# be written.
attr_reader :current_contents
# The PDF::Writer::Object::Outlines object. This is currently used very
# little. This is of little interest to external clients.
attr_reader :outlines #:nodoc:
# The complete set of page objects. This is of little interest to
# external consumers.
attr_reader :pageset #:nodoc:
attr_accessor :left_margin
attr_accessor :right_margin
attr_accessor :top_margin
attr_accessor :bottom_margin
attr_reader :page_width
attr_reader :page_height
# The absolute x position of the left margin.
attr_reader :absolute_left_margin
def absolute_left_margin #:nodoc:
@left_margin
end
# The absolute x position of the right margin.
attr_reader :absolute_right_margin
def absolute_right_margin #:nodoc:
@page_width - @right_margin
end
# Returns the absolute y position of the top margin.
attr_reader :absolute_top_margin
def absolute_top_margin #:nodoc:
@page_height - @top_margin
end
# Returns the absolute y position of the bottom margin.
attr_reader :absolute_bottom_margin
def absolute_bottom_margin #:nodoc:
@bottom_margin
end
# The height of the margin area.
attr_reader :margin_height
def margin_height #:nodoc:
absolute_top_margin - absolute_bottom_margin
end
# The width of the margin area.
attr_reader :margin_width
def margin_width #:nodoc:
absolute_right_margin - absolute_left_margin
end
# The absolute x middle position.
attr_reader :absolute_x_middle
def absolute_x_middle #:nodoc:
@page_width / 2.0
end
# The absolute y middle position.
attr_reader :absolute_y_middle
def absolute_y_middle #:nodoc:
@page_height / 2.0
end
# The middle of the writing area between the left and right margins.
attr_reader :margin_x_middle
def margin_x_middle #:nodoc:
(absolute_right_margin + absolute_left_margin) / 2.0
end
# The middle of the writing area between the top and bottom margins.
attr_reader :margin_y_middle
def margin_y_middle #:nodoc:
(absolute_top_margin + absolute_bottom_margin) / 2.0
end
# The vertical position of the writing point. The vertical position is
# constrained between the top and bottom margins. Any attempt to set it
# outside of those margins will cause the y pointer to be placed
# absolutely at the margins.
attr_accessor :y
def y=(yy) #:nodoc:
@y = yy
@y = absolute_top_margin if @y > absolute_top_margin
@y = @bottom_margin if @y < @bottom_margin
end
# The vertical position of the writing point. If the vertical position
# is outside of the bottom margin, a new page will be created.
attr_accessor :pointer
def pointer=(y) #:nodoc:
@y = y
start_new_page if @y < @bottom_margin
end
# Used to change the vertical position of the writing point. The pointer
# is moved *down* the page by +dy+ (that is, #y is reduced by +dy+), so
# if the pointer is to be moved up, a negative number must be used.
# Moving up the page will not move to the previous page because of
# limitations in the way that PDF::Writer works. The writing point will
# be limited to the top margin position.
#
# If +make_space+ is true and a new page is forced, then the pointer
# will be moved down on the new page. This will allow space to be
# reserved for graphics.
def move_pointer(dy, make_space = false)
@y -= dy
if @y < @bottom_margin
start_new_page
@y -= dy if make_space
elsif @y > absolute_top_margin
@y = absolute_top_margin
end
end
# Define the margins in millimetres.
def margins_mm(top, left = top, bottom = top, right = left)
margins_pt(mm2pts(top), mm2pts(left), mm2pts(bottom), mm2pts(right))
end
# Define the margins in centimetres.
def margins_cm(top, left = top, bottom = top, right = left)
margins_pt(cm2pts(top), cm2pts(left), cm2pts(bottom), cm2pts(right))
end
# Define the margins in inches.
def margins_in(top, left = top, bottom = top, right = left)
margins_pt(in2pts(top), in2pts(left), in2pts(bottom), in2pts(right))
end
# Define the margins in points. This will move the #y pointer
#
# # T L B R
# pdf.margins_pt(36) # 36 36 36 36
# pdf.margins_pt(36, 54) # 36 54 36 54
# pdf.margins_pt(36, 54, 72) # 36 54 72 54
# pdf.margins_pt(36, 54, 72, 90) # 36 54 72 90
def margins_pt(top, left = top, bottom = top, right = left)
# Set the margins to new values
@top_margin = top
@bottom_margin = bottom
@left_margin = left
@right_margin = right
# Check to see if this means that the current writing position is
# outside the writable area
if @y > (@page_height - top)
# Move y down
@y = @page_height - top
end
start_new_page if @y < bottom # Make a new page
end
# Allows the user to find out what the ID is of the first page that was
# created during startup - useful if they wish to add something to it
# later.
attr_reader :first_page
# Add a new translation table for a font family. A font family will be
# used to associate a single name and font styles with multiple fonts.
# A style will be identified with a single-character style identifier or
# a series of style identifiers. The only styles currently recognised
# are:
#
# +b+:: Bold (or heavy) fonts. Examples: Helvetica-Bold, Courier-Bold,
# Times-Bold.
# +i+:: Italic (or oblique) fonts. Examples: Helvetica-Oblique,
# Courier-Oblique, Times-Italic.
# +bi+:: Bold italic fonts. Examples Helvetica-BoldOblique,
# Courier-BoldOblique, Times-BoldItalic.
# +ib+:: Italic bold fonts. Generally defined the same as +bi+ font
# styles. Examples: Helvetica-BoldOblique, Courier-BoldOblique,
# Times-BoldItalic.
#
# Each font family key is the base name for the font.
attr_reader :font_families
# Initialize the font families for the default fonts.
def init_font_families
# Set the known family groups. These font families will be used to
# enable bold and italic markers to be included within text
# streams. HTML forms will be used... <b></b> <i></i>
@font_families["Helvetica"] =
{
"b" => 'Helvetica-Bold',
"i" => 'Helvetica-Oblique',
"bi" => 'Helvetica-BoldOblique',
"ib" => 'Helvetica-BoldOblique'
}
@font_families['Courier'] =
{
"b" => 'Courier-Bold',
"i" => 'Courier-Oblique',
"bi" => 'Courier-BoldOblique',
"ib" => 'Courier-BoldOblique'
}
@font_families['Times-Roman'] =
{
"b" => 'Times-Bold',
"i" => 'Times-Italic',
"bi" => 'Times-BoldItalic',
"ib" => 'Times-BoldItalic'
}
end
private :init_font_families
# Sets the trim box area.
def trim_box(x0, y0, x1, y1)
@pages.trim_box = [ x0, y0, x1, y1 ]
end
# Sets the bleed box area.
def bleed_box(x0, y0, x1, y1)
@pages.bleed_box = [ x0, y0, x1, y1 ]
end
# set the viewer preferences of the document, it is up to the browser to
# obey these.
def viewer_preferences(label, value = 0)
@catalog.viewer_preferences ||= PDF::Writer::Object::ViewerPreferences.new(self)
# This will only work if the label is one of the valid ones.
if label.kind_of?(Hash)
label.each { |kk, vv| @catalog.viewer_preferences.__send__("#{kk.downcase}=".intern, vv) }
else
@catalog.viewer_preferences.__send__("#{label.downcase}=".intern, value)
end
end
# Add a link in the document to an external URL.
def add_link(uri, x0, y0, x1, y1)
PDF::Writer::Object::Annotation.new(self, :link, [x0, y0, x1, y1], uri)
end
# Add a link in the document to an internal destination (ie. within the
# document)
def add_internal_link(label, x0, y0, x1, y1)
PDF::Writer::Object::Annotation.new(self, :ilink, [x0, y0, x1, y1], label)
end
# Add an outline item (Bookmark).
def add_outline_item(label, title = label)
PDF::Writer::Object::Outline.new(self, label, title)
end
# Standard encryption/DRM options.
ENCRYPT_OPTIONS = { #:nodoc:
:print => 4,
:modify => 8,
:copy => 16,
:add => 32
}
# should be used for internal checks, not implemented as yet
def check_all_here
end
# Return the PDF stream as a string.
def render(debug = false)
add_page_numbers
@compression = false if $DEBUG or debug
@arc4.init(@encryption_key) unless @arc4.nil?
check_all_here
xref = []
content = "%PDF-#{@version}\n%\303\242\303\243\303\217\303\223\n"
pos = content.size
objects.each do |oo|
cont = oo.to_s
content << cont
xref << pos
pos += cont.size
end
# pos += 1 # Newline character before XREF
content << "\nxref\n0 #{xref.size + 1}\n0000000000 65535 f \n"
xref.each { |xx| content << "#{'%010d' % [xx]} 00000 n \n" }
content << "\ntrailer\n"
content << " << /Size #{xref.size + 1}\n"
content << " /Root 1 0 R\n /Info #{@info.oid} 0 R\n"
# If encryption has been applied to this document, then add the marker
# for this dictionary
if @arc4 and @encryption
content << "/Encrypt #{@encryption.oid} 0 R\n"
end
if @file_identifier
content << "/ID[<#{@file_identifier}><#{@file_identifier}>]\n"
end
content << " >>\nstartxref\n#{pos}\n%%EOF\n"
content
end
alias :to_s :render
# Loads the font metrics. This is now thread-safe.
def load_font_metrics(font)
metrics = PDF::Writer::FontMetrics.open(font)
@mutex.synchronize do
@fonts[font] = metrics
@fonts[font].font_num = @fonts.size
end
metrics
end
private :load_font_metrics
def find_font(fontname)
name = File.basename(fontname, ".afm")
@objects.detect do |oo|
oo.kind_of?(PDF::Writer::Object::Font) and /#{oo.basefont}$/ =~ name
end
end
private :find_font
def font_file(fontfile)
path = "#{fontfile}.pfb"
return path if File.exists?(path)
path = "#{fontfile}.ttf"
return path if File.exists?(path)
nil
end
private :font_file
def load_font(font, encoding = nil)
metrics = load_font_metrics(font)
name = File.basename(font).gsub(/\.afm$/o, "")
encoding_diff = nil
case encoding
when Hash
encoding_name = encoding[:encoding]
encoding_diff = encoding[:differences]
encoding = PDF::Writer::Object::FontEncoding.new(self, encoding_name, encoding_diff)
when NilClass
encoding_name = encoding = 'WinAnsiEncoding'
else
encoding_name = encoding
end
wfo = PDF::Writer::Object::Font.new(self, name, encoding)
# We have an Adobe Font Metrics (.afm) file. We need to find the
# associated Type1 (.pfb) or TrueType (.ttf) files (we do not yet
# support OpenType fonts); we need to load it into a
# PDF::Writer::Object and put the references into the metrics object.
base = metrics.path.sub(/\.afm$/o, "")
fontfile = font_file(base)
unless fontfile
base = File.basename(base)
FONT_PATH.each do |path|
fontfile = font_file(File.join(path, base))
break if fontfile
end
end
if font =~ /afm/o and fontfile
# Find the array of font widths, and put that into an object.
first_char = -1
last_char = 0
widths = {}
metrics.c.each_value do |details|
num = details["C"]
if num >= 0
# warn "Multiple definitions of #{num}" if widths.has_key?(num)
widths[num] = details['WX']
first_char = num if num < first_char or first_char < 0
last_char = num if num > last_char
end
end
# Adjust the widths for the differences array.
if encoding_diff
encoding_diff.each do |cnum, cname|
(cnum - last_char).times { widths << 0 } if cnum > last_char
last_char = cnum
widths[cnum - first_char] = metrics.c[cname]['WX'] if metrics.c[cname]
end
end
raise RuntimeError, 'Font metrics file (.afm) invalid - no charcters described' if first_char == -1 and last_char == 0
widthid = PDF::Writer::Object::Contents.new(self, :raw)
widthid << "["
(first_char .. last_char).each do |ii|
if widths.has_key?(ii)
widthid << " #{widths[ii].to_i}"
else
widthid << " 0"
end
end
widthid << "]"
# Load the pfb file, and put that into an object too. Note that PDF
# supports only binary format Type1 font files and TrueType font
# files. There is a simple utility to convert Type1 from pfa to pfb.
data = File.open(fontfile, "rb") { |ff| ff.read }
# Create the font descriptor.
fdsc = PDF::Writer::Object::FontDescriptor.new(self)
# Raw contents causes problems with Acrobat Reader.
pfbc = PDF::Writer::Object::Contents.new(self)
# Determine flags (more than a little flakey, hopefully will not
# matter much).
flags = 0
if encoding == "none"
flags += 2 ** 2
else
flags += 2 ** 6 if metrics.italicangle.nonzero?
flags += 2 ** 0 if metrics.isfixedpitch == "true"
flags += 2 ** 5 # Assume a non-symbolic font
end
# 1: FixedPitch: All glyphs have the same width (as opposed to
# proportional or variable-pitch fonts, which have
# different widths).
# 2: Serif: Glyphs have serifs, which are short strokes drawn
# at an angle on the top and bottom of glyph stems.
# (Sans serif fonts do not have serifs.)
# 3: Symbolic Font contains glyphs outside the Adobe standard
# Latin character set. This flag and the Nonsymbolic
# flag cannot both be set or both be clear (see
# below).
# 4: Script: Glyphs resemble cursive handwriting.
# 6: Nonsymbolic: Font uses the Adobe standard Latin character set
# or a subset of it (see below).
# 7: Italic: Glyphs have dominant vertical strokes that are
# slanted.
# 17: AllCap: Font contains no lowercase letters; typically used
# for display purposes, such as for titles or
# headlines.
# 18: SmallCap: Font contains both uppercase and lowercase
# letters. The uppercase letters are similar to
# those in the regular version of the same typeface
# family. The glyphs for the lowercase letters have
# the same shapes as the corresponding uppercase
# letters, but they are sized and their proportions
# adjusted so that they have the same size and
# stroke weight as lowercase glyphs in the same
# typeface family.
# 19: ForceBold: See below.
list = {
'Ascent' => 'Ascender',
'CapHeight' => 'CapHeight',
'Descent' => 'Descender',
'FontBBox' => 'FontBBox',
'ItalicAngle' => 'ItalicAngle'
}
fdopt = {
'Flags' => flags,
'FontName' => metrics.fontname,
'StemV' => 100 # Don't know what the value for this should be!
}
list.each do |kk, vv|
zz = metrics.__send__(vv.downcase.intern)
fdopt[kk] = zz if zz
end
# Determine the cruicial lengths within this file
if fontfile =~ /\.pfb$/o
fdopt['FontFile'] = pfbc.oid
i1 = data.index('eexec') + 6
i2 = data.index('00000000') - i1
i3 = data.size - i2 - i1
pfbc.add('Length1' => i1, 'Length2' => i2, 'Length3' => i3)
elsif fontfile =~ /\.ttf$/o
fdopt['FontFile2'] = pfbc.oid
pfbc.add('Length1' => data.size)
end
fdsc.options = fdopt
# Embed the font program
pfbc << data
# Tell the font object about all this new stuff
tmp = {
'BaseFont' => metrics.fontname,
'Widths' => widthid.oid,
'FirstChar' => first_char,
'LastChar' => last_char,
'FontDescriptor' => fdsc.oid
}
tmp['SubType'] = 'TrueType' if fontfile =~ /\.ttf/
tmp.each { |kk, vv| wfo.__send__("#{kk.downcase}=".intern, vv) }
end
# Also set the differences here. Note that this means that these will
# take effect only the first time that a font is selected, else they
# are ignored.
metrics.differences = encoding_diff unless encoding_diff.nil?
metrics.encoding = encoding_name
metrics
end
private :load_font
# If the named +font+ is not loaded, then load it and make the required
# PDF objects to represent the font. If the font is already loaded, then
# make it the current font.
#
# The parameter +encoding+ applies only when the font is first being
# loaded; it may not be applied later. It may either be an encoding name
# or a hash. The Hash must contain two keys:
#
# <tt>:encoding</tt>:: The name of the encoding. Either *none*,
# *WinAnsiEncoding*, *MacRomanEncoding*, or
# *MacExpertEncoding*. For symbolic fonts, an
# encoding of *none* is recommended with a
# differences Hash.
# <tt>:differences</tt>:: This Hash value is a mapping between character
# byte values (0 .. 255) and character names
# from the AFM file for the font.
#
# The standard PDF encodings are detailed fully in the PDF Reference
# version 1.6, Appendix D.
#
# Note that WinAnsiEncoding is not the same as Windows code page 1252
# (roughly equivalent to latin-1), Most characters map, but not all. The
# encoding value currently defaults to WinAnsiEncoding.
#
# If the font's "natural" encoding is desired, then it is necessary to
# specify the +encoding+ parameter as <tt>{ :encoding => nil }</tt>.
def select_font(font, encoding = nil)
load_font(font, encoding) unless @fonts[font]
@current_base_font = font
current_font!
@current_base_font
end
# Selects the current font based on defined font families and the
# current text state. As noted in #font_families, a "bi" font can be
# defined differently than an "ib" font. It should not be possible to
# have a "bb" text state, but if one were to show up, an entry for the
# #font_families would have to be defined to select anything other than
# the default font. This function is to be called whenever the current
# text state is changed; it will update the current font to whatever the
# appropriate font defined in the font family.
#
# When the user calls #select_font, both the current base font and the
# current font will be reset; this function only changes the current
# font, not the current base font.
#
# This will probably not be needed by end users.
def current_font!
select_font("Helvetica") unless @current_base_font