Simmo
Simmo

Reputation: 1719

How can I amend individual page sizes within a pdf using ruby?

We send a PDF directly to a label printer for printing. The printer has a cutter and will cut a continuous strip of label to the appropriate length, depending on the page size. In order to save label paper, we would like to reduce the length of each page to remove any whitespace, which varies on a per page basis. I can calculate the point at which to amend the page length to, but don't know how to then do it.

I'm using Ruby on Rails. I don't mind what library I use, but am already using imagemagick and rghost so either of those would be good.

Upvotes: 3

Views: 1130

Answers (2)

Ahmad Ali
Ahmad Ali

Reputation: 556

You can do this by using combine_pdf gem.

After installing the gem, you can try my example code in your rails console.

The following example, sets different page dimensions for even and odd pages. You can obviously put your logic there.

lets set the path of these two variables according to your system directory:

pdf_path = "/Users/apple/Desktop/a.pdf"
new_pdf_path = "/Users/apple/Desktop/b.pdf"

you can give desired dimensions in the following format: cropped_size = [X_min, Y_min, X_max, Y_max]

I have used two different arrays for dimensions but you can also any dynamic params in page.crop

cropped_size_1 = [0, 0, 400, 400]
cropped_size_2 = [300, 300, 800, 800]

updated_pdf = CombinePDF.new(pdf_path)
updated_pdf.pages.each_with_index do |page, index|
  if index % 2 == 0
    page.crop(cropped_size_1)
  else
    page.crop(cropped_size_2)
  end
end
updated_pdf.save(new_pdf_path)

P.S: Above solution actually do cropping under cover!

Upvotes: 1

demir
demir

Reputation: 4709

I tried to resize the pages assuming that each page has an image. I hope I understand correctly.

I used HexaPDF.

To run as a ruby project:

  1. mkdir foo
  2. cd foo
  3. bundle init
  4. Add gem 'hexapdf' to Gemfile
  5. bundle
  6. Create amend.rb file

    # amend.rb
    require 'hexapdf'
    
    pdf = HexaPDF::Document.open(ARGV[0])
    # page_dimensions = { page_index => { w: content_width (image), h: content_height (image) } }
    page_dimensions = { 0 => { w: 323, h: 115 }, 1 => { w: 504, h: 709 }, 2 => { w: 432, h: 443 } }
    padding = 70 # You can change it if you want
    pdf.pages.each do |page|
      media_box = page.box.value.dup
      # With media_box, you can set the page dimensions.
      # [left, bottom, right, top]
      # Bottom left values: [0, 0, 0, 0]
      # A4 page dimensions: [0, 0, 595, 842]
      media_box[1] = media_box[3] - page_dimensions[page.index][:h] - 2 * padding
      media_box[2] = page_dimensions[page.index][:w] + 2 * padding
      page[:MediaBox] = media_box
    end
    pdf.write(ARGV[1])
    
  7. Add your PDF file to foo directory. Let's call it X.pdf
  8. Run program

    ruby amend.rb X.pdf X_new.pdf
    
  9. Check X_new.pdf

Upvotes: 2

Related Questions