2013-04-29 105 views
2

使用docsplit gem我可以從PDF或任何其他文件類型中提取文本。例如,使用以下行:使用docsplit從內存中的文檔中提取文本

Docsplit.extract_pages('doc.pdf') 

我可以擁有PDF文件的文本內容。

我目前正在使用Rails,並通過請求發送PDF並存在內存中。查看API和源代碼,我找不到從內存中提取文本的方法,只能從文件中提取文本。

有沒有辦法讓這個PDF的文本避免創建一個臨時文件?如果它很重要,我正在使用attachment_fu

回答

0

如果您擁有字符串中的內容,請使用StringIO創建IO可以讀取的類文件對象。在StringIO中,如果內容是真正的文本或二進制文件,它們都是相同的。

看任:

 
new(string=""[, mode]) 
Creates new StringIO instance from with string and mode. 

open(string=""[, mode]) {|strio| ...} 
Equivalent to ::new except that when it is called with a block, it yields with the new instance and closes it, and returns the result which returned from the block. 
+0

這就是我一直在尋找,謝謝 – fotanus 2013-04-30 00:39:46

+0

其實這不是我所期待的。 Docsplit需要一個文件路徑作爲輸入,而我不能從一個字符串獲取它。輸出同樣的東西。 – fotanus 2013-04-30 18:54:20

+0

如果你需要一個文件路徑,你將不得不把它寫出到磁盤。 Tempfile可以工作,或者是一個普通的'File.write',然後是'File.delete'。 – 2013-04-30 19:05:41

2

使用的臨時目錄:

require 'docsplit' 

def pdf_to_text(pdf_filename) 
    Docsplit.extract_text([pdf_filename], ocr: false, output: Dir.tmpdir) 

    txt_file = File.basename(pdf_filename, File.extname(pdf_filename)) + '.txt' 
    txt_filename = Dir.tmpdir + '/' + txt_file 

    extracted_text = File.read(txt_filename) 
    File.delete(txt_filename) 

    extracted_text 
end 

pdf_to_text('doc.pdf')