pdforge logo

Product

Resources

Integrations

pdforge logo

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

How to Generate PDF from HTML with Rails Using WickedPDF

Written by

Written by

Marcelo Abreu, founder of pdforge

Marcelo | Founder of pdf noodle

Marcelo | Founder of pdf noodle

Last Updated

Last Updated

Oct 31, 2024

Oct 31, 2024

Tags

Tags

PDF Libraries

PDF Libraries

Ruby on rails

Ruby on rails

pdforge logo
pattern behind Call to action

Overview of WickedPDF: A Trusted PDF Library for Rails

WickedPDF is a powerful PDF library for Ruby on Rails that enables developers to generate PDF documents directly from HTML. By using wkhtmltopdf, WickedPDF converts HTML, CSS, and JavaScript into accurate, high-quality PDFs, capturing the intended style and layout seamlessly.

You can check out the full documentation here.

Comparison Between WickedPDF and Other Ruby PDF Libraries

Number of downloads from bestgems of WickedPDF

Ruby offers a range of PDF generation libraries, each with unique features:

  • Prawn and HexaPDF - Offer complete control over document structure, making them ideal for generating PDFs from scratch. However, they lack support for direct HTML conversion, which limits their flexibility for web-based applications.

  • PDFKit - Enable HTML-to-PDF conversion but don’t offer seamless integration with Rails, requiring extra configuration to work effectively within Rails projects.

  • Puppeteer-ruby and Grover - Uses a headless Chromium instance for rendering, offering excellent compatibility with complex HTML and JavaScript, though it may be heavier and more resource-intensive for simple PDF needs.

In comparison, WickedPDF Provides smooth HTML-to-PDF rendering with deep Rails integration, simplifying setup and use. It’s an excellent choice for Rails projects that need straightforward HTML-to-PDF generation. If you want to dig deeper on a comparison between WickedPDF and other Ruby pdf gems, we also have a detailed article with a full comparison between the best PDF gems for Ruby on rails in 2025.

Guide to generate pdf from html using Ruby on rails wickedPDF
Guide to generate pdf from html using Ruby on rails wickedPDF
Guide to generate pdf from html using Ruby on rails wickedPDF

Setting Up WickedPDF and Required Dependencies

Installing WickedPDF and PDF Rendering Dependencies

To get started, add the wicked_pdf gem to your Rails project, along with wkhtmltopdf, which handles the actual PDF rendering. Add the following to your Gemfile and install with bundle install:

# Gemfile
gem 'wicked_pdf'

After installing wicked_pdf, download wkhtmltopdf and ensure it’s accessible in your system path, or configure WickedPDF to locate it directly.

# Configure wkhtmltopdf in an initializer
WickedPdf.config = {
  exe_path: '/usr/local/bin/wkhtmltopdf' # Modify path as needed

Project Folder Structure

To organize your project for PDF generation, create dedicated folders for layout templates, style sheets, and any other assets used in your PDF files. You might structure it as follows:


Use pdf.html.erb as a base layout for your PDFs and keep custom styling in pdf.css to maintain a clean structure.

Configuring WickedPDF for HTML to PDF Conversion

Setting up global PDF configurations simplifies WickedPDF usage across your project. Create an initializer (config/initializers/wicked_pdf.rb) where you define options such as page orientation, page size, and default margin settings.

# config/initializers/wicked_pdf.rb
WickedPdf.config = {
  layout: 'pdf.html', # Custom PDF layout
  orientation: 'Portrait',
  page_size: 'A4',
  margin: { top: 10, bottom: 10, left: 10, right: 10

Generating PDFs from HTML in Ruby on Rails

Structuring HTML Templates for PDF Output

For structured PDF documents like invoices, create an HTML template that includes detailed sections, such as headers, itemized tables, and totals. In views/layouts/pdf.html.erb, set up the layout template:

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial, sans-serif; }
    .invoice-header { text-align: center; font-size: 24px; margin-bottom: 20px; }
    .invoice-details, .items-table { width: 100%; }
    .items-table th, .items-table td { padding: 8px; border-bottom: 1px solid #ddd; }
  </style>
</head>
<body>
  <div class="invoice-header">Invoice</div>
  <div class="invoice-details">
    <p>Invoice Number: <%= @invoice.number %></p>
    <p>Date: <%= @invoice.date %></p>
  </div>
  <table class="items-table">
    <thead>
      <tr><th>Description</th><th>Quantity</th><th>Price</th><th>Total</th></tr>
    </thead>
    <tbody>
      <% @invoice.items.each do |item| %>
        <tr>
          <td><%= item.description %></td>
          <td><%= item.quantity %></td>
          <td><%= number_to_currency(item.price) %></td>
          <td><%= number_to_currency(item.total) %></td>
        </tr>
      <

Using CSS for PDF Styling and Formatting with WickedPDF

Incorporate inline CSS within your HTML template or create an external stylesheet to control the layout, fonts, colors, and spacing. This approach maintains a consistent appearance for your PDF outputs. Using pdf.css helps keep the PDF styling separate, especially if it diverges from your main app styles.

Generating PDF Documents Programmatically with WickedPDF

To programmatically generate PDFs, set up a controller action that calls render pdf:. Here’s an example in the InvoicesController:

# app/controllers/invoices_controller.rb
def show
  @invoice = Invoice.find(params[:id])
  respond_to do |format|
    format.html
    format.pdf do
      render pdf: "invoice_#{@invoice.id}",
             template: 'invoices/show.pdf.erb',
             layout: 'pdf'
    end
  end
end

This code fetches the invoice record, then renders it in both HTML and PDF formats, allowing for seamless viewing.

Creating PDF Reports via Controller Actions in Rails

WickedPDF makes it simple to produce reports by adapting render pdf: in your controllers.

To create a custom report, pass data to the view, which will display it according to your defined layout. Rails helpers like link_to and number_to_currency can enhance report readability.

Handling Different File Delivery Options: Inline, Download, and Email

For flexibility in file delivery, WickedPDF allows you to specify disposition, which controls whether the PDF opens inline, prompts download, or attaches to an email. For example:

# Display PDF inline in the browser
render pdf: "inline_invoice", disposition: "inline"

# Prompt PDF download
render pdf: "download_invoice", disposition: "attachment"

Leveraging WickedPDF Options for Custom PDF Settings

Customize your PDFs using WickedPDF’s advanced options. For instance, adding headers and footers is straightforward with header and footer parameters, enabling you to insert branding or metadata at the top and bottom of each page. The disable_smart_shrinking option can also be helpful in addressing layout issues, making content scaling consistent across pages.

Alternative: Convert HTML to PDF Using pdf noodle

Homepage of pdf noodle

Managing HTML-to-PDF conversion at scale can quickly become a nightmare!

Especially in serverless environments where cold starts, memory limits, and headless browser quirks love to break at the worst possible time (we even wrote a full article about it). Add constant template iterations, version control headaches, and the need to support non-technical contributors, and suddenly your “simple PDF library” turns into an ongoing engineering project.

pdf noodle eliminates all of that.

Instead of maintaining brittle infrastructure or wrestling with outdated pdf libraries, pdf noodle gives you a battle-tested PDF generation API that just works!

Fast, scalable, and designed for both developers and non-developers. You send raw HTML or use our AI-powered template builder, and pdf noodle handles the rendering, scaling, optimization, and delivery so your team doesn’t have to.

Here's an example of a simple API request to generate your pixel-perfect PDF with just a few lines of code:

require 'net/http'
require 'json'
require 'uri'

class PdfApiService
  def self.generate_pdf(html_content)
    uri = URI("https://api.pdfnoodle.com/v1/html-to-pdf/sync")
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    request = Net::HTTP::Post.new(uri.path, {
      'Content-Type' => 'application/json',
      'Authorization' => "Bearer your-api-key"
    })
    request.body = {
      html: html_content
    }.to_json
    response = http.request(request)
    response.body if response.is_a?(Net::HTTPSuccess)
  end
end

pdf noodle also includes a powerful AI Agent that can generate PDF templates instantly, along with a modern editor for refining the design, also using AI, to match your brand. You don't need developing or design experience to quickly update layouts, adjust styling, and manage template versions.

Here’s a quick demo showing how it works:

You can create your account and design your first template without any upfront payment.

Conclusion

Choosing the right PDF library depends on your project’s specific needs:

WickedPDF is ideal for HTML-to-PDF conversions within Rails, particularly for documents like invoices or reports that rely on HTML layouts.

Prawn or HexaPDF are better suited for highly customized PDFs built from scratch.

If you don't want to waste time maintaining pdfs layouts and their infrastructure or if you don't want to keep track of best practices to generate PDFs at scale, third-party PDF APIs like pdf noodle will save you hours of work and deliver a high quality pdf layout.

Generating pdfs can be annoying!

Let us help you make it easier while you focus on what truly matters for your company.

pdforge logo
pattern behind Call to action

Generating pdfs can be annoying!

Let us help you make it easier while you focus on what truly matters for your company.

pdforge logo
pattern behind Call to action

Generating pdfs can be annoying!

Let us help you make it easier while you focus on what truly matters for your company.

pdforge logo
pattern behind Call to action

Table of contents

Automate PDF Generation in minutes

No code or design experience needed

AI creates your template in seconds

Fine tune the design in our friendly builder

Generate PDFs with our API or integrations