Wicked PDF

repository·master·Indexed 25 days ago

https://github.com/mileszs/wicked_pdf

A Ruby on Rails plugin for generating PDF documents from HTML views using the wkhtmltopdf shell utility. It provides controller integration via the render pdf: option, specialized asset helpers for absolute paths, and Rack middleware for automatic PDF rendering of URLs. Supports advanced configuration for page sizes, orientations, headers, footers, and generating PDFs from strings, files, or URLs.

Tokens
4.7K
Snippets
10
Records
41
Agent score
85%

What's inside wicked_pdf

  1. Use wicked_pdf helpers with Webpacker

    master

    For Webpacker assets, use the following specific helpers:

    • wicked_pdf_stylesheet_pack_tag for stylesheets
    • wicked_pdf_javascript_pack_tag for javascripts
    • wicked_pdf_asset_pack_path("path/to/asset") to get a path for use with standard helpers like image_tag.
  2. Implement page numbering

    master

    To add page numbers, you can use a JavaScript snippet in your template that targets specific classes. The classes page and topage will be automatically filled by the script.

    Option 1: JavaScript approach Include this in your header/footer template:

    <script>
      function number_pages() {
        var vars={};
        var x=document.location.search.substring(1).split('&');
        for(var i in x){var z=x[i].split('=',2);vars[z[0]] = decodeURIComponent(z[1]);}
        var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];
        for(var i in x){
          var y = document.getElementsByClassName(x[i]);
          for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];
        }
      }
    </script>
    <body onload="number_pages()">
      Page <span class="page"></span> of <span class="topage"></span>
    </body>

    Option 2: wkhtmltopdf built-in approach Use the special [page] and [topage] tokens in your header/footer configuration:

    render pdf: 'filename', header: { right: '[page] of [topage]' }
  3. Install Wicked PDF and wkhtmltopdf

    master

    Wicked PDF is a Ruby on Rails plugin that uses the wkhtmltopdf shell utility to generate PDFs from HTML.

    1. Add gem 'wicked_pdf' to your Gemfile and run bundle install.
    2. Generate the initializer: rails generate wicked_pdf.
    3. (Optional) For older Rails versions, register the PDF mime type in config/initializers/mime_types.rb:
      Mime::Type.register "application/pdf", :pdf
    4. Install the wkhtmltopdf binary. The easiest way on Linux or OSX is to add gem 'wkhtmltopdf-binary' to your Gemfile and run bundle install.
    gem 'wicked_pdf'
    gem 'wkhtmltopdf-binary'
  4. Use wicked_pdf helpers for assets

    master

    Because wkhtmltopdf runs outside of Rails, standard layouts may not work with relative asset paths. Use these helpers to provide absolute references:

    • wicked_pdf_stylesheet_link_tag "name"
    • wicked_pdf_javascript_include_tag "name"
    • wicked_pdf_image_tag "name"

    Note for Asset Pipeline users: If using the asset pipeline, these helpers may raise an error if the /assets/ prefix is included. A workaround is to use wicked_pdf_asset_base64("name") to inline assets as base64, though this is slower for large files.

    <!doctype html>
    <html>
      <head>
        <meta charset='utf-8' />
        <%= wicked_pdf_stylesheet_link_tag "pdf" %>
        <%= wicked_pdf_javascript_include_tag "number_pages" %>
      </head>
      <body onload='number_pages'>
        <div id="header">
          <%= wicked_pdf_image_tag 'mysite.jpg' %>
        </div>
        <div id="content">
          <%= yield %>
        </div>
      </body>
    </html>
  5. Use Wicked PDF Middleware

    master

    You can use Rack Middleware to automatically generate PDF views for all URLs by appending .pdf to the request.

    Add this to application.rb or environment.rb:

    require 'wicked_pdf'
    config.middleware.use WickedPdf::Middleware

    You can restrict the middleware using :only or :except options:

    # Only for /invoice
    config.middleware.use WickedPdf::Middleware, {}, only: '/invoice'
    
    # Except for admin and specific patterns
    config.middleware.use WickedPdf::Middleware, {}, except: [ %r[^/admin], '/secret', %r[^/people/\d] ]
    require 'wicked_pdf'
    config.middleware.use WickedPdf::Middleware, {}, only: '/invoice'
  6. Configure wkhtmltopdf executable path

    master

    If the wkhtmltopdf binary is not in your webserver's PATH, configure it in your Wicked PDF initializer:

    WickedPdf.configure do |c|
      c.exe_path = '/usr/local/bin/wkhtmltopdf'
      c.enable_local_file_access = true
    end
  7. Integrate Wicked PDF into Rails via Railtie

    master

    Wicked PDF includes a WickedRailtie that automatically integrates the library into the Rails boot process. When used in a Rails application, it performs the following setup:

    1. Prepends PdfHelper to ActionController::Base, making PDF generation methods available in your controllers.
    2. Includes WickedPdfHelper::Assets in ActionView, enabling asset support within your PDF templates.
    3. Registers the application/pdf MIME type if it is not already defined.
  8. Debug PDF rendering as HTML

    master

    To design your PDF faster, you can view the content as plain HTML in your browser.

    1. Configure the controller to support a debug parameter: show_as_html: params.key?('debug')
    2. Access the URL with the debug parameter: http://localhost:3001/CONTROLLER/X.pdf?debug

    Note: When debugging, wicked_pdf_* helpers use file:/// paths. To prevent browser cross-domain errors from blocking assets, use a conditional in your template:

    <%= params.key?('debug') ? image_tag('foo') : wicked_pdf_image_tag('foo') %>
  9. Basic Usage: Render PDF in a Controller

    master

    To serve a PDF in a Rails controller, use the render pdf: option within a respond_to block. The filename should exclude the .pdf extension.

    class ThingsController < ApplicationController
      def show
        respond_to do |format|
          format.html
          format.pdf do
            render pdf: "file_name"
          end
        end
      end
    end
  10. Super Advanced Usage: Generate PDF from strings, files, or URLs

    master

    You can use WickedPdf.new to generate PDFs outside of the standard Rails controller render flow:

    • From a string: WickedPdf.new.pdf_from_string('<html>...</html>')
    • From an HTML file: WickedPdf.new.pdf_from_html_file('/absolute/path/to/file.html')
    • From a URL: WickedPdf.new.pdf_from_url('https://example.com')

    To save a generated PDF string to a file manually:

    pdf = render_to_string(pdf: "some_file", template: "templates/pdf")
    save_path = Rails.root.join('pdfs','filename.pdf')
    File.open(save_path, 'wb') { |file| file << pdf }