### Install wkhtmltopdf on Debian/Ubuntu Source: https://github.com/mileszs/wicked_pdf/wiki/Getting-Started-Installing-wkhtmltopdf This snippet details the process of installing the wkhtmltopdf static binary on Debian/Ubuntu-based Linux systems. It involves removing existing installations, installing dependencies, downloading the binary, extracting it, changing ownership, and moving it to a system-wide executable path. ```bash sudo apt-get remove --purge wkhtmltopdf sudo apt-get install openssl build-essential xorg libssl-dev wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-i386.tar.bz2 tar xvjf wkhtmltopdf-0.9.9-static-i386.tar.bz2 sudo chown root:root wkhtmltopdf-i386 sudo cp wkhtmltopdf-i386 /usr/bin/wkhtmltopdf ``` -------------------------------- ### Configure wicked_pdf initializer for Windows Source: https://github.com/mileszs/wicked_pdf/wiki/Getting-Started-Installing-wkhtmltopdf This snippet shows how to configure the wicked_pdf gem on Windows 8 x64 by creating an initializer file. It specifies the executable path for wkhtmltopdf. Ensure the server has write permissions to the specified location. ```ruby WickedPdf.config = { :exe_path => '#SITE\wkhtmltopdf\wkhtmltopdf.exe' } ``` -------------------------------- ### Install wkhtmltopdf-binary Gem Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md To use Wicked PDF, you need to install the wkhtmltopdf executable. This gem provides a convenient way to install a compatible version of wkhtmltopdf on most systems. Add it to your Gemfile and run `bundle install`. ```ruby gem 'wkhtmltopdf-binary' ``` -------------------------------- ### Basic PDF Generation in Rails Controller Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md This example demonstrates how to generate a PDF response in a Rails controller. The `respond_to` block handles HTML requests as usual and specifies PDF generation for the `.pdf` format, rendering a file named 'file_name.pdf'. ```ruby class ThingsController < ApplicationController def show respond_to do |format| format.html format.pdf do render pdf: "file_name" # Excluding ".pdf" extension. end end end end ``` -------------------------------- ### Wicked PDF wkhtmltopdf Binary Options Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md This section explains how to pass options directly to the `wkhtmltopdf` binary for finer control over Webkit rendering before PDF generation. Examples include `print_media_type` and `no_background`. Refer to the `wkhtmltopdf` documentation for a full list of global options. ```ruby print_media_type: true # Passes `--print-media-type` no_background: true # Passes `--no-background` ``` -------------------------------- ### Configure Wicked PDF Executable Path Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md If the wkhtmltopdf executable is not in your system's PATH, you can configure its location within a Rails initializer. This example shows how to set the `exe_path` and enable local file access. ```ruby WickedPdf.configure do |c| c.exe_path = '/usr/local/bin/wkhtmltopdf' c.enable_local_file_access = true end ``` -------------------------------- ### Install Wicked PDF Gem Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Add the Wicked PDF gem to your Gemfile to integrate PDF generation capabilities into your Rails application. Ensure you run `bundle install` after adding the gem. ```ruby gem 'wicked_pdf' ``` -------------------------------- ### Wicked PDF Helpers for Layouts (No Asset Pipeline) Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md When generating PDFs, standard Rails asset helpers may not work. Use Wicked PDF's specific helpers like `wicked_pdf_stylesheet_link_tag`, `wicked_pdf_image_tag`, and `wicked_pdf_javascript_include_tag` to correctly reference assets in your PDF layout. This example shows how to include a stylesheet, JavaScript for numbering pages, and an image. ```html <%= wicked_pdf_stylesheet_link_tag "pdf" -%> <%= wicked_pdf_javascript_include_tag "number_pages" %>
<%= yield %>
``` -------------------------------- ### PDF View Template Source: https://github.com/mileszs/wicked_pdf/wiki/Background-PDF-creation-via-delayed_job-gem This HTML+ERB code defines the structure and content of a PDF document generated by Wicked PDF. It includes basic HTML setup, meta tags, and a reference to a stylesheet. The content dynamically displays the document ID. ```html+erb PDF Doc <%= wicked_pdf_stylesheet_link_tag 'pdf' %> <% @doc = doc %>

The doc ID is: <%= @doc.id %>.

``` -------------------------------- ### Use CDN Reference for jQuery with Wicked PDF (Rails) Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md When using Wicked PDF, you can leverage standard Rails helpers to reference assets from a Content Delivery Network (CDN). This example demonstrates how to include specific versions of jQuery and jQuery UI using `javascript_include_tag`, pointing to external CDN URLs. This approach is useful for reducing your application's asset load and ensuring fast delivery of common libraries. ```html <%= javascript_include_tag "http://code.jquery.com/jquery-1.10.0.min.js" %> <%= javascript_include_tag "http://code.jquery.com/ui/1.10.3/jquery-ui.min.js" %> ``` -------------------------------- ### Debugging PDF Rendering in Rails with WickedPDF Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Enable debug mode to view PDF content as plain HTML in the browser for faster design iteration. This requires configuring a render parameter and using a GET parameter in the URL. Assets might need special handling due to cross-domain policies. ```Ruby render :pdf => "some_file_name", :show_as_html => params.key?('debug') ``` ```erb <%= params.key?('debug') ? image_tag('foo') : wicked_pdf_image_tag('foo') %> ``` -------------------------------- ### ActionView::Base Initialization for Rails 6 Source: https://github.com/mileszs/wicked_pdf/wiki/Background-PDF-creation-via-delayed_job-gem This Ruby snippet provides the correct way to initialize `ActionView::Base` for Rails 6, addressing compatibility issues. It uses `ActionView::LookupContext` and `ActionView::ViewPaths.all_view_paths` for proper view path resolution. ```ruby av = ActionView::Base.new(ActionView::LookupContext.new(ActionView::ViewPaths.all_view_paths)) ``` -------------------------------- ### PDF Generation using ApplicationController.render (Rails 6.1+) Source: https://github.com/mileszs/wicked_pdf/wiki/Background-PDF-creation-via-delayed_job-gem For Rails 6.1 and later, this Ruby code demonstrates simplifying PDF generation by using `ApplicationController.render` directly, eliminating the need to instantiate `ActionView::Base` manually. This approach is more streamlined for rendering templates. ```ruby # Use ApplicationController.render instead of av.render # No need to create av instance separately ``` -------------------------------- ### Delayed Job for PDF Generation (Rails < 6.1) Source: https://github.com/mileszs/wicked_pdf/wiki/Background-PDF-creation-via-delayed_job-gem This Ruby code defines a `GeneratePdfJob` class for Delayed Job. It includes a `perform` method to render a PDF using Wicked PDF and an `ActionView::Base` instance, and a `success` callback to update the document status. It sets up view paths and includes necessary helpers for rendering. ```ruby class GeneratePdfJob < Struct.new(:doc_id) # delayed_job automatically looks for a "perform" method def perform # create an instance of ActionView, so we can use the render method outside of a controller av = ActionView::Base.new() av.view_paths = ActionController::Base.view_paths # need these in case your view constructs any links or references any helper methods. av.class_eval do include Rails.application.routes.url_helpers include ApplicationHelper end pdf_html = av.render :template => "docs/pdf.html.erb", :layout => nil, :locals => {:doc => doc} # use wicked_pdf gem to create PDF from the doc HTML doc_pdf = WickedPdf.new.pdf_from_string(pdf_html, :page_size => 'Letter') # save PDF to disk pdf_path = Rails.root.join('tmp', "#{doc.id}.pdf") File.open(pdf_path, 'wb') do |file| file << doc_pdf end end # delayed_job's built-in success callback method def success(job) doc.update_attribute(:status, 'complete') end private # get the Doc object when the job is run def doc @doc = Doc.find(doc_id) end end ``` -------------------------------- ### Precompile Assets for Wicked PDF (Rails) Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Precompiling assets used in PDF views is crucial for avoiding deployment issues. This configuration ensures that assets are correctly served in production environments where `config.assets.compile` is typically set to `false`. Add the necessary CSS and JavaScript files to the `config.assets.precompile` array in your `application.rb` or environment-specific configuration file. ```ruby config.assets.precompile += ['blueprint/screen.css', 'pdf.css', 'jquery.ui.datepicker.js', 'pdf.js', ...etc...] ``` -------------------------------- ### Precompile Rails Assets Source: https://github.com/mileszs/wicked_pdf/wiki/Configuring-wicked_pdf-for-Bootstrap This command compiles all assets (JavaScript, CSS, images) for the development environment, making them available for use by the application and Wicked PDF. This is a standard Rails maintenance task. ```bash rake assets:precompile RAILS_ENV=development ``` -------------------------------- ### Configure Wicked PDF Defaults Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Sets default configuration options for all PDF generations within the application. This is typically done in the `wicked_pdf.rb` initializer file located in the Rails `config/initializers` directory. -------------------------------- ### Generate PDF from HTML File Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Creates a PDF document from a local HTML file. The file path must be an absolute path. No external dependencies beyond the Wicked PDF gem are specified. ```ruby pdf = WickedPdf.new.pdf_from_html_file('/your/absolute/path/here') ``` -------------------------------- ### Generate PDF from URL Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Generates a PDF by fetching content from a given URL. This method requires an active internet connection to access the specified URL. The output is a PDF file. ```ruby pdf = WickedPdf.new.pdf_from_url('https://github.com/mileszs/wicked_pdf') ``` -------------------------------- ### Adjusting wkhtmltopdf DPI for Cross-Platform Consistency Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md wkhtmltopdf can render at different resolutions across platforms (e.g., Linux vs. Windows). Use the `:zoom` option with a value like `0.78125` (75/96) to align rendering resolution between platforms and ensure consistent output. ```Ruby render :pdf => "output.pdf", :zoom => 0.78125 ``` -------------------------------- ### Enable Wicked PDF Rack Middleware Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Integrates Wicked PDF as Rack middleware to automatically generate PDF views for URLs ending in `.pdf`. This requires adding the middleware to the Rails application's configuration. ```ruby # in application.rb (Rails3) or environment.rb (Rails2) require 'wicked_pdf' config.middleware.use WickedPdf::Middleware ``` -------------------------------- ### Wicked PDF Asset Helpers for Webpacker Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Wicked PDF provides specific helpers for integrating with Webpacker, Rails' default JavaScript bundler. Use `wicked_pdf_stylesheet_pack_tag` for stylesheets, `wicked_pdf_javascript_pack_tag` for JavaScript, and `wicked_pdf_asset_pack_path` to reference other assets like images directly. ```html # For stylesheets: <%= wicked_pdf_stylesheet_pack_tag 'application' %> # For javascripts: <%= wicked_pdf_javascript_pack_tag 'application' %> # For images or other assets: <%= image_tag wicked_pdf_asset_pack_path("media/images/foobar.png") %> ``` -------------------------------- ### Wicked PDF Configuration Options Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md This snippet outlines the various configuration options available for Wicked PDF, such as quiet mode, outlines, margins, headers, footers, table of contents (TOC) settings, progress callbacks, and temporary file deletion. These options allow for fine-grained control over PDF generation. ```ruby quiet: false, # `false` is same as `log_level: 'info'`, `true` is same as `log_level: 'none'` outline: { outline: true, outline_depth: LEVEL }, margin: { top: SIZE, # default 10 (mm) bottom: SIZE, left: SIZE, right: SIZE }, header: { html: { template: 'users/header', # use :template OR :url layout: 'pdf_plain', # optional, use 'pdf_plain' for a pdf_plain.html.pdf.erb file, defaults to main layout url: 'www.example.com', locals: { foo: @bar }}, center: 'TEXT', font_name: 'NAME', font_size: SIZE, left: 'TEXT', right: 'TEXT', spacing: REAL, line: true, content: 'HTML CONTENT ALREADY RENDERED'}, # optionally you can pass plain html already rendered (useful if using pdf_from_string) footer: { html: { template:'shared/footer', # use :template OR :url layout: 'pdf_plain.html', # optional, use 'pdf_plain' for a pdf_plain.html.pdf.erb file, defaults to main layout url: 'www.example.com', locals: { foo: @bar }}, center: 'TEXT', font_name: 'NAME', font_size: SIZE, left: 'TEXT', right: 'TEXT', spacing: REAL, line: true, content: 'HTML CONTENT ALREADY RENDERED'}, toc: { font_name: "NAME", depth: LEVEL, header_text: "TEXT", header_fs: SIZE, text_size_shrink: 0.8, l1_font_size: SIZE, l2_font_size: SIZE, l3_font_size: SIZE, l4_font_size: SIZE, l5_font_size: SIZE, l6_font_size: SIZE, l7_font_size: SIZE, level_indentation: NUM, l1_indentation: NUM, l2_indentation: NUM, l3_indentation: NUM, l4_indentation: NUM, l5_indentation: NUM, l6_indentation: NUM, l7_indentation: NUM, no_dots: true, disable_dotted_lines: true, disable_links: true, disable_toc_links: true, disable_back_links:true, xsl_style_sheet: 'file.xsl'}, progress: proc { |output| puts output }, delete_temporary_files: true ``` -------------------------------- ### Define protect_against_forgery for ActionView::Base Source: https://github.com/mileszs/wicked_pdf/wiki/Background-PDF-creation-via-delayed_job-gem This Ruby code snippet shows how to define a `protect_against_forgery?` method on `ActionView::Base` to resolve `ActionView::Template::Error` when rendering views outside of a controller context. This is often necessary when using `ActionView::Base.new()` directly. ```ruby ActionView::Base.send(:define_method, :protect_against_forgery?) { false } ``` -------------------------------- ### Wicked PDF Advanced Usage: PDF from HTML File Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md This snippet illustrates how to create a PDF directly from an existing HTML file without the need to convert it to a string first. This approach can be more efficient for larger HTML documents. The specific method for this operation is not shown but implied by the comment. ```ruby # create a pdf file from a html file without converting it to string ``` -------------------------------- ### Track PDF Generation Progress in a Job Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Allows tracking the progress of PDF generation, particularly useful within background job systems like Resque. A callback block is provided to `pdf_from_string` to parse progress information and update job status. ```ruby class PdfJob def perform blk = proc { |output| match = output.match(/[.+] Page (?\d+) of (?\d+)/) if match current_page = match[:current_page].to_i total_pages = match[:total_pages].to_i message = "Generated #{current_page} of #{total_pages} pages" at current_page, total_pages, message end } WickedPdf.new.pdf_from_string(html, progress: blk) end end ``` -------------------------------- ### Generate PDF using Rails Controller View Rendering Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Renders a PDF directly from a Rails controller action, leveraging existing views and templates. This method allows passing various Wicked PDF options and specifies the encoding. It uses Rails' `render_to_string` with the `pdf` option. ```ruby pdf = render_to_string pdf: "some_file_name", template: "templates/pdf", encoding: "UTF-8" ``` -------------------------------- ### Return PDF in Rails API Controller Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Provides a method to generate and send a PDF response from a Rails controller in API mode. It renders the view to a string, generates the PDF, and then sends it back with appropriate headers. ```ruby pdf_html = ActionController::Base.new.render_to_string(template: 'controller_name/action_name', layout: 'pdf') pdf = WickedPdf.new.pdf_from_string(pdf_html) send_data pdf, filename: 'file.pdf' ``` -------------------------------- ### Configure Rails Application for Asset Paths Source: https://github.com/mileszs/wicked_pdf/wiki/Configuring-wicked_pdf-for-Bootstrap This configuration adds custom asset paths to the Rails application, allowing it to find stylesheets for Bootstrap, Font Awesome, and fonts. These paths are crucial for the asset pipeline to locate and serve these resources. ```ruby class Application < Rails::Application config.assets.paths << "#{Rails.root}/app/assets/stylesheets/font-awesome-4.2.0/css/" config.assets.paths << "#{Rails.root}/app/assets/stylesheets/bootstrap/" #All bootstraps css files location config.assets.paths << "#{Rails.root}/vendor/assets/fonts" end ``` -------------------------------- ### Import Bootstrap and Font Awesome in PDF CSS Source: https://github.com/mileszs/wicked_pdf/wiki/Configuring-wicked_pdf-for-Bootstrap This step imports Bootstrap and Font Awesome stylesheets into the `pdf.css.scss` file. This ensures that the styles defined in these libraries are applied when generating PDFs. ```scss @import "bootstrap"; @import "font-awesome"; @import "estilo"; ``` -------------------------------- ### Wicked PDF Advanced Usage: PDF from String Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Demonstrates how to generate a PDF directly from an HTML string using the `pdf_from_string` method. This is useful for dynamic content generation where an intermediate HTML file is not necessary. An instance of `WickedPdf` is required to call this method. ```ruby # create a pdf from a string pdf = WickedPdf.new.pdf_from_string('

Hello There!

') ``` -------------------------------- ### Save PDF to File Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Saves a generated PDF (represented as a string) to a specified file path. This involves opening a file in binary write mode and writing the PDF content to it. Assumes `pdf` variable holds the PDF content. ```ruby save_path = Rails.root.join('pdfs','filename.pdf') File.open(save_path, 'wb') do |file| file << pdf end ``` -------------------------------- ### Configure Rack Middleware with Conditions Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Allows fine-tuning the Rack middleware to enable or disable PDF generation for specific URLs using `:only` or `:except` conditions. These conditions can be strings or regular expressions. ```ruby # conditions can be plain strings or regular expressions, and you can supply only one or an array config.middleware.use WickedPdf::Middleware, {}, only: '/invoice' config.middleware.use WickedPdf::Middleware, {}, except: [ %r[^/admin], '/secret', %r[^/people/\d] ] ``` -------------------------------- ### Generate PDF from HTML String with Header/Footer Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Converts an HTML string into a PDF, allowing for custom templates, layouts, and content for headers and footers. This method is versatile for complex PDF generation. It utilizes Rails' `render_to_string` for template rendering. ```ruby pdf = WickedPdf.new.pdf_from_string( render_to_string('templates/pdf', layout: 'pdfs/layout_pdf.html'), footer: { content: render_to_string( 'templates/footer', layout: 'pdfs/layout_pdf.html' ) } ) ``` -------------------------------- ### Generate PDF with Advanced Wicked PDF Options in Rails Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md This Ruby code snippet shows how to render a PDF using the Wicked PDF gem within a Rails controller action. It covers numerous options for customizing the PDF output, such as specifying file names, templates, layouts, wkhtmltopdf binary path, page settings, headers, footers, and error handling. It is intended for use within a Rails application's controller. ```ruby class ThingsController < ApplicationController def show respond_to do |format| format.html format.pdf do render pdf: 'file_name', disposition: 'attachment', # default 'inline' template: 'things/show', locals: {foo: @bar}, file: "#{Rails.root}/files/foo.erb", inline: 'INLINE HTML', layout: 'pdf', # for a pdf.pdf.erb file wkhtmltopdf: '/usr/local/bin/wkhtmltopdf', # path to binary show_as_html: params.key?('debug'), # allow debugging based on url param orientation: 'Landscape', # default Portrait page_size: 'A4, Letter, ...', # default A4 page_height: NUMBER, page_width: NUMBER, save_to_file: Rails.root.join('pdfs', "#{filename}.pdf"), save_only: false, # depends on :save_to_file being set first default_protocol: 'http', proxy: 'TEXT', basic_auth: false, # when true username & password are automatically sent from session username: 'TEXT', password: 'TEXT', title: 'Alternate Title', # otherwise first page title is used cover: 'URL, Pathname, or raw HTML string', dpi: 'dpi', encoding: 'TEXT', user_style_sheet: 'URL', cookie: ['_session_id SESSION_ID'], # could be an array or a single string in a 'name value' format post: ['query QUERY_PARAM'], # could be an array or a single string in a 'name value' format redirect_delay: NUMBER, javascript_delay: NUMBER, window_status: 'TEXT', # wait to render until some JS sets window.status to the given string image_quality: NUMBER, no_pdf_compression: true, zoom: FLOAT, page_offset: NUMBER, book: true, default_header: true, disable_javascript: false, grayscale: true, lowquality: true, enable_plugins: true, disable_internal_links: true, disable_external_links: true, keep_relative_links: true, print_media_type: true, # define as true the key 'disable_local_file_access' or 'enable_local_file_access', not both disable_local_file_access: true, enable_local_file_access: false, # must be true when using wkhtmltopdf > 0.12.6 allow: ["#{Rails.root}/public"], # could be an array or a single string disable_smart_shrinking: true, use_xserver: true, background: false, # background needs to be true to enable background colors to render no_background: true, no_stop_slow_scripts: false, viewport_size: 'TEXT', # available only with use_xserver or patched QT extra: '', # directly inserted into the command to wkhtmltopdf raise_on_all_errors: nil, # raise error for any stderr output. Such as missing media, image assets raise_on_missing_assets: nil, # raise when trying to access a missing asset log_level: 'info' # Available values: none, error, warn, or info - only available with wkhtmltopdf 0.12.5+ end end end end ``` -------------------------------- ### Generate PDF from HTML String without Layout for Header/Footer Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Creates a PDF from an HTML string, where header or footer content is provided without a specific layout. This requires the header/footer content to be a complete, valid HTML document. It uses Rails' `render_to_string`. ```ruby pdf = WickedPdf.new.pdf_from_string( render_to_string('templates/full_pdf_template'), header: { content: render_to_string('templates/full_header_template') } ) ``` -------------------------------- ### Security Considerations for User-Generated Content with WickedPDF Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md WickedPDF renders HTML to PDF by saving temporary files. If allowing user-generated content, sanitize it first to prevent security risks. Disallow requests to internal IP addresses and hostnames, as they could leak sensitive metadata. ```html ``` -------------------------------- ### Wicked PDF Helpers with Asset Pipeline Workaround Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md To work around potential errors with asset names when using the asset pipeline and Wicked PDF, you can use `wicked_pdf_asset_base64`. This helper base64 encodes assets and inlines them, which is effective for small assets but can be slow for large ones. ```html <%= stylesheet_link_tag wicked_pdf_asset_base64("pdf") %> <%= javascript_include_tag wicked_pdf_asset_base64("number_pages") %>
<%= yield %>
``` -------------------------------- ### Include PDF as Email Attachment Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Renders a PDF from a view and includes it as an attachment in an email. This process involves generating the PDF content as a string and assigning it to an attachment. It's recommended to schedule this operation in a background job due to potential performance impact. ```ruby attachments['attachment.pdf'] = WickedPdf.new.pdf_from_string( render_to_string('link_to_view.pdf.erb', layout: 'pdf') ) ``` -------------------------------- ### Add Bootstrap to Application CSS Manifest Source: https://github.com/mileszs/wicked_pdf/wiki/Configuring-wicked_pdf-for-Bootstrap This step involves modifying the `application.css` file to include the Bootstrap stylesheet. This is a prerequisite for using Bootstrap styles within the application, including in generated PDFs. ```css *= require bootstrap ``` -------------------------------- ### HTML Meta Tag for UTF-8 Encoding Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Includes a meta tag in HTML views or layouts to ensure proper display of UTF-8 encoded characters within the generated PDF. This is a standard HTML practice for character encoding. ```html ``` -------------------------------- ### Add Bootstrap to Application JavaScript Manifest Source: https://github.com/mileszs/wicked_pdf/wiki/Configuring-wicked_pdf-for-Bootstrap This step involves modifying the `application.js` file to include the Bootstrap JavaScript files. This is necessary if your application relies on Bootstrap's JavaScript components. ```javascript //= require bootstrap ``` -------------------------------- ### Enqueue PDF Generation Job in Rails Controller Source: https://github.com/mileszs/wicked_pdf/wiki/Background-PDF-creation-via-delayed_job-gem This Ruby code snippet shows how to enqueue a custom PDF generation job using Delayed Job within a Rails controller. It finds a document by ID, enqueues a `GeneratePdfJob` with the document's ID, and updates the document's status to 'queued'. ```ruby class DocsController < ApplicationController def generate_pdf @doc = Doc.find(params[:id]) # enqueue our custom job object that uses delayed_job methods Delayed::Job.enqueue GeneratePdfJob.new(@doc.id) # update the status so nobody generates a PDF twice doc.update_attribute(:status, 'queued') end end ``` -------------------------------- ### CSS for Page Breaks Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Defines CSS rules to control page breaks within the generated PDF. Classes like `alwaysbreak`, `nobreak`, and `nobreak:before` can be applied to HTML elements to manage page layout. ```css div.alwaysbreak { page-break-before: always; } div.nobreak:before { clear:both; } div.nobreak { page-break-inside: avoid; } ``` -------------------------------- ### JavaScript for Page Numbering Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md A JavaScript function to dynamically number pages in a PDF. When embedded in the HTML, it uses URL parameters to insert page numbers (e.g., current page, total pages) into elements with specific classes. ```html Page of ``` -------------------------------- ### Wicked PDF Built-in Page Numbering Source: https://github.com/mileszs/wicked_pdf/blob/master/README.md Utilizes wkhtmltopdf's built-in functionality for page numbering when explicit page breaks are not used. This is achieved by setting a header, such as `[page] of [topage]`, which the library automatically replaces with the correct numbers. ```ruby render pdf: 'filename', header: { right: '[page] of [topage]' } ``` -------------------------------- ### Update Bootstrap Font Face Resource Locations Source: https://github.com/mileszs/wicked_pdf/wiki/Configuring-wicked_pdf-for-Bootstrap This modification updates the `@font-face` rule in `bootstrap.css` to correctly reference font files. It changes the path from `../fonts/` to `/assets/` to ensure fonts are served correctly by the Rails asset pipeline. ```css @font-face { font-family: 'Glyphicons Halflings'; src: url('/assets/glyphicons-halflings-regular.eot'); src: url('/assets/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('/assets/glyphicons-halflings-regular.woff') format('woff'), url('/assets/glyphicons-halflings-regular.ttf') format('truetype'), url('/assets/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg'); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.