Class: HexaPDF::Type::Page

Inherits:
Dictionary show all
Defined in:
lib/hexapdf/type/page.rb

Overview

Represents a page of a PDF document.

A page object contains the meta information for a page. Most of the fields are independent from the page’s content like the /Dur field. However, some of them (like /Resources or /UserUnit) influence how or if the page’s content can be rendered correctly.

A number of field values can also be inherited: /Resources, /MediaBox, /CropBox, /Rotate. Field inheritance means that if a field is not set on the page object itself, the value is taken from the nearest page tree ancestor that has this value set.

See: PDF1.7 s7.7.3.3, s7.7.3.4, Pages

Constant Summary collapse

PAPER_SIZE =

The predefined paper sizes in points (1/72 inch):

  • ISO sizes: A0x4, A0x2, A0-A10, B0-B10, C0-C10

  • Letter, Legal, Ledger, Tabloid, Executive

{
  A0x4: [0, 0, 4768, 6741].freeze,
  A0x2: [0, 0, 3370, 4768].freeze,
  A0: [0, 0, 2384, 3370].freeze,
  A1: [0, 0, 1684, 2384].freeze,
  A2: [0, 0, 1191, 1684].freeze,
  A3: [0, 0, 842, 1191].freeze,
  A4: [0, 0, 595, 842].freeze,
  A5: [0, 0, 420, 595].freeze,
  A6: [0, 0, 298, 420].freeze,
  A7: [0, 0, 210, 298].freeze,
  A8: [0, 0, 147, 210].freeze,
  A9: [0, 0, 105, 147].freeze,
  A10: [0, 0, 74, 105].freeze,
  B0: [0, 0, 2835, 4008].freeze,
  B1: [0, 0, 2004, 2835].freeze,
  B2: [0, 0, 1417, 2004].freeze,
  B3: [0, 0, 1001, 1417].freeze,
  B4: [0, 0, 709, 1001].freeze,
  B5: [0, 0, 499, 709].freeze,
  B6: [0, 0, 354, 499].freeze,
  B7: [0, 0, 249, 354].freeze,
  B8: [0, 0, 176, 249].freeze,
  B9: [0, 0, 125, 176].freeze,
  B10: [0, 0, 88, 125].freeze,
  C0: [0, 0, 2599, 3677].freeze,
  C1: [0, 0, 1837, 2599].freeze,
  C2: [0, 0, 1298, 1837].freeze,
  C3: [0, 0, 918, 1298].freeze,
  C4: [0, 0, 649, 918].freeze,
  C5: [0, 0, 459, 649].freeze,
  C6: [0, 0, 323, 459].freeze,
  C7: [0, 0, 230, 323].freeze,
  C8: [0, 0, 162, 230].freeze,
  C9: [0, 0, 113, 162].freeze,
  C10: [0, 0, 79, 113].freeze,
  Letter: [0, 0, 612, 792].freeze,
  Legal: [0, 0, 612, 1008].freeze,
  Ledger: [0, 0, 792, 1224].freeze,
  Tabloid: [0, 0, 1224, 792].freeze,
  Executive: [0, 0, 522, 756].freeze,
}.freeze
INHERITABLE_FIELDS =

The inheritable fields.

[:Resources, :MediaBox, :CropBox, :Rotate].freeze
REQUIRED_INHERITABLE_FIELDS =

The required inheritable fields.

[:Resources, :MediaBox].freeze

Constants included from DictionaryFields

DictionaryFields::Boolean, DictionaryFields::PDFByteString, DictionaryFields::PDFDate

Instance Attribute Summary

Attributes inherited from Object

#data, #document, #must_be_indirect

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Dictionary

#[]=, define_field, define_type, #delete, #each, each_field, #empty?, field, #key?, #to_h, type, #type

Methods inherited from Object

#<=>, #==, #cache, #cached?, #clear_cache, deep_copy, #deep_copy, #document?, #eql?, field, #gen, #gen=, #hash, #indirect?, #initialize, #inspect, make_direct, #null?, #oid, #oid=, #type, #validate, #value, #value=

Constructor Details

This class inherits a constructor from HexaPDF::Object

Class Method Details

.media_box(paper_size, orientation: :portrait) ⇒ Object

Returns the media box for the given paper size. See PAPER_SIZE for the defined paper sizes.



108
109
110
111
112
113
114
115
116
# File 'lib/hexapdf/type/page.rb', line 108

def self.media_box(paper_size, orientation: :portrait)
  unless PAPER_SIZE.key?(paper_size)
    raise HexaPDF::Error, "Invalid paper size specified: #{paper_size}"
  end

  media_box = PAPER_SIZE[paper_size].dup
  media_box[2], media_box[3] = media_box[3], media_box[2] if orientation == :landscape
  media_box
end

Instance Method Details

#[](name) ⇒ Object

Returns the value for the entry name.

If name is an inheritable value and the value has not been set on the page object, its value is retrieved from the ancestor page tree nodes.

See: Dictionary#[]



168
169
170
171
172
173
174
175
176
# File 'lib/hexapdf/type/page.rb', line 168

def [](name)
  if value[name].nil? && INHERITABLE_FIELDS.include?(name)
    node = self
    node = node[:Parent] while node.value[name].nil? && node[:Parent]
    node == self || node.value[name].nil? ? super : node[name]
  else
    super
  end
end

#ancestor_nodesObject

Returns all parent nodes of the page up to the root of the page tree.

The direct parent is the first node in the array and the root node the last.



390
391
392
393
394
395
# File 'lib/hexapdf/type/page.rb', line 390

def ancestor_nodes
  parent = self[:Parent]
  result = [parent]
  result << parent while (parent = parent[:Parent])
  result
end

#box(type = :crop, rectangle = nil) ⇒ Object

:call-seq:

page.box(type = :crop)              -> box
page.box(type = :crop, rectangle)   -> rectangle

If no rectangle is given, returns the rectangle defining a certain kind of box for the page. Otherwise sets the value for the given box type to rectangle (an array with four values or a HexaPDF::Rectangle).

This method should be used instead of directly accessing any of /MediaBox, /CropBox, /BleedBox, /ArtBox or /TrimBox because it also takes the fallback values into account!

The following types are allowed:

:media

The media box defines the boundaries of the medium the page is to be printed on.

:crop

The crop box defines the region to which the contents of the page should be clipped when it is displayed or printed. The default is the media box.

:bleed

The bleed box defines the region to which the contents of the page should be clipped when output in a production environment. The default is the crop box.

:trim

The trim box defines the intended dimensions of the page after trimming. The default value is the crop box.

:art

The art box defines the region of the page’s meaningful content as intended by the author. The default is the crop box.

See: PDF1.7 s14.11.2



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/hexapdf/type/page.rb', line 222

def box(type = :crop, rectangle = nil)
  if rectangle
    case type
    when :media, :crop, :bleed, :trim, :art
      self["#{type.capitalize}Box".to_sym] = rectangle
    else
      raise ArgumentError, "Unsupported page box type provided: #{type}"
    end
  else
    case type
    when :media then self[:MediaBox]
    when :crop then self[:CropBox] || self[:MediaBox]
    when :bleed then self[:BleedBox] || self[:CropBox] || self[:MediaBox]
    when :trim then self[:TrimBox] || self[:CropBox] || self[:MediaBox]
    when :art then self[:ArtBox] || self[:CropBox] || self[:MediaBox]
    else
      raise ArgumentError, "Unsupported page box type provided: #{type}"
    end
  end
end

#canvas(type: :page, translate_origin: true) ⇒ Object

Returns the requested type of canvas for the page.

There are potentially three different canvas objects, one for each of the types :underlay, :page, and :overlay. The canvas objects are cached once they are created so that their graphics states are correctly retained without the need for parsing the contents. This also means that on subsequent invocations the graphic states of the canvases might already be changed.

type

Can either be

  • :page for getting the canvas for the page itself (only valid for initially empty pages)

  • :overlay for getting the canvas for drawing over the page contents

  • :underlay for getting the canvas for drawing unter the page contents

translate_origin

Specifies whether the origin should automatically be translated into the lower-left corner of the crop box.

Note that this argument is only used for the first invocation for every canvas type. So if a canvas was initially requested with this argument set to false and then with true, it won’t have any effect as the cached canvas is returned.

To check whether the origin has been translated or not, use

canvas.graphics_state.ctm.evaluate(0, 0)

and check whether the result is [0, 0]. If it is, then the origin has not been translated.



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
# File 'lib/hexapdf/type/page.rb', line 425

def canvas(type: :page, translate_origin: true)
  unless [:page, :overlay, :underlay].include?(type)
    raise ArgumentError, "Invalid value for 'type', expected: :page, :underlay or :overlay"
  end
  cache_key = "#{type}_canvas".intern
  return cache(cache_key) if cached?(cache_key)

  if type == :page && key?(:Contents)
    raise HexaPDF::Error, "Cannot get the canvas for a page with contents"
  end

  create_canvas = lambda do
    Content::Canvas.new(self).tap do |canvas|
      next unless translate_origin
      crop_box = box(:crop)
      if crop_box.left != 0 || crop_box.bottom != 0
        canvas.translate(crop_box.left, crop_box.bottom)
      end
    end
  end

  contents = self[:Contents]
  if contents.nil?
    page_canvas = cache(:page_canvas, create_canvas.call)
    self[:Contents] = document.add({Filter: :FlateDecode},
                                   stream: page_canvas.stream_data)
  end

  if type == :overlay || type == :underlay
    underlay_canvas = cache(:underlay_canvas, create_canvas.call)
    overlay_canvas = cache(:overlay_canvas, create_canvas.call)

    stream = HexaPDF::StreamData.new do
      Fiber.yield(" q ")
      fiber = underlay_canvas.stream_data.fiber
      while fiber.alive? && (data = fiber.resume)
        Fiber.yield(data)
      end
      " Q q "
    end
    underlay = document.add({Filter: :FlateDecode}, stream: stream)

    stream = HexaPDF::StreamData.new do
      Fiber.yield(" Q q ")
      fiber = overlay_canvas.stream_data.fiber
      while fiber.alive? && (data = fiber.resume)
        Fiber.yield(data)
      end
      " Q "
    end
    overlay = document.add({Filter: :FlateDecode}, stream: stream)

    self[:Contents] = [underlay, *self[:Contents], overlay]
  end

  cache(cache_key)
end

#contentsObject

Returns the concatenated stream data from the content streams as binary string.

Note: Any modifications done to the returned value *won’t* be reflected in any of the streams’ data!



327
328
329
330
331
332
# File 'lib/hexapdf/type/page.rb', line 327

def contents
  Array(self[:Contents]).each_with_object("".b) do |content_stream, content|
    content << " " unless content.empty?
    content << content_stream.stream
  end
end

#contents=(data) ⇒ Object

Replaces the contents of the page with the given string.

This is done by deleting all but the first content stream and reusing this content stream; or by creating a new one if no content stream exists.



338
339
340
341
342
343
344
345
346
347
# File 'lib/hexapdf/type/page.rb', line 338

def contents=(data)
  first, *rest = self[:Contents]
  rest.each {|stream| document.delete(stream) }
  if first
    self[:Contents] = first
    document.deref(first).stream = data
  else
    self[:Contents] = document.add({Filter: :FlateDecode}, stream: data)
  end
end

#copy_inherited_valuesObject

Copies the page’s inherited values from the ancestor page tree nodes into a hash and returns the hash.

The hash can then be used to update the page itself (e.g. when moving a page from one position to another) or another page (e.g. when importing a page from another document).



183
184
185
186
187
# File 'lib/hexapdf/type/page.rb', line 183

def copy_inherited_values
  INHERITABLE_FIELDS.each_with_object({}) do |name, hash|
    hash[name] = HexaPDF::Object.deep_copy(self[name]) if value[name].nil?
  end
end

#each_annotationObject

:call-seq:

page.each_annotation {|annotation| block}    -> page
page.each_annotation                         -> Enumerator

Yields each annotation of this page.



518
519
520
521
522
523
524
525
# File 'lib/hexapdf/type/page.rb', line 518

def each_annotation
  return to_enum(__method__) unless block_given?
  self[:Annots]&.each do |annotation|
    next unless annotation
    yield(document.wrap(annotation, type: :Annot))
  end
  self
end

#flatten_annotations(annotations = ) ⇒ Object

Flattens all or the given annotations of the page. Returns an array with all the annotations that couldn’t be flattened because they don’t have an appearance stream.

Flattening means making the appearances of the annotations part of the content stream of the page and deleting the annotations themselves. Invisible and hidden fields are deleted but not rendered into the content stream.

If an annotation is a form field widget, only the widget will be deleted but not the form field itself.



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
# File 'lib/hexapdf/type/page.rb', line 536

def flatten_annotations(annotations = self[:Annots])
  not_flattened = (annotations || []).to_ary
  return not_flattened unless key?(:Annots)

  annotations = not_flattened & self[:Annots] if annotations != self[:Annots]
  return not_flattened if annotations.empty?

  canvas = self.canvas(type: :overlay)
  if (pos = canvas.graphics_state.ctm.evaluate(0, 0)) != [0, 0]
    canvas.save_graphics_state
    canvas.translate(-pos[0], -pos[1])
  end

  to_delete = []
  not_flattened -= annotations
  annotations.each do |annotation|
    annotation = document.wrap(annotation, type: :Annot)
    appearance = annotation.appearance
    if annotation.flagged?(:hidden) || annotation.flagged?(:invisible)
      to_delete << annotation
      next
    elsif !appearance
      not_flattened << annotation
      next
    end

    rect = annotation[:Rect]
    box = appearance.box

    # PDF1.7 12.5.5 algorithm
    # Step a) Calculate smallest rectangle containing transformed bounding box
    matrix = HexaPDF::Content::TransformationMatrix.new(*appearance[:Matrix].value)
    llx, lly = matrix.evaluate(box.left, box.bottom)
    ulx, uly = matrix.evaluate(box.left, box.top)
    lrx, lry = matrix.evaluate(box.right, box.bottom)
    left, right = [llx, ulx, lrx, lrx + (ulx - llx)].minmax
    bottom, top = [lly, uly, lry, lry + (uly - lly)].minmax

    # Step b) Fit calculated rectangle to annotation rectangle by translating/scaling
    a = HexaPDF::Content::TransformationMatrix.new
    a.translate(rect.left - left, rect.bottom - bottom)
    a.scale(rect.width.fdiv(right - left), rect.height.fdiv(top - bottom))

    # Step c) Premultiply form matrix - done implicitly when drawing the XObject

    canvas.transform(*a) do
      # Use [box.left, box.bottom] to counter default translation in #xobject since that
      # is already taken care of in matrix a
      canvas.xobject(appearance, at: [box.left, box.bottom])
    end
    to_delete << annotation
  end
  canvas.restore_graphics_state unless pos == [0, 0]

  to_delete.each do |annotation|
    if annotation[:Subtype] == :Widget
      annotation.form_field.delete_widget(annotation)
    else
      self[:Annots].delete(annotation)
      document.delete(annotation)
    end
  end

  not_flattened
end

#indexObject

Returns the index of the page in the page tree.



366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/hexapdf/type/page.rb', line 366

def index
  idx = 0
  node = self
  while (parent_node = node[:Parent])
    parent_node[:Kids].each do |kid|
      break if kid == node
      idx += (kid.type == :Page ? 1 : kid[:Count])
    end
    node = parent_node
  end
  idx
end

#labelObject

Returns the label of the page which is an optional, alternative description of the page index.

See HexaPDF::Document::Pages for details.



383
384
385
# File 'lib/hexapdf/type/page.rb', line 383

def label
  document.pages.page_label(index)
end

#must_be_indirect?Boolean

Returns true since page objects must always be indirect.

Returns:



158
159
160
# File 'lib/hexapdf/type/page.rb', line 158

def must_be_indirect?
  true
end

#orientation(type = :crop) ⇒ Object

Returns the orientation of the specified box (default is the crop box), either :portrait or :landscape.



245
246
247
248
249
250
251
252
253
254
# File 'lib/hexapdf/type/page.rb', line 245

def orientation(type = :crop)
  box = self.box(type)
  rotation = self[:Rotate]
  if (box.height > box.width && (rotation == 0 || rotation == 180)) ||
      (box.height < box.width && (rotation == 90 || rotation == 270))
    :portrait
  else
    :landscape
  end
end

#process_contents(processor) ⇒ Object

Processes the content streams associated with the page with the given processor object.

See: HexaPDF::Content::Processor



359
360
361
362
363
# File 'lib/hexapdf/type/page.rb', line 359

def process_contents(processor)
  self[:Resources] = {} if self[:Resources].nil?
  processor.resources = self[:Resources]
  Content::Parser.parse(contents, processor)
end

#resourcesObject

Returns the, possibly inherited, resource dictionary which is automatically created if it doesn’t exist.



351
352
353
354
# File 'lib/hexapdf/type/page.rb', line 351

def resources
  self[:Resources] ||= document.wrap({ProcSet: [:PDF, :Text, :ImageB, :ImageC, :ImageI]},
                                     type: :XXResources)
end

#rotate(angle, flatten: false) ⇒ Object

Rotates the page angle degrees counterclockwise where angle has to be a multiple of 90.

Positive values rotate the page to the left, negative values to the right. If flatten is true, the rotation is not done via the page’s meta data but by “rotating” the canvas itself.

Note that the :Rotate key of a page object describes the angle in a clockwise orientation but this method uses counterclockwise rotation to be consistent with other rotation methods (e.g. HexaPDF::Content::Canvas#rotate).



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
# File 'lib/hexapdf/type/page.rb', line 265

def rotate(angle, flatten: false)
  if angle % 90 != 0
    raise ArgumentError, "Page rotation has to be multiple of 90 degrees"
  end

  # /Rotate and therefore cw_angle is angle in clockwise orientation
  cw_angle = (self[:Rotate] - angle) % 360

  if flatten
    delete(:Rotate)
    return if cw_angle == 0

    matrix = case cw_angle
             when 90  then Content::TransformationMatrix.new(0, -1, 1, 0, -box.bottom, box.right)
             when 180 then Content::TransformationMatrix.new(-1, 0, 0, -1, box.right, box.top)
             when 270 then Content::TransformationMatrix.new(0, 1, -1, 0, box.top, -box.left)
             end

    rotate_box = lambda do |box|
      llx, lly, urx, ury = \
        case cw_angle
        when 90  then [box.right, box.bottom, box.left, box.top]
        when 180 then [box.right, box.top, box.left, box.bottom]
        when 270 then [box.left, box.top, box.right, box.bottom]
        end
      box.value.replace(matrix.evaluate(llx, lly).concat(matrix.evaluate(urx, ury)))
    end

    [:MediaBox, :CropBox, :BleedBox, :TrimBox, :ArtBox].each do |box_name|
      next unless key?(box_name)
      rotate_box.call(self[box_name])
    end

    each_annotation do |annot|
      rotate_box.call(annot[:Rect])
      if (quad_points = annot[:QuadPoints])
        quad_points = quad_points.value if quad_points.respond_to?(:value)
        result = []
        quad_points.each_slice(2) {|x, y| result.concat(matrix.evaluate(x, y)) }
        quad_points.replace(result)
      end
      if (appearance = annot.appearance)
        appearance[:Matrix] = matrix.dup.premultiply(*appearance[:Matrix].value).to_a
      end
      if annot[:Subtype] == :Widget
        app_ch = annot[:MK] ||= document.wrap({}, type: :XXAppearanceCharacteristics)
        app_ch[:R] = (app_ch[:R] + 360 - cw_angle) % 360
      end
    end

    before_contents = document.add({}, stream: " q #{matrix.to_a.join(' ')} cm ")
    after_contents = document.add({}, stream: " Q ")
    self[:Contents] = [before_contents, *self[:Contents], after_contents]
  else
    self[:Rotate] = cw_angle
  end
end

#to_form_xobject(reference: true) ⇒ Object

Creates a Form XObject from the page’s dictionary and contents for the given PDF document.

If reference is true, the page’s contents is referenced when possible to avoid unnecessary decoding/encoding.

Note 1: The created Form XObject is not added to the document automatically!

Note 2: If reference is false and if a canvas is used on this page (see #canvas), this method should only be called once the contents of the page has been fully defined. The reason is that during the copying of the content stream data the contents may be modified to make it a fully valid content stream.



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/hexapdf/type/page.rb', line 494

def to_form_xobject(reference: true)
  first, *rest = self[:Contents]
  stream = if !first
             nil
           elsif !reference || !rest.empty? || first.raw_stream.kind_of?(String)
             contents
           else
             first.raw_stream
           end
  dict = {
    Type: :XObject,
    Subtype: :Form,
    BBox: HexaPDF::Object.deep_copy(box(:crop)),
    Resources: HexaPDF::Object.deep_copy(self[:Resources]),
    Filter: :FlateDecode,
  }
  document.wrap(dict, stream: stream)
end