Search code examples
ruby-on-rails-4pdf-generation

Rails combining pdfs from action stream


I have an action in my controller #applications that renders a html page of my websites application page. When I specify the path for this action with the :pdf format it will render the page as a pdf (which works correctly).

I am writing another action #applications_print_version that needs to contain the rendered view from #applications plus some other pdfs (from a list of urls). Using combine_pdf I have been able to get the list of pdfs via urls working, but I can not get the #applications view to be added to the combined pdf in the #applications_print_version working.

Here is what I have so far.

def applications_print_version
    html = render_to_string(action: :applications) 
    pdf = WickedPdf.new.pdf_from_string(html) 

    new_pdf = CombinePDF.new
    new_pdf << CombinePDF.parse(pdf)

    #List of pdfs I got from somewhere else
    @pdf_attachments.each { |att| new_pdf << CombinePDF.parse( Net::HTTP.get( URI.parse( att.url ) ) ) }

    send_data new_pdf.to_pdf, :disposition => 'inline', :type => "application/pdf"
end

This solution does have all the data, but the pdf variable has no styling. I can't seem to get this to work.


Solution

  • Thanks to a local community support I have managed to get it to work. There were a few things I needed to fix.

    The layout that I was using to render #applications was using my standard pdf layout that I used for PDFKit. I duplicated the layout and replaced

    <%= stylesheet_link_tag 'application' %>
    

    with

    <%= wicked_pdf_stylesheet_link_tag 'application' %>
    

    One I did that I could render the #applications action with the layout the WickedPDF needed.

    html = render_to_string(action: :applications, layout: 'wicked_pdf') 
    

    I ran into another issue. There is a known issue with WickedPDF https://github.com/mileszs/wicked_pdf/issues/470

    So I had to remove any instances of @import "bootstrap" in my stylesheets which is not ideal, but I could not resolve the above issue.

    Any now the #applications_print_version works correctly!

    If anyone can do better, please let me know, I would like to know :)