在ruby中使用页面特定的脚注渲染pdf

时间:2012-07-11 13:00:27

标签: ruby pdf-generation wkhtmltopdf prawn

我正在寻找一种使用脚注呈现pdf文档的方法,其中脚注文本显示在与脚注引用相同的页面的页脚中(而不是文档结尾)。这种脚注出现在书籍中,例如译者的评论在哪里。能够将脚注ref与脚注文本链接是可选的。

到目前为止,我看了Prawn和PDFKit,但我似乎无法找到一个简单的解决方案。

这是我正在尝试做的一个示例:footnote sample

这就是我用Prawn想出来的。显然,这需要更多的工作来覆盖角落案件。我想知道是否值得在这条路线上走得更远,或者尝试一些完全不同的东西,比如乳胶(没有用过红宝石)。

Prawn::Document.generate("foo.pdf",:page_size => 'A4') do
  #read 150 lorem ipsum records of various length 
  records = File.read(
    Rails.root.join("lib/assets/lorem_ipsum_paragraphs.txt")
  ).split("\n").reject(&:blank?)
  #assign some random footnotes to the paragraphs
  footnotes = {
    1 => '* ' + records[120],
    2 => '* ' + records[54],
    11 => '* ' + records[2]
  }
  #this array will hold the current footnotes to draw
  #the assumption being we'll draw them on the current page as soon as we
  #reach the part of the page where we need to fit those
  footnotes_to_draw = []
  #this will hold the amount of space required to draw the footnotes
  space_needed = 0
  for i in 0..records.length
    str = records[i]
    if footnotes.keys.include? i
      str += '*'#this one has a footnote attached
      footnotes_to_draw << footnotes[i]
      space_needed += (height_of(footnotes[i]) + 15)
    end
    text "#{str}"
    if space_needed > 0
      #that means we will need to draw a footer on this page
      space_available = cursor
      puts "space needed: #{space_needed}, space available: #{space_available}"
      #check if we can still draw the next record, or now's the time'
      unless space_available - space_needed > height_of(records[i+1])
        puts "draw footer now"
        bounding_box [0,space_needed], :width => bounds.width, :height => space_needed do
          stroke_horizontal_rule
          footnotes_to_draw.each do |footnote|
            pad(10){text footnote}
          end
        end
        #reset current footnotes
        footnotes_to_draw = []
        space_needed = 0
        move_down space_needed
      end
    end
  end
end

0 个答案:

没有答案