1
votes

I have been using Ruby on Rails (version 5.2.1) with the RubyMine IDE for a project and am at a development stage in which I want to create some PDF-based reports. For this, I have grabbed the Prawn (version 2.2.2) gem. I set up a button that would download the PDF from a page:

<%= button_to "Download", action: :download_report %>

It is routed to the appropriate controller:

get 'pages#download_report' => 'pages#report_page'
post 'pages#download_report', action: :download_report, controller: 'pages'

And in the Pages controller, the download_report method is:

def download_report
    Prawn::Document.generate("hello.pdf") do
        text "Hello World!"
    end
    send_data("hello.pdf", filename: "hello.pdf", type: 'application/pdf')
end

The server runs fine in development and there is no error in utilizing the button. A PDF is sent and I can "open" it, but the PDF fails to load and will not open in any PDF reader that I have tried, including Microsoft Edge's and Adobe Acrobat Reader. I am perplexed as to why this error is happening, as it seems like this basic test should work. I am still relatively new to Ruby on Rails, so I would not be surprised if it is a basic error, but it is not one that I am easily seeing. Any help or advice is appreciated.

Thanks to anyone who responds in advance! Let me know if you want me to provide any more information to help diagnose the problem.

2
Have you checked the file size of the downloaded file? Is it maybe empty? - Axel Tetzlaff
@AxelTetzlaff: The file size was only nine bytes or so; the way in which the data was transmitted (using send_data) likely did not appropriately return the PDF and may have lost some of the data on the way. The answer below utilizing send_file seems to have solved my issue, however. Thanks! - Stephen Bothwell
I guess the content of the file was "hello.pdf" 😂 - Axel Tetzlaff

2 Answers

2
votes

Change send_data with send_file :

 def download_report
    Prawn::Document.generate("hello.pdf") do
      text "Hello World!"
    end
    send_file "hello.pdf",type: 'application/pdf'
end 
0
votes

I am using prawn a lot in my project and this is the config that i follow. Haven't faced any problem till now.

send_data your_file.render, filename: filename, type: "application/pdf"