Search code examples
ruby-on-railsrubypdfpdf-generationprawn

Ruby on Rails: Prawn Gem Generates PDF, but PDF Cannot Display


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.


Solution

  • 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