docpdf 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b68eda5d7355d1d3a227ef71f44d41f95dc7ccbfe7b08af17739e629c9ab26dc
4
- data.tar.gz: 23e0ab911eb89df49eeac3634b50ef6d8bf8f7b74a8861067e2a0e44f3946e82
3
+ metadata.gz: 1cce5a9238d275084c580e067ea4978c347049616a6d9f2a9f3b02a977e15c69
4
+ data.tar.gz: b1382ff6812b061f46a463e38d3dd9bdc90f2d63cea8675cbd467ea05a250b78
5
5
  SHA512:
6
- metadata.gz: 14aff5944d6ac087f241b078c557e480974f322ca2cbcf3c9d08136e6b37f6598ca1bbd17e14267b060632e83e54491dbb5dc6a42b15768eb64883bbe3fd7838
7
- data.tar.gz: cb43492ce6e3b7257e3c6cc01281904c509dcb473f77e932361ae986f0f39cda9af3bc0a4080b2e8c7d24e2c13adf6d4a8b93230ed455eef6b6ed74ede98e301
6
+ metadata.gz: af61ac481a3a93c23760507213314ccc0fb0d89d7e82ef023aad83dc929917f7edd9f0a39d8c4ebb2e173d6302ac39ed5952acccc3629c9cc26857f1b51e395a
7
+ data.tar.gz: 61c942282a86e914799869f8cce37645f6124a0a6782692208fed0ed31c874d36ad52580f06273d0ce79b2df9a8d3a490a0846d6eb0e0929fd8ae645932254ea
data/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.0] - 2026-11-20
4
+
5
+ ### Changed
6
+ - Image conversion now prepares photos for documents by default: photos are turned upright from their EXIF orientation, stripped of metadata (including GPS location), flattened onto white, shrunk to at most 2400 pixels per side, and placed on a page whose long edge is 11 inches. Previously a page was one point per pixel, so a 12-megapixel phone photo became a 56-inch page, and sideways photos stayed sideways. Configure with `config.image_options`; `page_long_edge: nil` restores one point per pixel. Both RMagick and MiniMagick adapters apply the same steps.
7
+ - The MiniMagick adapter converts only the first frame of multi-frame images.
8
+
9
+ ### Added
10
+ - `config.soffice_timeout` (default 120 seconds) kills LibreOffice, and everything it started, when a conversion runs too long, raising `ConversionError`. Previously a document that made LibreOffice hang blocked the caller forever. Set it to `nil` for the old behavior.
11
+
12
+ ## [0.1.7] - 2026-10-08
13
+
14
+ ### Fixed
15
+ - The HexaPDF stamper raised `ConversionError` on PDFs with spec violations HexaPDF cannot correct, even though viewers render them fine. One example is a tagged PDF exported from Canva with a structure element missing its parent. The stamper now corrects what HexaPDF can and writes the rest as it came in, the way the `hexapdf` CLI does.
16
+ - `DocPDF.convert` raised `NameError: uninitialized constant DocPDF::InputNormalizer::Pathname` on Ruby 3.3 and 3.4 when nothing else had loaded `pathname`. Bundler and Rails both load it, so only plain Ruby scripts were affected. `DocPDF.watermark` with a file path and `font_file` given as a hash hit the same error. DocPDF now requires `pathname` itself.
17
+
3
18
  ## [0.1.6] - 2026-09-18
4
19
 
5
20
  ### Added
data/README.md CHANGED
@@ -194,6 +194,9 @@ DocPDF.configure do |config|
194
194
  # LibreOffice binary path (default: "soffice", found via PATH)
195
195
  config.soffice_path = "/usr/bin/soffice"
196
196
 
197
+ # Seconds before a LibreOffice conversion is killed (default: 120; nil waits forever)
198
+ config.soffice_timeout = 60
199
+
197
200
  # Stamper adapter for watermarking (default: nil, auto-detects hexapdf then combine_pdf)
198
201
  config.stamper = :hexapdf # or :combine_pdf
199
202
 
@@ -214,6 +217,16 @@ DocPDF.configure do |config|
214
217
  color: "000000", # default: "333333" (hex)
215
218
  }
216
219
 
220
+ # Image (photo/scan) conversion defaults
221
+ config.image_options = {
222
+ auto_orient: true, # turn photos upright from their EXIF orientation
223
+ strip: true, # drop EXIF and other metadata (camera, GPS location)
224
+ background: "white", # flatten transparency onto this color (nil keeps alpha)
225
+ max_edge: 2400, # shrink so neither side exceeds this many pixels (nil: never)
226
+ page_long_edge: 11, # page's long edge in inches (nil: one point per pixel)
227
+ quality: 85, # JPEG quality inside the PDF (nil: ImageMagick default)
228
+ }
229
+
217
230
  # Text watermark defaults (per-stamp options override these)
218
231
  config.watermark_options = {
219
232
  font: "Times", # default: "Helvetica"
@@ -0,0 +1,23 @@
1
+ module DocPDF
2
+ module Adapters
3
+ module Converters
4
+ # ImageMagick arguments for config.image_options, shared by the image adapters.
5
+ module ImageNormalizer
6
+ module_function
7
+
8
+ def arguments(options = DocPDF.configuration.image_options)
9
+ args = []
10
+ args << "-auto-orient" if options[:auto_orient]
11
+ args << "-strip" if options[:strip]
12
+ args += ["-background", options[:background], "-alpha", "remove", "-alpha", "off"] if options[:background]
13
+ args += ["-resize", "#{options[:max_edge]}x#{options[:max_edge]}>"] if options[:max_edge]
14
+ if options[:page_long_edge]
15
+ args += ["-units", "PixelsPerInch", "-set", "density", "%[fx:max(w,h)/#{options[:page_long_edge]}]"]
16
+ end
17
+ args += ["-compress", "jpeg", "-quality", options[:quality].to_s] if options[:quality]
18
+ args
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -1,5 +1,6 @@
1
1
  require "mini_magick"
2
2
  require_relative "base"
3
+ require_relative "image_normalizer"
3
4
 
4
5
  module DocPDF
5
6
  module Adapters
@@ -9,20 +10,21 @@ module DocPDF
9
10
 
10
11
  class << self
11
12
  def convert(data, filename)
12
- img = nil
13
- Tempfile.create(["docpdf", File.extname(filename || ".tmp")]) do |tempfile|
14
- tempfile.binmode
15
- tempfile.write(data)
16
- tempfile.rewind
17
-
18
- img = ::MiniMagick::Image.open(tempfile.path)
19
- img.format("pdf")
20
- img.to_blob
13
+ Tempfile.create(["docpdf", File.extname(filename || ".tmp")]) do |input|
14
+ input.binmode
15
+ input.write(data)
16
+ input.flush
17
+ Tempfile.create(["docpdf", ".pdf"]) do |output|
18
+ ::MiniMagick.convert do |convert|
19
+ convert << "#{input.path}[0]" # first frame only
20
+ ImageNormalizer.arguments.each { |argument| convert << argument }
21
+ convert << "pdf:#{output.path}"
22
+ end
23
+ File.binread(output.path)
24
+ end
21
25
  end
22
26
  rescue ::MiniMagick::Error => e
23
27
  raise ConversionError, "MiniMagick failed to convert #{filename || 'image'} to PDF: #{e.message}"
24
- ensure
25
- img&.destroy!
26
28
  end
27
29
  end
28
30
  end
@@ -1,5 +1,6 @@
1
1
  require "rmagick"
2
2
  require_relative "base"
3
+ require_relative "image_normalizer"
3
4
 
4
5
  module DocPDF
5
6
  module Adapters
@@ -13,16 +14,48 @@ module DocPDF
13
14
  Tempfile.create(["docpdf", File.extname(filename || ".tmp")]) do |tempfile|
14
15
  tempfile.binmode
15
16
  tempfile.write(data)
16
- tempfile.rewind
17
+ tempfile.flush
17
18
 
18
- img = Magick::Image.read(tempfile.path).first
19
- img.to_blob { |attrs| attrs.format = "PDF" }
19
+ img = normalize(Magick::Image.read(tempfile.path).first, DocPDF.configuration.image_options)
20
+ img.to_blob do |attrs|
21
+ attrs.format = "PDF"
22
+ if (quality = DocPDF.configuration.image_options[:quality])
23
+ attrs.compression = Magick::JPEGCompression
24
+ attrs.quality = quality
25
+ end
26
+ end
20
27
  end
21
28
  rescue Magick::ImageMagickError => e
22
29
  raise ConversionError, "RMagick failed to convert #{filename || 'image'} to PDF: #{e.message}"
23
30
  ensure
24
31
  img&.destroy!
25
32
  end
33
+
34
+ private
35
+
36
+ # Same steps as ImageNormalizer.arguments, through the RMagick API.
37
+ def normalize(img, options)
38
+ img = replace(img, img.auto_orient) if options[:auto_orient]
39
+ img.strip! if options[:strip]
40
+ if options[:background]
41
+ flat = img.alpha? ? img.flatten_images_on(options[:background]) : nil
42
+ img = replace(img, flat) if flat
43
+ end
44
+ if (edge = options[:max_edge]) && [img.columns, img.rows].max > edge
45
+ img = replace(img, img.resize_to_fit(edge, edge))
46
+ end
47
+ if (inches = options[:page_long_edge])
48
+ dpi = [img.columns, img.rows].max / inches.to_f
49
+ img.units = Magick::PixelsPerInchResolution
50
+ img.density = "#{dpi}x#{dpi}"
51
+ end
52
+ img
53
+ end
54
+
55
+ def replace(old, new)
56
+ old.destroy! unless old.equal?(new)
57
+ new
58
+ end
26
59
  end
27
60
  end
28
61
  end
@@ -32,11 +32,11 @@ module DocPDF
32
32
  soffice = DocPDF.configuration.soffice_path
33
33
  profile_dir = File.join(output_dir, "profile")
34
34
  stderr_path = File.join(output_dir, "stderr.log")
35
- success = system(soffice, "--headless",
36
- "-env:UserInstallation=file://#{profile_dir}",
37
- "--convert-to", "pdf",
38
- "--outdir", output_dir, tempfile.path,
39
- out: File::NULL, err: stderr_path)
35
+ success = run(soffice, "--headless",
36
+ "-env:UserInstallation=file://#{profile_dir}",
37
+ "--convert-to", "pdf",
38
+ "--outdir", output_dir, tempfile.path,
39
+ stderr_path: stderr_path, source_filename: source_filename)
40
40
 
41
41
  pdf_path = Dir.glob(File.join(output_dir, "*.pdf")).first
42
42
 
@@ -57,6 +57,41 @@ module DocPDF
57
57
  end
58
58
  end
59
59
  end
60
+
61
+ private
62
+
63
+ # Like Kernel#system (nil when soffice can't be started), but kills
64
+ # LibreOffice and everything it started after config.soffice_timeout
65
+ # seconds, so a document that makes it hang can't hold the caller forever.
66
+ def run(*command, stderr_path:, source_filename:)
67
+ pid = Process.spawn(*command, out: File::NULL, err: stderr_path, pgroup: true)
68
+ timeout = DocPDF.configuration.soffice_timeout
69
+ deadline = timeout && Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
70
+ loop do
71
+ _, status = Process.wait2(pid, Process::WNOHANG)
72
+ return status.success? if status
73
+
74
+ if deadline && Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
75
+ kill_group(pid)
76
+ raise ConversionError, "LibreOffice timed out after #{timeout}s converting #{source_filename || 'document'}"
77
+ end
78
+ sleep 0.05
79
+ end
80
+ rescue Errno::ENOENT, Errno::EACCES
81
+ nil
82
+ end
83
+
84
+ def kill_group(pid)
85
+ Process.kill("KILL", -pid)
86
+ rescue Errno::ESRCH
87
+ nil
88
+ ensure
89
+ begin
90
+ Process.wait(pid)
91
+ rescue Errno::ECHILD
92
+ nil
93
+ end
94
+ end
60
95
  end
61
96
  end
62
97
  end
@@ -22,7 +22,7 @@ module DocPDF
22
22
  page.canvas(type: :overlay).xobject(stamp_form, at: [0, 0]) if page_indices.nil? || page_indices.include?(idx)
23
23
  end
24
24
 
25
- write_to_string(doc)
25
+ write_to_string_leniently(doc)
26
26
  rescue HexaPDF::Error, Errno::ENOENT => e
27
27
  raise ConversionError, "HexaPDF failed to stamp PDF: #{e.message}"
28
28
  end
@@ -125,11 +125,23 @@ module DocPDF
125
125
  doc.config["font.map"] = (doc.config["font.map"] || {}).merge(name => map)
126
126
  end
127
127
 
128
- def write_to_string(doc)
128
+ def write_to_string(doc, **write_options)
129
129
  io = StringIO.new
130
- doc.write(io)
130
+ doc.write(io, **write_options)
131
131
  io.string
132
132
  end
133
+
134
+ # The caller's PDF may break the spec in ways HexaPDF cannot repair, like a
135
+ # tagged PDF whose structure elements have no parent. Viewers open those
136
+ # fine, so correct what can be corrected and write the rest as it came in,
137
+ # the way the hexapdf CLI does. Objects are validated one at a time because
138
+ # Document#validate stops at the first one it cannot correct, and the stamp
139
+ # form only becomes an indirect object when validation reaches its page.
140
+ def write_to_string_leniently(doc)
141
+ doc.trailer.validate(auto_correct: true)
142
+ doc.each { |obj| obj.validate(auto_correct: true) }
143
+ write_to_string(doc, validate: false)
144
+ end
133
145
  end
134
146
  end
135
147
  end
@@ -1,6 +1,8 @@
1
1
  module DocPDF
2
2
  class Configuration
3
3
  attr_accessor :soffice_path,
4
+ :soffice_timeout,
5
+ :image_options,
4
6
  :converter,
5
7
  :stamper,
6
8
  :page_size,
@@ -15,6 +17,21 @@ module DocPDF
15
17
  color: "333333",
16
18
  }.freeze
17
19
 
20
+ # Photos are turned upright from their EXIF orientation, stripped of metadata
21
+ # (camera, GPS location), flattened onto white, and shrunk to at most
22
+ # max_edge pixels. The page's long edge is page_long_edge inches, so a phone
23
+ # photo becomes a page about the size of a printed sheet rather than one
24
+ # point per pixel (a 12 MP photo would otherwise be a 56-inch page).
25
+ # Set page_long_edge to nil for the old one-point-per-pixel sizing.
26
+ IMAGE_DEFAULTS = {
27
+ auto_orient: true,
28
+ strip: true,
29
+ background: "white",
30
+ max_edge: 2400,
31
+ page_long_edge: 11,
32
+ quality: 85,
33
+ }.freeze
34
+
18
35
  WATERMARK_DEFAULTS = {
19
36
  font: "Helvetica",
20
37
  font_file: nil,
@@ -25,6 +42,8 @@ module DocPDF
25
42
 
26
43
  def initialize
27
44
  @soffice_path = "soffice"
45
+ @soffice_timeout = 120 # seconds; nil waits forever
46
+ @image_options = IMAGE_DEFAULTS.dup
28
47
  @converter = nil
29
48
  @stamper = nil
30
49
  @page_size = "LETTER"
@@ -1,3 +1,5 @@
1
+ require "pathname"
2
+
1
3
  module DocPDF
2
4
  # Prawn's built-in AFM fonts only cover Windows-1252, so any text outside it
3
5
  # fails to render. Pointing an adapter at a TrueType file lifts that limit.
@@ -1,3 +1,5 @@
1
+ require "pathname"
2
+
1
3
  module DocPDF
2
4
  class InputNormalizer
3
5
  attr_reader :data, :filename, :source_filename, :mime_type
@@ -1,3 +1,3 @@
1
1
  module DocPDF
2
- VERSION = "0.1.6"
2
+ VERSION = "0.2.0"
3
3
  end
@@ -1,3 +1,5 @@
1
+ require "pathname"
2
+
1
3
  module DocPDF
2
4
  class Watermarker
3
5
  POSITIONS = %i[center top bottom left right top_left top_right bottom_left bottom_right].freeze
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: docpdf
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.6
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Velocity Labs, LLC
@@ -26,6 +26,7 @@ files:
26
26
  - lib/docpdf/adapters/converters/base.rb
27
27
  - lib/docpdf/adapters/converters/fallback.rb
28
28
  - lib/docpdf/adapters/converters/hexapdf.rb
29
+ - lib/docpdf/adapters/converters/image_normalizer.rb
29
30
  - lib/docpdf/adapters/converters/mini_magick.rb
30
31
  - lib/docpdf/adapters/converters/passthrough.rb
31
32
  - lib/docpdf/adapters/converters/prawn.rb