我一直在嘗試一個簡單的Ruby程序來解析一個簡單的pdf文件並提取我感興趣的文本。我發現pdf-reader是相當不錯的PDF文件解析gem。我已經閱讀了那個寶石和一些tutorials的例子。如何在Ruby中解析pdf
我已經嘗試了回調方法,並能夠從我的pdf文件中獲取所有文本。但是我不理解某些回調的論點背後的概念。
例如,如果我的pdf有一個簡單的表,有3列和2行。 (標題行的值是姓名,地址,年齡)和第一行值(阿倫,霍斯科泰,22),並當U運行紅寶石以下Ruby腳本
receiver = PDF::Reader::RegisterReceiver.new
reader = PDF::Reader.new("Arun.pdf")
reader.pages.each do |page|
page.walk(receiver)
receiver.callbacks.each do |cb|
puts cb.inspect
end
end
它打印出一系列回調的其中一些有趣的回調show_text_with_positioning就像下面
{:name=>:show_text_with_positioning, :args=>[["N", 5, "am", -4, "e"]]}
{:name=>:show_text_with_positioning, :args=>[[" "]]}
{:name=>:show_text_with_positioning, :args=>[["Ad", 6, "d", 3, "ress"]]}
{:name=>:show_text_with_positioning, :args=>[[" "]]}
{:name=>:show_text_with_positioning, :args=>[["Age"]]}
{:name=>:show_text_with_positioning, :args=>[[" "]]}
{:name=>:show_text_with_positioning, :args=>[["Ar", 4, "u", 3, "n"]]}
{:name=>:show_text_with_positioning, :args=>[[" "]]}
{:name=>:show_text_with_positioning, :args=>[["H", 3, "o", -5, "sk", 9, "o", -5, "te"]]}
{:name=>:show_text_with_positioning, :args=>[[" "]]}
{:name=>:show_text_with_positioning, :args=>[["22"]]}
{:name=>:show_text_with_positioning, :args=>[[" "]]}
從上面的回調,這是什麼ARGS表示針對PDF文件?如果我想在這裏只提取名爲'Arun'的名字值(任何東西都可以到這裏)或者年齡值i'e'25'(任何值都可以在這裏),那麼我怎樣才能在ruby程序中做到這一點?是否有任何pdf-parser API或Ruby API只能從pdf文件中獲取單個「感興趣」的值?
如何編寫一個Ruby程序來訪問我感興趣的特定回調?
receiver = PDF::Reader::TextReceiver.new($stdout)
PDF::Reader.file("Arun.pdf", receiver)
一旦你的文字,你可以使用常規: