gettalong / hexapdf

Versatile PDF creation and manipulation for Ruby
https://hexapdf.gettalong.org
Other
1.21k stars 69 forks source link

cli "watermark" command is not respecting cropbox #206

Closed andi-dev closed 1 year ago

andi-dev commented 1 year ago

Hey again :)

I ran into an issue with the watermark-command, or more specifically I ran into the issue when trying to adapt the code in watermark.rb to our use case.

I have the following two pdfs:

Background: https://drive.google.com/file/d/1nDOXwnt6EjNuoAT-OKjDnuzpUf00awAS/view?usp=share_link Overlay: https://drive.google.com/file/d/1EjYftJGHF_dvhojgiBgRpOrpjAyMoWBo/view?usp=share_link

the blue checkboxes in the overlay, should fit (almost) exactly into the top-left and bottom-right corners of the grid.

When I attempt to "stamp" the overlay onto the background ( hexapdf watermark -t stamp -i 1-e -w overlay.pdf background.pdf out.pdf ), I get the following result:

image

When I try the same with pdftk ( pdftk background.pdf multibackground overlay.pdf output out-pdftk.pdf ) the result is fine.

I was able to fix this, by changing the code I took from watermark.rb like this:

   background_doc.pages.each_with_index do |page, index|
      xobject = background_doc.import(overlay_doc.pages[index].to_form_xobject)
      # Change 1: Always use cropbox, because it falls back to mediabox if it is not set.
      pw = page.box(:crop).width.to_f
      ph = page.box(:crop).height.to_f
      xw = xobject.width.to_f
      xh = xobject.height.to_f
      canvas = page.canvas(type: :overlay)
      ratio = [pw / xw, ph / xh].min
      xw *= ratio
      xh *= ratio
      x = ((pw - xw) / 2)
      y = ((ph - xh) / 2)
      # Change 2: If the cropbox is not mediabox (-> cropbox is explicitly set and not just falling back),
      # fix placement of the imported object accordingly.
      if page.box(:crop).value != page.box(:media).value
        x += page.box(:crop).left
        y += page.box(:crop).bottom
      end
      canvas.xobject(xobject, at: [x, y], width: xw, height: xh)
    end

However I am not sure if you had a reason to ignore the cropbox in your implementation and if I am missing something. I still have to get used to pdfs box-system...

Thank you for your work!

gettalong commented 1 year ago

W.r.t. to the box-system: I can only say: me too :grin:

A customer recently had a similar problem (see #204) and through this I already have a fix available (see https://github.com/gettalong/hexapdf/commit/5a50b7745f7d9408d9932b543e5a9957b18fdf62). So this will work in a few days when the next version is released.

I now get the following output: image

This seems correct?

andi-dev commented 1 year ago

Hey, thanks again for your quick reply. I can confirm that it works with the actions-branch! Looking forward to the new release!