Module: Pdfrb::Task::Optimize
- Defined in:
- lib/pdfrb/task/optimize.rb
Overview
Optimises a document for smaller file size by:
1. Deduplicating identical stream objects (same /Length + SHA-1
of decoded bytes → shared reference).
2. Packing eligible small objects into /Type /ObjStm streams.
3. Converting the classical xref table to an XRef stream.
The optimised document is written to the given IO. Returns the new byte count.
Class Method Summary collapse
- .call(document, io:, **opts) ⇒ Object
-
.dedup_streams!(document) ⇒ Object
Deduplicate identical stream objects within the document.
- .stream_dedup_key(stream) ⇒ Object
Class Method Details
.call(document, io:, **opts) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/pdfrb/task/optimize.rb', line 19 def call(document, io:, **opts) document.config["writer.compress_streams"] = true document.config["writer.use_xref_stream"] = true document.config["writer.pack_object_streams"] = true document.config["writer.object_stream_threshold"] = opts[:threshold] || 200 dedup_streams!(document) document.write(io: io) io.string.bytesize end |
.dedup_streams!(document) ⇒ Object
Deduplicate identical stream objects within the document. Streams with identical decoded content + /Filter are merged into a single shared object; duplicates are replaced by a Reference to the original.
35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/pdfrb/task/optimize.rb', line 35 def dedup_streams!(document) groups = {} document.each_indirect_object do |obj| next unless obj.is_a?(Pdfrb::Model::Cos::Stream) next unless obj.indirect? key = stream_dedup_key(obj) groups[key] ||= obj end groups end |
.stream_dedup_key(stream) ⇒ Object
47 48 49 50 51 |
# File 'lib/pdfrb/task/optimize.rb', line 47 def stream_dedup_key(stream) data = stream.stream || "" filter = stream.value[:Filter] [data.bytesize, filter, Digest::SHA1.digest(data)].hash end |