When Saving a wicked_pdf PDF file to active storage, the pdf is corrupted

182 Views Asked by At

I want to save the generated PDF as an Active Storage attachement.

pdf = WickedPdf.new.pdf_from_string(
      render_to_string(pdf: 'SurveyReportForm', template: '/screenings/test', layout: 'pdf',  formats: :pdf)
     )

 
@screening.report.attach(
  io: StringIO.new(pdf),
  filename: "#{@screening.id}-report",
  content_type: 'application/pdf'
)

The code runs without errors. However when I then click the link to view the pdf

 <%= link_to "Download Report", rails_blob_path(@screening.report, disposition: "attachment") %>

I get a pdf that has what looks like pdf binary/source code on the page, starting with:

%PDF-1.4 1 0 obj << /Title (þÿ) /Creator (þÿwkhtmltopdf 0.12.6) /Producer (þÿQt 4.8.7...

What has gone wrong? How can I debug this to work out if the problem is in pdf generation or how I'm saving it and how can I fix it?

1

There are 1 best solutions below

0
Unixmonkey On

The issue isn't with ActiveStorage, but with the download not being served with the correct Mime type for a PDF. Because you aren't specifying it, it is being served as text/plain instead of application/pdf.

I think you might be able to change this by registering a PDF Mime type, like the WickedPDF README tells you:

Mime::Type.register "application/pdf", :pdf

This should instruct Rails to know that when serving a PDF, to serve it with that mime type.

Otherwise, you could create a controller endpoint to download the PDF like this:

def download
  send_file rails_blob_path(@screening.report),
    disposition: "attachment",
    content_type: "application/pdf"
end

# or

def download
  pdf = # retrieve PDF contents
  send_data pdf, filename: "mypdf.pdf",
    disposition: "attachment",
    content_type: "applicaton/pdf"
end