How to shrink Barby barcode to fit on PDF page siz

2019-07-23 13:20发布

I am generating a barcode using Barby and adding it to a PDF generated with Prawn. The barcode can be variable length, so I want to be able to shrink its width to ensure it fits on the PDF.

I can shrink the barcode's width by adding xdim: <scale factor> to the annotate_pdf options. However, I don't know how to tell if my barcode will overrun the PDF page size and then what scale factor to use.

app/pdfs/item_pdf.rb

require 'barby'
require 'barby/barcode/code_128'
require 'barby/outputter/prawn_outputter'

class ItemPdf < Prawn::Document
  def initialize(item)
    super(page_size: [79.2, 254.88],
          margin: 9,
          page_layout: :landscape)
    @item = item

    font_size 16
    job_name
    item_number
    barcode
  end

  def job_name
    text_box "Job: #{@item.job.name}", 
             height: 20,
             at: [0, 60],
             overflow: :shrink_to_fit
  end

  def item_number
    text_box "Item: \##{@item.number}",
             height: 20,
             at: [0, 40],
             overflow: :shrink_to_fit
  end

  def barcode
    barcode = Barby::Code128.new @item.number
    barcode.annotate_pdf(self, height: 25)
  end
end

1条回答
做自己的国王
2楼-- · 2019-07-23 13:38

Ok; the height option isn't valid for 2D barcodes, for the same reason that width isn't available for any barcode: It's not possible to impose those dimensions on the result without corrupting it.

source: https://github.com/toretore/barby/issues/30. you can find the source code from here.

so one option you have is saving the barcode as a png image file and then you can resize it to fit pdf width using prawn.

查看更多
登录 后发表回答