### 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
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 (?