In my Rails 7 app to PDF creation I'm using external service. To get PDF I have to send a GET request and in the response I'm receiving encoded string. Now I would like to give the possibility to download this file without saving it on the server.
How to do so? all searched topics are almost 10y old, is it some modern way (or maybe a gem) to do so ?
Everything I found actually boils down to the code below:
# service which I'm using to create generate pdf from string
class PdfGenerator
def initialize(binary_pdf)
@binary_pdf = binary_pdf
end
attr_reader :binary_pdf
def call
File.open('invoice.pdf', 'wb') do |file|
content = Base64.decode64(binary_pdf)
file << content
end
end
end
# payments_controller.rb
def pdf_download
response = client.invoice_pdf(payment_id: params[:id]) # get request to fetch pdf
PdfGenerator.new(response[:invoice_pdf]).call
end
View where I'm hitting pdf_download endpoint:
<%= link_to t('.pdf_download'), pdf_download_payment_path(payment.id), data: { 'turbo-method' => :post } %>
I expected to start downloading the file but nothing like that happened. In rails server I'm receiving below message instead:
No template found for PaymentsController#pdf_download, rendering head :no_content Completed 204 No Content in 8ms (ActiveRecord: 0.2ms | Allocations: 2737)