PDF view
# avo-2
f
Hi, what would be the best way to have pdf views on a given resource? I want to generate invoice PDFs by using the standard html templating.
l
Hi @future-author-97799 there are at least two possibilities to achieve a PDF view on a resource Custom field ( have some advantages, for example you can use it on the sidebar and have an PDF preview on the whole resource's sidebar ) https://docs.avohq.io/2.0/custom-fields.html Resource tools https://docs.avohq.io/2.0/resource-tools.html Not sure which one fits better on your use case
f
You mean I could achieve what would be some :
Copy code
def show
    @expense = Expense.find(params[:id])
    respond_to do |format|
      format.html
      format.pdf do
        render pdf: 'file_name'   # Excluding ".pdf" extension.
      end
    end
  end
and have the PDF downloadable?
l
Let's pick the custom field option. You'll be able to control all the code inside that field. That means you can do an image tag with the file preview and I think you can wrap it into a link that redirects to an endpoint that starts the download
f
yes, but this endpoint is outside of avo, right?
I mean, I need to create this endpoint outside of avo?
l
Your choise, you can create it to point to one of your avo controllers
f
but then, how do I implement he pdf format in the avo controller?
l
Ok, let's do it step by step, i'm aslo not sure how to handle it on the controller
frist you have to create the custom field
rails g avo:field pdf_preview
Go to
app/components/avo/fields/pdf_preview_field/show_component.html.erb
and replace the code there with
Copy code
ruby
<%= field_wrapper **field_wrapper_args do %>
  <%= image_tag helpers.main_app.url_for(@field.value.preview(resize_to_limit: [600, 600])), class: 'rounded-lg object-cover' %>
<% end %>
go to your resource and use the field and check if it works
field :your_pdf_file_name, as: :pdf_preview
let me know if everything is fine until here
Also, let me know if you find any obstacle, after you arive here we only need 1 more easy step and you'll have it downloadable (without any custom endpoint needed)
f
Thanks, I misexplained my scenario. In your example, I need to have a PDF file attached to my model, but I want to generate it on the fly from a html template
l
Ahhh got it, I misunderstood the use case You can give it a try and generate it inside the component (not ideal) Or use an resource tool and generate it on the show endpoint like the code snippet you posted above.
f
yes, I think aving a custom endpoint for that, would be the cleanest.
I won't be able to rewrite the avo/expenses#show with my pdf rendering, right?
l
You can do that but i don't think you want to override the whole resource show endpoint, i think it's beter to have the pdf related only on the resource tool endpoint
f
agree, thanks for your help !
l
Anytime!