![](/img/trans.png)
[英]Customizing a Ruby Struct with pre-defined definitions and a custom block
[英]Calling pre-defined code from within a Ruby block
我正在嘗試使用PrawnPDF制作高度格式化的文檔,並且希望有一種方法來調用函數,以在不同的地方一遍又一遍地生成特定的文本。 我有這個
@pdf = Prawn::Document.new(:margin => [5, 5], :page_size => 'A4') do
text
text
<insert general text>
text
text
<insert general text>
etc etc
end
pdf.generate("output.pdf")
我要插入的一般文字是這樣的:
pdf.bounding_box([column_check,pdf.cursor], :width => 250, :height => 12) do
pdf.stroke_color "894131"
pdf.stroke do
pdf.fill_color "894131"
pdf.fill_and_stroke_rounded_rectangle [pdf.cursor - 12,pdf.cursor], 288, 12, 0
pdf.fill_color 'FFFFFF'
end
pdf.pad(5) do
pdf.draw_text(prices[:manganese], :at => [4, pdf.cursor - 4], :size => 6)
end
pdf.fill_color '000000'
end
pdf.move_down 2
(我更改了將PDF生成為隱式的方式)
看起來我不能從Prawn :: Document.new塊中調用函數,如何解決呢? 我不太了解編程,所以我覺得有一個使用yield塊或proc的解決方案,或者我沒有太多經驗的解決方案...
(基本上,每次我打電話時,我都希望能夠為價格哈希調用不同的符號)
因為需要訪問超出塊范圍的方法,所以我將generate()
與顯式塊形式一起使用:
def general_text(pdf)
pdf.bounding_box(...) do
# ...
end
pdf.move_down 2
end
@pdf = Prawn::Document.generate("output.pdf", {:margin => [5, 5], :page_size => 'A4'}) do |pdf|
pdf.text
pdf.text
general_text(pdf)
pdf.text
pdf.text
general_text(pdf)
# ...
end
我自己沒有檢查,但認為應該可以。
更新要使用不同的鍵進行哈希,請在general_text()方法中添加另一個參數:
def general_text(pdf, key)
# ... prices[key] ...
end
@pdf = Prawn::Document.generate(...) do |pdf|
...
general_text(pdf, :manganese)
...
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.