gamba 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ # A page of a PDF written elsewhere, drawn like an image: a form XObject showing what a viewer shows of it, its
5
+ # crop box turned by its /Rotate. Placed many times, it is written once; pages of one file share their resources.
6
+ class ImportedPage < Prawn::Images::Image
7
+ include PageBoxes
8
+
9
+ # A file read once per document, its objects copied into it as its pages are used.
10
+ Source = Struct.new(:reader, :copier, :pages)
11
+ # Fonts whose glyphs need no font file: their procedures are in the PDF.
12
+ FONT_PROGRAMS = %i[FontFile FontFile2 FontFile3].freeze
13
+ TYPE3 = PDF::Core::Name.new(value: "Type3")
14
+ FORM = PDF::Core::Name.new(value: "Form")
15
+ MARKED_CONTENT_OPERATOR = %r{(?:\A|[\x00\t\n\f\r >])(?:BDC|BMC)(?:\z|[\x00\t\n\f\r ()<>\[\]{}/%])}
16
+
17
+ attr_reader :width, :height, :form
18
+
19
+ # source: a path, an IO, the bytes of a PDF, or anything answering download, as Active Storage attachments do.
20
+ def self.bytes(source)
21
+ if source.respond_to?(:download) && !source.respond_to?(:read)
22
+ source.download.b
23
+ elsif source.respond_to?(:read)
24
+ source.rewind if source.respond_to?(:rewind)
25
+ source.read.b
26
+ elsif source.is_a?(String) && source.b.start_with?("%PDF-")
27
+ source.b
28
+ else
29
+ path = Pathname.new(source)
30
+ raise ArgumentError, "#{path} not found" unless path.file?
31
+
32
+ path.binread
33
+ end
34
+ end
35
+
36
+ def self.source(document, bytes)
37
+ reader = PDF::Core::Reader.new(bytes)
38
+ document.min_version(reader.version)
39
+ Source.new(reader, Copier.new(reader) { document.ref!(_1) }, reader.pages)
40
+ end
41
+
42
+ def initialize(document, source, number)
43
+ super()
44
+ @reader = source.reader
45
+ raise Prawn::Errors::MalformedPDF, "This PDF has no pages" if source.pages.empty?
46
+ unless number.is_a?(Integer) && number.between?(1, source.pages.size)
47
+ raise ArgumentError, "page is #{number.inspect}: this PDF has pages 1 to #{source.pages.size}"
48
+ end
49
+
50
+ page = source.pages[number - 1].last
51
+ if document.pdf_a? || document.pdf_ua?
52
+ # PDF/A and PDF/UA both embed every font; PDF/UA names the error when both apply, as everywhere else.
53
+ @embedding_violation = document.pdf_ua? ? [Prawn::Errors::PdfUaViolation, "PDF/UA"] : [Prawn::Errors::PdfAViolation, "PDF/A"]
54
+ check_fonts_embedded(page[:Resources], {})
55
+ end
56
+ check_no_marked_content(page[:Contents], document) if document.tagged?
57
+ @form = document.ref!(form_dictionary(page, source.copier))
58
+ @form.stream, filters = content(page[:Contents], source.copier)
59
+ @form.data.merge!(filters)
60
+ source.copier.finish
61
+ end
62
+
63
+ # What draws the page in a box of this width and height, from its lower left corner.
64
+ def placement(width, height, x, y)
65
+ [width / @width.to_f, 0, 0, height / @height.to_f, x, y]
66
+ end
67
+
68
+ private
69
+
70
+ # The form maps the visible box, turned, onto a box from the origin as wide and high as the page is shown.
71
+ def form_dictionary(page, copier)
72
+ left, bottom, right, top = visible_box(page)
73
+ width = right - left
74
+ height = top - bottom
75
+ turn = rotation(page)
76
+ @width, @height = (turn % 180).zero? ? [width, height] : [height, width]
77
+ matrix = [1.0, 0.0, 0.0, 1.0, -left, -bottom]
78
+ matrix = multiply(matrix, ROTATIONS.fetch(turn).call(width, height)) unless turn.zero?
79
+ dictionary = {Type: :XObject, Subtype: :Form, BBox: [left, bottom, right, top], Matrix: matrix, Resources: copier.copy(page[:Resources] || {})}
80
+ dictionary[:Group] = copier.copy(page[:Group]) if page[:Group]
81
+ dictionary
82
+ end
83
+
84
+ # A form holds one stream: a page's only content stream keeps its bytes and filters, several are decoded and
85
+ # joined, as their division may fall between an operator and its operands.
86
+ def content(value, copier)
87
+ streams = Array(@reader.resolve(value)).map { @reader.resolve(_1) }.grep(PDF::Core::Reader::Stream)
88
+ return [+" ", {}] if streams.empty?
89
+ return [+streams.first.data, copier.copy(streams.first.dictionary.slice(:Filter, :DecodeParms))] if streams.one?
90
+
91
+ [streams.map { @reader.decoded(_1) }.join("\n"), {}]
92
+ end
93
+
94
+ # The page is drawn as one figure or artifact: marked content of its own would nest in it, which tagged PDF
95
+ # forbids, and its MCIDs would point at a structure tree left behind. The operator follows whitespace or the >> of
96
+ # its properties, and comes before whitespace, a delimiter or the end: /P<</MCID 0>>BDC(a)Tj is written too.
97
+ def check_no_marked_content(contents, document)
98
+ streams = Array(@reader.resolve(contents)).map { @reader.resolve(_1) }.grep(PDF::Core::Reader::Stream)
99
+ return unless streams.any? { @reader.decoded(_1).match?(MARKED_CONTENT_OPERATOR) }
100
+
101
+ error, standard = document.pdf_ua? ? [Prawn::Errors::PdfUaViolation, "PDF/UA"] : [Prawn::Errors::PdfAViolation, "PDF/A-3a"]
102
+ raise error, "#{standard} cannot import a page that has marked content of its own, a page of a tagged PDF: Gamba does not merge structure trees yet"
103
+ end
104
+
105
+ # PDF/A wants every font's program in the file: a page that leaves one to the viewer raises.
106
+ def check_fonts_embedded(resources, visited)
107
+ resources = @reader.resolve(resources)
108
+ return unless resources.is_a?(Hash)
109
+
110
+ fonts = @reader.resolve(resources[:Font])
111
+ fonts.each_value { |font| check_font_embedded(@reader.resolve(font)) } if fonts.is_a?(Hash)
112
+ xobjects = @reader.resolve(resources[:XObject])
113
+ return unless xobjects.is_a?(Hash)
114
+
115
+ xobjects.each_value do |reference|
116
+ next if !reference.is_a?(PDF::Core::Reader::Ref) || visited[reference.number]
117
+
118
+ visited[reference.number] = true
119
+ xobject = @reader.resolve(reference)
120
+ check_fonts_embedded(xobject.dictionary[:Resources], visited) if xobject.is_a?(PDF::Core::Reader::Stream) && xobject.dictionary[:Subtype] == FORM
121
+ end
122
+ end
123
+
124
+ def check_font_embedded(font)
125
+ return unless font.is_a?(Hash) && font[:Subtype] != TYPE3
126
+
127
+ descendant = @reader.resolve(@reader.resolve(font[:DescendantFonts]).then { _1.is_a?(Array) ? _1.first : nil })
128
+ font = descendant if descendant.is_a?(Hash)
129
+ descriptor = @reader.resolve(font[:FontDescriptor])
130
+ return if descriptor.is_a?(Hash) && FONT_PROGRAMS.any? { descriptor[_1] }
131
+
132
+ name = @reader.resolve(font[:BaseFont])
133
+ error, standard = @embedding_violation
134
+ raise error, "#{standard} embeds every font: the page uses #{name.respond_to?(:value) ? name.value : "a font"} without its font file"
135
+ end
136
+ end
137
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "gamba/testing"
4
+
5
+ module Gamba
6
+ # require "gamba/minitest": assertions on PDFs, as bytes or a file's path, in every Minitest::Test.
7
+ module Minitest
8
+ def assert_pdf_text(pdf, text, page: nil, at: nil)
9
+ gamba_check { Gamba::Testing.text_failure(pdf, text, page:, at:) }
10
+ end
11
+
12
+ def assert_same_pages(expected, actual)
13
+ gamba_check { Gamba::Testing.pages_failure(expected, actual) }
14
+ end
15
+
16
+ def assert_valid_pdf(pdf)
17
+ gamba_check { Gamba::Testing.validity_failure(pdf) }
18
+ end
19
+
20
+ def assert_pdf_a(pdf, flavour: "3b")
21
+ gamba_check { Gamba::Testing.pdf_a_failure(pdf, flavour:) }
22
+ end
23
+
24
+ private
25
+
26
+ def gamba_check
27
+ failure = yield
28
+ assert failure.nil?, failure
29
+ rescue Gamba::PdfCheck::ToolMissing => error
30
+ (Gamba::Testing.missing_tools == :skip) ? skip(error.message) : flunk(error.message)
31
+ end
32
+ end
33
+ end
34
+
35
+ Minitest::Test.include(Gamba::Minitest) if defined?(Minitest::Test)
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ module Layout
5
+ # What a header or a footer block knows of the page it is drawn on.
6
+ Page = Data.define(:number, :total)
7
+
8
+ # A header or a footer: a stack built again for each page once the document knows how many it has, drawn in
9
+ # room taken from the page's margin box so the body never runs under it.
10
+ class Band
11
+ EDGES = {header: :top, footer: :bottom}.freeze
12
+
13
+ def initialize(prawn, styles, name, gap, block)
14
+ @prawn = prawn
15
+ @styles = styles
16
+ @name = name
17
+ @gap = gap
18
+ @block = block
19
+ end
20
+
21
+ # The room is the height the band has on the page it is declared on; it is kept on the pages that follow.
22
+ def reserve
23
+ first_page = @prawn.page_number
24
+ @height = stack(first_page).height(@prawn, @prawn.margin_box.width)
25
+ @prawn.page.margins[EDGES.fetch(@name)] += @height + @gap
26
+ @prawn.__send__(:generate_margin_box)
27
+ @prawn.y = [@prawn.y, @prawn.margin_box.absolute_top].min
28
+ @prawn.repeat(->(page_number) { page_number >= first_page }, dynamic: true) { paint }
29
+ end
30
+
31
+ private
32
+
33
+ def stack(page_number)
34
+ stack = Stack.new(@styles)
35
+ @block.call(stack, Page.new(number: page_number, total: @prawn.page_count))
36
+ stack
37
+ end
38
+
39
+ # On the whole page as bounds: a table of the band then finds room where the margin box has none.
40
+ def paint
41
+ stack = stack(@prawn.page_number)
42
+ body = @prawn.margin_box
43
+ height = stack.height(@prawn, body.width)
44
+ if height > @height + FIT_TOLERANCE_POINTS
45
+ raise Prawn::Errors::CannotFit, "the #{@name} is #{height.round(1)} pt high on page #{@prawn.page_number}, " \
46
+ "#{@height.round(1)} pt were kept for it, its height on the page it was declared on"
47
+ end
48
+
49
+ top = (@name == :header) ? body.absolute_top + @gap + @height : body.absolute_bottom - @gap
50
+ @prawn.tag_artifact(:Pagination, @name.capitalize) do
51
+ @prawn.canvas { stack.paint(@prawn, body.absolute_left, top, body.width) }
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "layout"
4
+ require_relative "table"
5
+ require_relative "band"
6
+
7
+ module Gamba
8
+ # Gamba's own API, over a Prawn::Document that stays reachable through #prawn. Blocks receive this object,
9
+ # options are keywords, and an unknown one raises instead of being ignored.
10
+ class Document
11
+ include Layout::Builder
12
+
13
+ OPTIONS = %i[
14
+ page_size page_layout margin left_margin right_margin top_margin bottom_margin background info print_scaling
15
+ pdf_a pdf lang background_pdf background_pdf_page
16
+ ].freeze
17
+ TEXT_ATTRIBUTES = Layout::Styles::TEXT_ATTRIBUTES
18
+ # No Prawn page to match here, so fonts that have ligatures and GPOS kerning use them.
19
+ DEFAULT_FONT_FEATURES = %i[liga kern].freeze
20
+
21
+ def initialize(prawn = nil, **options)
22
+ Layout::Styles.check_options(options, OPTIONS)
23
+ @prawn = prawn || Prawn::Document.new(options)
24
+ @styles = Layout::Styles.new(@prawn, DEFAULT_FONT_FEATURES)
25
+ end
26
+
27
+ # The Prawn document underneath. Boxes still waiting for the one they are kept with are placed first, so what
28
+ # Prawn draws next comes after them.
29
+ def prawn
30
+ place_kept
31
+ @prawn
32
+ end
33
+
34
+ def register_font(family, normal:, bold: nil, italic: nil, bold_italic: nil, features: DEFAULT_FONT_FEATURES)
35
+ files = {normal:, bold:, italic:, bold_italic:}.compact
36
+ prawn.font_families[family] = files.transform_values { |file| {file:, features:} }
37
+ self
38
+ end
39
+
40
+ # Text attributes under a name: text "…", style: name. The :default style applies to every text; in PDF/A and
41
+ # PDF/UA its font is also the document's default, which Prawn's code starts from: Helvetica, Prawn's,
42
+ # cannot be embedded. It is looked up when first used, so it may be registered after.
43
+ def style(name, **attributes)
44
+ @styles.define(name, attributes)
45
+ font = attributes[:font]
46
+ @prawn.default_font_family = font if font && name == Layout::Styles::DEFAULT_STYLE && (@prawn.pdf_a? || @prawn.pdf_ua?)
47
+ self
48
+ end
49
+
50
+ def text(string, style: nil, **attributes)
51
+ add(Layout::Text.new(string, **@styles.text_arguments(style, attributes)))
52
+ end
53
+
54
+ # What follows starts at the top of a new page, the boxes waiting for a next one placed first.
55
+ def page_break
56
+ prawn.start_new_page
57
+ self
58
+ end
59
+
60
+ # Drawn at the top of every page from this one on. The block receives a stack to fill and the page, which
61
+ # answers number and total; gap is the room left between the header and the body.
62
+ def header(gap: 0, &block)
63
+ declare_band(:header, gap, block)
64
+ end
65
+
66
+ def footer(gap: 0, &block)
67
+ declare_band(:footer, gap, block)
68
+ end
69
+
70
+ def to_s
71
+ prawn.render
72
+ end
73
+
74
+ def write(destination)
75
+ if destination.respond_to?(:write)
76
+ destination.write(to_s)
77
+ else
78
+ File.binwrite(destination, to_s)
79
+ end
80
+ self
81
+ end
82
+
83
+ private
84
+
85
+ def declare_band(name, gap, block)
86
+ raise ArgumentError, "the #{name} takes a block, which receives a stack and the page" unless block
87
+ raise ArgumentError, "the #{name} is already declared: a document has one" if (@bands ||= {}).key?(name)
88
+
89
+ @bands[name] = Layout::Band.new(prawn, @styles.without_bookmarks, name, gap, block).tap(&:reserve)
90
+ self
91
+ end
92
+
93
+ # A box of the document is placed as soon as it is described, from the cursor, which it leaves below; one
94
+ # kept with the next waits for it, and they are placed together.
95
+ def add(box)
96
+ raise ArgumentError, "grow shares the width of a row: it means nothing on the document" if box.grow
97
+
98
+ if @kept.nil? && !box.keep_with_next
99
+ place(box)
100
+ else
101
+ (@kept ||= Layout::Group.new(@styles)).push(box)
102
+ place_kept unless box.keep_with_next
103
+ end
104
+ self
105
+ end
106
+
107
+ def place_kept
108
+ return unless @kept
109
+
110
+ kept = @kept
111
+ @kept = nil
112
+ place(kept)
113
+ end
114
+
115
+ def place(box)
116
+ bounds = @prawn.bounds
117
+ cursor = Layout::Cursor.new(@prawn)
118
+ box.flow_tagged(@prawn, cursor, bounds.absolute_left, [box.width || bounds.width, bounds.width].min)
119
+ @prawn.y = cursor.y
120
+ end
121
+ end
122
+ end