From 9db2c9a45604fba60b999fdcd920aeea44833b7f Mon Sep 17 00:00:00 2001 From: Thomas Leitner Date: Tue, 24 Sep 2024 10:37:41 +0200 Subject: [PATCH] Add Document#write_to_string for easily writing the document to a string --- CHANGELOG.md | 1 + lib/hexapdf/document.rb | 9 +++++++++ test/hexapdf/test_document.rb | 9 +++++++++ 3 files changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22ed8fb3..8dd6a7a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/hexapdf/document.rb b/lib/hexapdf/document.rb index a4af2c09..3c9982ca 100644 --- a/lib/hexapdf/document.rb +++ b/lib/hexapdf/document.rb @@ -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 diff --git a/test/hexapdf/test_document.rb b/test/hexapdf/test_document.rb index 8a006eb4..efb8353d 100644 --- a/test/hexapdf/test_document.rb +++ b/test/hexapdf/test_document.rb @@ -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