DEV Community

Dmitry Voronov for JetRockets

Posted on • Edited on • Originally published at jetrockets.pro

2 1

Render and combine PDF files into one

Render PDF files from HTML templates in Rails can be done using WickedPDF.

First you need to use ActionView to render HTML to a string:

def render_to_string(data)
  action_view = ActionView::Base.new
  action_view.view_paths = ActionController::Base.view_paths

  action_view.class_eval do
    include ApplicationHelper
    include PDFHelper
    # or other helpers
  end

  action_view.render template: 'pdf/template.html',
                     layout: 'layout/pdf.html',
                     locals: { data: data }
end
Enter fullscreen mode Exit fullscreen mode

Then you can render pdf with the desired settings like this:

# first pdf file with some view settings and values from data1...
pdf1 = WickedPdf.new.pdf_from_string(
        render_to_string(data1), {
            pdf: 'report1',
            page_size: 'Letter',
            orientation: 'Portrait'
        })
# ...and second pdf file with some view settings and values from data2
pdf2 = WickedPdf.new.pdf_from_string(
        render_to_string(data2), {
            pdf: 'report2',
            page_size: 'Letter',
            orientation: 'Landscape'
        })
Enter fullscreen mode Exit fullscreen mode

And now you can combine it with CombinePDF gem, that provide you parse method to get PDF content and to_pdfmethod to render the result back to PDF.

combiner = CombinePDF.new
combiner << CombinePDF.parse(pdf1)
combiner << CombinePDF.parse(pdf2)
combiner.to_pdf
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay