Class: Rpdfium::Attachment

Inherits:
Object
  • Object
show all
Defined in:
lib/rpdfium/structure/attachment.rb

Overview

Files embedded in the PDF (attachments). PDFium exposes them via FPDFDoc_GetAttachment.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(document, index) ⇒ Attachment

Returns a new instance of Attachment.

Raises:



8
9
10
11
12
13
# File 'lib/rpdfium/structure/attachment.rb', line 8

def initialize(document, index)
  @document = document
  @index    = index
  @handle   = Raw.FPDFDoc_GetAttachment(document.handle, index)
  raise Error, "Attachment #{index} not found" if @handle.null?
end

Instance Attribute Details

#documentObject (readonly)

Returns the value of attribute document.



6
7
8
# File 'lib/rpdfium/structure/attachment.rb', line 6

def document
  @document
end

#handleObject (readonly)

Returns the value of attribute handle.



6
7
8
# File 'lib/rpdfium/structure/attachment.rb', line 6

def handle
  @handle
end

#indexObject (readonly)

Returns the value of attribute index.



6
7
8
# File 'lib/rpdfium/structure/attachment.rb', line 6

def index
  @index
end

Instance Method Details

#bytesObject

Returns the bytes of the attached file. Probe-then-fetch pattern.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rpdfium/structure/attachment.rb', line 20

def bytes
  out_size = FFI::MemoryPointer.new(:ulong)
  Raw.FPDFAttachment_GetFile(@handle, FFI::Pointer::NULL, 0, out_size)
  n = out_size.read_ulong
  return "" if n.zero?

  buf = FFI::MemoryPointer.new(:uchar, n)
  Raw.FPDFAttachment_GetFile(@handle, buf, n, out_size)
  # Read n bytes (the size of OUR buffer), not out_size.read_ulong:
  # PDFium may update out_size with a value different from n (e.g. the
  # total size required), which would read past the buffer → IndexError.
  # If the actual write is < n, the remainder is filled with NUL.
  buf.read_bytes(n)
end

#nameObject



15
16
17
# File 'lib/rpdfium/structure/attachment.rb', line 15

def name
  Raw.read_utf16_string(:FPDFAttachment_GetName, @handle)
end

#save(path) ⇒ Object



35
36
37
38
# File 'lib/rpdfium/structure/attachment.rb', line 35

def save(path)
  File.binwrite(path, bytes)
  path
end