Skip to content

Commit

Permalink
Add Document#write_to_string for easily writing the document to a string
Browse files Browse the repository at this point in the history
  • Loading branch information
gettalong committed Sep 24, 2024
1 parent 44d25b4 commit 9db2c9a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

* [HexaPDF::Task::MergeAcroForm] for merging AcroForm information for imported
pages
* [HexaPDF::Document#write_to_string] for easily writing a document to a String

### Changed

Expand Down
9 changes: 9 additions & 0 deletions lib/hexapdf/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,15 @@ def write(file_or_io, incremental: false, validate: true, update_fields: true, o
end
end

# Writes the document to a string and returns the string.
#
# See #write for further information and details on the available arguments.
def write_to_string(**args)
io = StringIO.new(''.b)
write(io)
io.string
end

def inspect #:nodoc:
"<#{self.class.name}:#{object_id}>"
end
Expand Down
9 changes: 9 additions & 0 deletions test/hexapdf/test_document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -595,4 +595,13 @@
refute(dupped.encrypted?)
end
end

it "writes the document to a string" do
doc = HexaPDF::Document.new
doc.trailer.info[:test] = :test
str = doc.write_to_string(update_fields: false)
assert_equal(Encoding::ASCII_8BIT, str.encoding)
doc = HexaPDF::Document.new(io: StringIO.new(str))
assert_equal(:test, doc.trailer.info[:test])
end
end

0 comments on commit 9db2c9a

Please sign in to comment.