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?
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/plaininstead ofapplication/pdf.I think you might be able to change this by registering a PDF Mime type, like the WickedPDF README tells you:
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: