/
xobject.rb
918 lines (730 loc) · 31.8 KB
/
xobject.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
=begin
This file is part of Origami, PDF manipulation framework for Ruby
Copyright (C) 2016 Guillaume Delugré.
Origami is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Origami is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Origami. If not, see <http://www.gnu.org/licenses/>.
=end
module Origami
#
# A class representing a Stream containing the contents of a Page.
#
class ContentStream < Stream
DEFAULT_SIZE = 12
DEFAULT_FONT = :F1
DEFAULT_LEADING = 20
DEFAULT_STROKE_COLOR = Graphics::Color::GrayScale.new(0.0)
DEFAULT_FILL_COLOR = Graphics::Color::GrayScale.new(1.0)
DEFAULT_LINECAP = Graphics::LineCapStyle::BUTT_CAP
DEFAULT_LINEJOIN = Graphics::LineJoinStyle::MITER_JOIN
DEFAULT_DASHPATTERN = Graphics::DashPattern.new([], 0)
DEFAULT_LINEWIDTH = 1.0
attr_accessor :canvas
def initialize(data = "", dictionary = {})
super
@instructions = nil
@canvas = Graphics::DummyCanvas.new
end
def render(engine)
load!
@instructions.each do |instruction|
instruction.render(engine)
end
nil
end
def pre_build #:nodoc:
unless @instructions.nil?
if @canvas.gs.text_state.is_in_text_object?
@instructions << PDF::Instruction.new('ET').render(@canvas)
end
@data = @instructions.join
end
super
end
def instructions
load!
@instructions
end
def draw_image(name, attr = {})
load!
x, y = attr[:x], attr[:y]
@instructions << PDF::Instruction.new('q')
@instructions << PDF::Instruction.new('cm', 300, 0, 0, 300, x, y)
@instructions << PDF::Instruction.new('Do', name)
@instructions << PDF::Instruction.new('Q')
end
#
# Draw a straight line from the point at coord _from_, to the point at coord _to_.
#
def draw_line(from, to, attr = {})
draw_polygon([from, to], attr)
end
#
# Draw a polygon from a array of coordinates.
#
def draw_polygon(coords = [], attr = {})
load!
stroke_color = attr.fetch(:stroke_color, DEFAULT_STROKE_COLOR)
fill_color = attr.fetch(:fill_color, DEFAULT_FILL_COLOR)
line_cap = attr.fetch(:line_cap, DEFAULT_LINECAP)
line_join = attr.fetch(:line_join, DEFAULT_LINEJOIN)
line_width = attr.fetch(:line_width, DEFAULT_LINEWIDTH)
dash_pattern = attr.fetch(:dash, DEFAULT_DASHPATTERN)
stroke = attr[:stroke].nil? ? true : attr[:stroke]
fill = attr[:fill].nil? ? false : attr[:fill]
stroke = true if fill == false and stroke == false
set_fill_color(fill_color) if fill
set_stroke_color(stroke_color) if stroke
set_line_width(line_width)
set_line_cap(line_cap)
set_line_join(line_join)
set_dash_pattern(dash_pattern)
if @canvas.gs.text_state.is_in_text_object?
@instructions << PDF::Instruction.new('ET').render(@canvas)
end
unless coords.size < 1
x,y = coords.slice!(0)
@instructions << PDF::Instruction.new('m',x,y).render(@canvas)
coords.each do |px,py|
@instructions << PDF::Instruction.new('l',px,py).render(@canvas)
end
@instructions << (i =
if stroke and not fill
PDF::Instruction.new('s')
elsif fill and not stroke
PDF::Instruction.new('f')
elsif fill and stroke
PDF::Instruction.new('b')
end
)
i.render(@canvas)
end
self
end
#
# Draw a rectangle at position (_x_,_y_) with defined _width_ and _height_.
#
def draw_rectangle(x, y, width, height, attr = {})
load!
stroke_color = attr.fetch(:stroke_color, DEFAULT_STROKE_COLOR)
fill_color = attr.fetch(:fill_color, DEFAULT_FILL_COLOR)
line_cap = attr.fetch(:line_cap, DEFAULT_LINECAP)
line_join = attr.fetch(:line_join, DEFAULT_LINEJOIN)
line_width = attr.fetch(:line_width, DEFAULT_LINEWIDTH)
dash_pattern = attr.fetch(:dash, DEFAULT_DASHPATTERN)
stroke = attr[:stroke].nil? ? true : attr[:stroke]
fill = attr[:fill].nil? ? false : attr[:fill]
stroke = true if fill == false and stroke == false
set_fill_color(fill_color) if fill
set_stroke_color(stroke_color) if stroke
set_line_width(line_width)
set_line_cap(line_cap)
set_line_join(line_join)
set_dash_pattern(dash_pattern)
if @canvas.gs.text_state.is_in_text_object?
@instructions << PDF::Instruction.new('ET').render(@canvas)
end
@instructions << PDF::Instruction.new('re', x,y,width,height).render(@canvas)
@instructions << (i =
if stroke and not fill
PDF::Instruction.new('S')
elsif fill and not stroke
PDF::Instruction.new('f')
elsif fill and stroke
PDF::Instruction.new('B')
end
)
i.render(@canvas)
self
end
#
# Adds text to the content stream with custom formatting attributes.
# _text_:: Text to write.
# _attr_:: Formatting attributes.
#
def write(text, attr = {})
load!
x, y = attr[:x], attr[:y]
font = attr.fetch(:font, DEFAULT_FONT)
size = attr.fetch(:size, DEFAULT_SIZE)
leading = attr.fetch(:leading, DEFAULT_LEADING)
color = attr.fetch(:color, attr.fetch(:fill_color, DEFAULT_STROKE_COLOR))
stroke_color = attr.fetch(:stroke_color, DEFAULT_STROKE_COLOR)
line_width = attr.fetch(:line_width, DEFAULT_LINEWIDTH)
word_spacing = attr.fetch(:word_spacing, @canvas.gs.text_state.word_spacing)
char_spacing = attr.fetch(:char_spacing, @canvas.gs.text_state.char_spacing)
scale = attr.fetch(:scale, @canvas.gs.text_state.scaling)
rise = attr.fetch(:rise, @canvas.gs.text_state.text_rise)
rendering = attr.fetch(:rendering, @canvas.gs.text_state.rendering_mode)
@instructions << PDF::Instruction.new('ET').render(@canvas) if (x or y) and @canvas.gs.text_state.is_in_text_object?
unless @canvas.gs.text_state.is_in_text_object?
@instructions << PDF::Instruction.new('BT').render(@canvas)
end
set_text_font(font, size)
set_text_pos(x, y) if x or y
set_text_leading(leading)
set_text_rendering(rendering)
set_text_rise(rise)
set_text_scale(scale)
set_text_word_spacing(word_spacing)
set_text_char_spacing(char_spacing)
set_fill_color(color)
set_stroke_color(stroke_color)
set_line_width(line_width)
write_text_block(text)
self
end
def paint_shading(shade)
load!
@instructions << PDF::Instruction.new('sh', shade).render(@canvas)
self
end
def set_text_font(fontname, size)
load!
if fontname != @canvas.gs.text_state.font or size != @canvas.gs.text_state.font_size
@instructions << PDF::Instruction.new('Tf', fontname, size).render(@canvas)
end
self
end
def set_text_pos(tx,ty)
load!
@instructions << PDF::Instruction.new('Td', tx, ty).render(@canvas)
self
end
def set_text_leading(leading)
load!
if leading != @canvas.gs.text_state.leading
@instructions << PDF::Instruction.new('TL', leading).render(@canvas)
end
self
end
def set_text_rendering(rendering)
load!
if rendering != @canvas.gs.text_state.rendering_mode
@instructions << PDF::Instruction.new('Tr', rendering).render(@canvas)
end
self
end
def set_text_rise(rise)
load!
if rise != @canvas.gs.text_state.text_rise
@instructions << PDF::Instruction.new('Ts', rise).render(@canvas)
end
self
end
def set_text_scale(scaling)
load!
if scaling != @canvas.gs.text_state.scaling
@instructions << PDF::Instruction.new('Tz', scaling).render(@canvas)
end
self
end
def set_text_word_spacing(word_spacing)
load!
if word_spacing != @canvas.gs.text_state.word_spacing
@instructions << PDF::Instruction.new('Tw', word_spacing).render(@canvas)
end
self
end
def set_text_char_spacing(char_spacing)
load!
if char_spacing != @canvas.gs.text_state.char_spacing
@instructions << PDF::Instruction.new('Tc', char_spacing).render(@canvas)
end
self
end
def set_fill_color(color)
load!
@instructions << ( i =
if (color.respond_to? :r and color.respond_to? :g and color.respond_to? :b) or (color.is_a?(::Array) and color.size == 3)
r = (color.respond_to?(:r) ? color.r : color[0]).to_f / 255
g = (color.respond_to?(:g) ? color.g : color[1]).to_f / 255
b = (color.respond_to?(:b) ? color.b : color[2]).to_f / 255
PDF::Instruction.new('rg', r, g, b) if @canvas.gs.nonstroking_color != [r,g,b]
elsif (color.respond_to? :c and color.respond_to? :m and color.respond_to? :y and color.respond_to? :k) or (color.is_a?(::Array) and color.size == 4)
c = (color.respond_to?(:c) ? color.c : color[0]).to_f
m = (color.respond_to?(:m) ? color.m : color[1]).to_f
y = (color.respond_to?(:y) ? color.y : color[2]).to_f
k = (color.respond_to?(:k) ? color.k : color[3]).to_f
PDF::Instruction.new('k', c, m, y, k) if @canvas.gs.nonstroking_color != [c,m,y,k]
elsif color.respond_to?:g or (0.0..1.0) === color
g = color.respond_to?(:g) ? color.g : color
PDF::Instruction.new('g', g) if @canvas.gs.nonstroking_color != [ g ]
else
raise TypeError, "Invalid color : #{color}"
end
)
i.render(@canvas) if i
self
end
def set_stroke_color(color)
load!
@instructions << ( i =
if (color.respond_to? :r and color.respond_to? :g and color.respond_to? :b) or (color.is_a?(::Array) and color.size == 3)
r = (color.respond_to?(:r) ? color.r : color[0]).to_f / 255
g = (color.respond_to?(:g) ? color.g : color[1]).to_f / 255
b = (color.respond_to?(:b) ? color.b : color[2]).to_f / 255
PDF::Instruction.new('RG', r, g, b) if @canvas.gs.stroking_color != [r,g,b]
elsif (color.respond_to? :c and color.respond_to? :m and color.respond_to? :y and color.respond_to? :k) or (color.is_a?(::Array) and color.size == 4)
c = (color.respond_to?(:c) ? color.c : color[0]).to_f
m = (color.respond_to?(:m) ? color.m : color[1]).to_f
y = (color.respond_to?(:y) ? color.y : color[2]).to_f
k = (color.respond_to?(:k) ? color.k : color[3]).to_f
PDF::Instruction.new('K', c, m, y, k) if @canvas.gs.stroking_color != [c,m,y,k]
elsif color.respond_to?:g or (0.0..1.0) === color
g = color.respond_to?(:g) ? color.g : color
PDF::Instruction.new('G', g) if @canvas.gs.stroking_color != [ g ]
else
raise TypeError, "Invalid color : #{color}"
end
)
i.render(@canvas) if i
self
end
def set_dash_pattern(pattern)
load!
unless @canvas.gs.dash_pattern.eql? pattern
@instructions << PDF::Instruction.new('d', pattern.array, pattern.phase).render(@canvas)
end
self
end
def set_line_width(width)
load!
if @canvas.gs.line_width != width
@instructions << PDF::Instruction.new('w', width).render(@canvas)
end
self
end
def set_line_cap(cap)
load!
if @canvas.gs.line_cap != cap
@instructions << PDF::Instruction.new('J', cap).render(@canvas)
end
self
end
def set_line_join(join)
load!
if @canvas.gs.line_join != join
@instructions << PDF::Instruction.new('j', join).render(@canvas)
end
self
end
private
def load!
return unless @instructions.nil?
decode!
code = StringScanner.new self.data
@instructions = []
until code.eos?
insn = PDF::Instruction.parse(code)
@instructions << insn if insn
end
self
end
def write_text_block(text)
lines = text.split("\n").map!{|line| line.to_s}
@instructions << PDF::Instruction.new('Tj', lines.slice!(0)).render(@canvas)
lines.each do |line|
@instructions << PDF::Instruction.new("'", line).render(@canvas)
end
end
end #class ContentStream
class Page < Dictionary
def render(engine) #:nodoc:
contents = self.Contents
contents = [ contents ] unless contents.is_a? Array
contents.each do |stream|
stream = stream.cast_to(ContentStream) unless stream.is_a? ContentStream
stream.render(engine)
end
end
# TODO :nodoc:
def draw_image
raise NotImplementedError
end
# See ContentStream#draw_line.
def draw_line(from, to, attr = {})
last_content_stream.draw_line(from, to, attr); self
end
# See ContentStream#draw_polygon.
def draw_polygon(coords = [], attr = {})
last_content_stream.draw_polygon(coords, attr); self
end
# See ContentStream#draw_rectangle.
def draw_rectangle(x, y, width, height, attr = {})
last_content_stream.draw_rectangle(x, y, width, height, attr); self
end
# See ContentStream#write.
def write(text, attr = {})
last_content_stream.write(text, attr); self
end
# TODO :nodoc:
def paint_shading(_shade)
raise NotImplementedError
end
# TODO :nodoc:
def set_text_font(_font, _size)
raise NotImplementedError
end
# See ContentStream#set_text_pos.
def set_text_pos(tx, ty)
last_content_stream.set_text_pos(tx, ty); self
end
# See ContentStream#set_text_leading.
def set_text_leading(leading)
last_content_stream.set_text_leading(leading); self
end
# See ContentStream#set_text_rendering.
def set_text_rendering(rendering)
last_content_stream.set_text_rendering(rendering); self
end
# See ContentStream#set_text_rise.
def set_text_rise(rise)
last_content_stream.set_text_rise(rise); self
end
# See ContentStream#set_text_scale.
def set_text_scale(scaling)
last_content_stream.set_text_scale(scaling); self
end
# See ContentStream#set_text_word_spacing.
def set_text_word_spacing(word_spacing)
last_content_stream.set_text_word_spacing(word_spacing); self
end
# See ContentStream#set_text_char_spacing.
def set_text_char_spacing(char_spacing)
last_content_stream.set_text_char_spacing(char_spacing); self
end
# See ContentStream#set_fill_color.
def set_fill_color(color)
last_content_stream.set_fill_color(color); self
end
# See ContentStream#set_stroke_color.
def set_stroke_color(color)
last_content_stream.set_stroke_color(color); self
end
# See ContentStream#set_dash_pattern.
def set_dash_pattern(pattern)
last_content_stream.set_dash_pattern(pattern); self
end
# See ContentStream#set_line_width.
def set_line_width(width)
last_content_stream.set_line_width(width); self
end
# See ContentStream#set_line_cap.
def set_line_cap(cap)
last_content_stream.set_line_cap(cap); self
end
# See ContentStream#set_line_join.
def set_line_join(join)
last_content_stream.set_line_join(join); self
end
private
def last_content_stream #:nodoc:
streams = self.content_streams
if streams.empty?
self.Contents = ContentStream.new
else
streams.last
end
end
end # class Page
module Graphics
module XObject
def self.included(receiver)
receiver.field :Type, :Type => Name, :Default => :XObject
end
end
class FormXObject < ContentStream
include XObject
include ResourcesHolder
class Group < Dictionary
include StandardObject
module Type
TRANSPARENCY = :Transparency
end
field :Type, :Type => Name, :Default => :Group
field :S, :Type => Name, :Default => Type::TRANSPARENCY, :Required => true
end
class Reference < Dictionary
include StandardObject
field :F, :Type => FileSpec, :Required => true
field :Page, :Type => [ Integer, String ], :Required => true
field :ID, :Type => Array.of(String, length: 2)
end
field :Subtype, :Type => Name, :Default => :Form, :Required => true
field :FormType, :Type => Integer, :Default => 1
field :BBox, :Type => Rectangle, :Required => true
field :Matrix, :Type => Array.of(Number, length: 6), :Default => [1, 0, 0, 1, 0, 0]
field :Resources, :Type => Resources, :Version => "1.2"
field :Group, :Type => Group, :Version => "1.4"
field :Ref, :Type => Reference, :Version => "1.4"
field :Metadata, :Type => MetadataStream, :Version => "1.4"
field :PieceInfo, :Type => Dictionary, :Version => "1.3"
field :LastModified, :Type => String, :Version => "1.3"
field :StructParent, :Type => Integer, :Version => "1.3"
field :StructParents, :Type => Integer, :Version => "1.3"
field :OPI, :Type => Dictionary, :Version => "1.2"
field :OC, :Type => Dictionary, :Version => "1.5"
field :Name, :Type => Name
field :Measure, :Type => Dictionary, :Version => "1.7", :ExtensionLevel => 3
field :PtData, :Type => Dictionary, :Version => "1.7", :ExtensionLevel => 3
def pre_build
self.Resources = Resources.new.pre_build unless self.key?(:Resources)
super
end
end
class ImageXObject < Stream
include XObject
field :Subtype, :Type => Name, :Default => :Image, :Required => true
field :Width, :Type => Integer, :Required => true
field :Height, :Type => Integer, :Required => true
field :ColorSpace, :Type => [ Name, Array ]
field :BitsPerComponent, :Type => Integer
field :Intent, :Type => Name, :Version => "1.1"
field :ImageMask, :Type => Boolean, :Default => false
field :Mask, :Type => [ ImageXObject, Array.of(Integer) ], :Version => "1.3"
field :Decode, :Type => Array.of(Number)
field :Interpolate, :Type => Boolean, :Default => false
field :Alternates, :Type => Array, :Version => "1.3"
field :SMask, :Type => ImageXObject, :Version => "1.4"
field :SMaskInData, :Type => Integer, :Default => 0, :Version => "1.5"
field :Name, :Type => Name
field :StructParent, :Type => Integer, :Version => "1.3"
field :ID, :Type => String, :Version => "1.3"
field :OPI, :Type => Dictionary, :Version => "1.2"
field :Matte, :Type => Array.of(Number), :Version => "1.4" # Used in Soft-Mask images.
field :Metadata, :Type => MetadataStream, :Version => "1.4"
field :OC, :Type => Dictionary, :Version => "1.5"
field :Measure, :Type => Dictionary, :Version => "1.7", :ExtensionLevel => 3
field :PtData, :Type => Dictionary, :Version => "1.7", :ExtensionLevel => 3
def self.from_image_file(path, format = nil)
if path.respond_to?(:read)
data = fd.read
else
data = File.binread(File.expand_path(path))
format ||= File.extname(path)
end
image = ImageXObject.new
raise ArgumentError, "Missing file format" if format.nil?
case format.downcase
when 'jpg', 'jpeg', 'jpe', 'jif', 'jfif', 'jfi'
image.setFilter :DCTDecode
image.encoded_data = data
when 'jp2','jpx','j2k','jpf','jpm','mj2'
image.setFilter :JPXDecode
image.encoded_data = data
when 'jb2', 'jbig', 'jbig2'
image.setFilter :JBIG2Decode
image.encoded_data = data
else
raise NotImplementedError, "Unknown file format: '#{format}'"
end
image
end
#
# Converts an ImageXObject stream into an image file data.
# Output format depends on the stream encoding:
# * JPEG for DCTDecode
# * JPEG2000 for JPXDecode
# * JBIG2 for JBIG2Decode
# * PNG for everything else
#
# Returns an array of the form [ _format_, _data_ ]
#
def to_image_file
encoding = self.Filter
encoding = encoding[0] if encoding.is_a? ::Array
case (encoding && encoding.value)
when :DCTDecode then return [ 'jpg', self.data ]
when :JBIG2Decode then return [ 'jbig2', self.data ]
when :JPXDecode then return [ 'jp2', self.data ]
end
# Assume PNG data.
raise InvalidColorError, "No colorspace specified" unless self.ColorSpace
case cs = self.ColorSpace.value
when Color::Space::DEVICE_GRAY
color_type = 0
components = 1
when Color::Space::DEVICE_RGB
color_type = 2
components = 3
when ::Array
cs_type = cs[0]
case cs_type
when :Indexed
color_type = 3
components = 3
cs_base = cs[1]
lookup = cs[3]
when :ICCBased
icc_profile = cs[1]
raise InvalidColorError,
"Invalid ICC Profile parameter" unless icc_profile.is_a?(Stream)
case icc_profile.N
when 1
color_type = 0
components = 1
when 3
color_type = 2
components = 3
else
raise InvalidColorError,
"Invalid number of components in ICC profile: #{icc_profile.N}"
end
else
raise InvalidColorError, "Unsupported color space: #{self.ColorSpace}"
end
else
raise InvalidColorError, "Unsupported color space: #{self.ColorSpace}"
end
bpc = self.BitsPerComponent || 8
w, h = self.Width, self.Height
pixels = self.data
hdr = [137, 80, 78, 71, 13, 10, 26, 10].pack('C*')
chunks = []
chunks <<
[
'IHDR',
[
w, h,
bpc, color_type, 0, 0, 0
].pack("N2C5")
]
if self.Intents
intents =
case self.Intents.value
when Intents::PERCEPTUAL then 0
when Intents::RELATIVE then 1
when Intents::SATURATION then 2
when Intents::ABSOLUTE then 3
else
3
end
chunks <<
[
'sRGB',
[ intents ].pack('C')
]
chunks << [ 'gAMA', [ 45455 ].pack("N") ]
chunks <<
[
'cHRM',
[
31270,
32900,
64000,
33000,
30000,
60000,
15000,
6000
].pack("N8")
]
end
if color_type == 3
lookup =
case lookup
when Stream then lookup.data
when String then lookup.value
else
raise InvalidColorError, "Invalid indexed palette table"
end
raise InvalidColorError, "Invalid base color space" unless cs_base
palette = ""
case cs_base
when Color::Space::DEVICE_GRAY
lookup.each_byte do |g|
palette << Color.gray_to_rgb(g).pack("C3")
end
when Color::Space::DEVICE_RGB
palette << lookup[0, (lookup.size / 3) * 3]
when Color::Space::DEVICE_CMYK
(lookup.size / 4).times do |i|
cmyk = lookup[i * 4, 4].unpack("C4").map!{|c| c.to_f / 255}
palette << Color.cmyk_to_rgb(*cmyk).map!{|c| (c * 255).to_i}.pack("C3")
end
when ::Array
case cs_base[0]
when :ICCBased
icc_profile = cs_base[1]
raise InvalidColorError,
"Invalid ICC Profile parameter" unless icc_profile.is_a?(Stream)
case icc_profile.N
when 1
lookup.each_byte do |g|
palette << Color.gray_to_rgb(g).pack("C3")
end
when 3
palette << lookup[0, (lookup.size / 3) * 3]
else
raise InvalidColorError,
"Invalid number of components in ICC profile: #{icc_profile.N}"
end
else
raise InvalidColorError, "Unsupported color space: #{cs_base}"
end
else
raise InvalidColorError, "Unsupported color space: #{cs_base}"
end
if icc_profile
chunks <<
[
'iCCP',
'ICC Profile' + "\x00\x00" + Zlib::Deflate.deflate(icc_profile.data, Zlib::BEST_COMPRESSION)
]
end
chunks <<
[
'PLTE',
palette
]
bpr = w
else # color_type != 3
if icc_profile
chunks <<
[
'iCCP',
'ICC Profile' + "\x00\x00" + Zlib::Deflate.deflate(icc_profile.data, Zlib::BEST_COMPRESSION)
]
end
bpr = (bpc >> 3) * components * w
end
nrows = pixels.size / bpr
nrows.times do |irow|
pixels.insert(irow * bpr + irow, "\x00")
end
chunks <<
[
'IDAT',
Zlib::Deflate.deflate(pixels, Zlib::BEST_COMPRESSION)
]
if self.Metadata.is_a?(Stream)
chunks <<
[
'tEXt',
"XML:com.adobe.xmp" + "\x00" + self.Metadata.data
]
end
chunks << [ 'IEND', '' ]
[ 'png',
hdr + chunks.map!{ |chk|
[ chk[1].size, chk[0], chk[1], Zlib.crc32(chk[0] + chk[1]) ].pack("NA4A*N")
}.join
]
end
end
class ReferenceDictionary < Dictionary
include StandardObject
field :F, :Type => Dictionary, :Required => true
field :Page, :Type => [Integer, String], :Required => true
field :ID, :Tyoe => Array
end
end
end