2016-12-02 27 views
-3

如何從一個rails db條目中檢索我的PDF二進制數據並將其輸出爲PDF格式?這是我到目前爲止,但這只是顯示和空的PDF文件:在RAILS中將二進制列條目轉換爲.pdf文件

def download 
    @submissions = Submission.all 

    # Create .pdf from binaries 
    @submissions.each do |sub| 
     @filePath = Rails.root.join('tmp/system/', sub.id.to_s, sub.file_file_name) 
     logger.error('Filepath here: ' + @filePath.to_s) 
     @content = Attachment.find_by! submission_id: 174 
     File.open(@filePath.to_s, 'w:binary') do |out| 
      out.write(@content.file_contents) 
     end 
    end 

爲什麼這不寫入任何東西到PDF文件?

+0

請閱讀 「[問]」 和 「[MCVE]」。我們需要更多關於你在做什麼的信息。向我們展示您爲解決此問題而編寫的最小代碼。如果你還沒有寫任何,那麼http://meta.stackoverflow.com/questions/261592將適用。除了二進制數據,'file_content'中有什麼?一個PDF文件? –

+0

我認爲這個問題很明確。您不需要關於此類問題的更多信息 –

回答

0

答案在這裏:

# Download zip file of all submission 
    def download 
    @submissions = Submission.all 

    # Create .pdf from binaries 
    @submissions.each do |sub| 
     @filePath = Rails.root.join('tmp/system/', sub.id.to_s) 
     Dir.mkdir(@filePath.to_s) 
     @content = Attachment.find_by! submission_id: sub.id 
     File.open((@filePath.to_s + '/' + sub.file_file_name.to_s), 'w+b') do |out| 
      out.write(@content.file_contents) 
     end 
    end 
end 
0

通常情況下,你可以只寫出來:

File.open('/tmp/whatever.pdf', 'w:binary') do |out| 
    out.write(model.file_content) 
end 

請記住,如果你需要一個真正的臨時文件,使用Tempfile

file = Tempfile.new 
file.write(model.file_content) 
file.close 

要使用此文件:

do_something_with_pdf(file.path) 

完成後,將其刪除:

file.unlink 
+0

非常感謝您的回覆@tadman。真的很感激它。不幸的是,我不能在星期一之前嘗試,但我會在這裏發表我的回覆。希望你的建議能起作用。非常感謝! –

+0

請參閱我上面更新的問題。這不能正確解碼pdf,不幸的是,即使編碼/解碼看起來不錯,我的pdf也無法打開 –

相關問題