Giter Site home page Giter Site logo

wicked_pdf's Introduction

Wicked PDF Gem Version Build Status Code Climate Open Source Helpers

A PDF generation plugin for Ruby on Rails

Wicked PDF uses the shell utility wkhtmltopdf to serve a PDF file to a user from HTML. In other words, rather than dealing with a PDF generation DSL of some sort, you simply write an HTML view as you would normally, then let Wicked PDF take care of the hard stuff.

Wicked PDF has been verified to work on Ruby versions 2.2 through 2.6; Rails 4 through 6.1

Installation

Add this to your Gemfile and run bundle install:

gem 'wicked_pdf'

Then create the initializer with

rails generate wicked_pdf

You may also need to add

Mime::Type.register "application/pdf", :pdf

to config/initializers/mime_types.rb in older versions of Rails.

Because wicked_pdf is a wrapper for wkhtmltopdf, you'll need to install that, too.

The simplest way to install all of the binaries on most Linux or OSX systems is through the gem wkhtmltopdf-binary. Builds for other systems are available here To install that gem, add this:

gem 'wkhtmltopdf-binary'

To your Gemfile and run bundle install.

This gem currently installs version 0.12.x of wkhtmltopdf. Some of the options listed below are specific 0.9 or below, and others are for 0.12 and up.

You can see what flags are supported for the current version in wkhtmltopdf's auto-generated manual

If your wkhtmltopdf executable is not on your webserver's path, you can configure it in an initializer:

WickedPdf.configure do |c|
  c.exe_path = '/usr/local/bin/wkhtmltopdf'
  c.enable_local_file_access = true
end

For more information about wkhtmltopdf, see the project's homepage.

Basic Usage

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

Usage Conditions - Important!

The wkhtmltopdf binary is run outside of your Rails application; therefore, your normal layouts will not work. If you plan to use any CSS, JavaScript, or image files, you must modify your layout so that you provide an absolute reference to these files. The best option for Rails without the asset pipeline is to use the wicked_pdf_stylesheet_link_tag, wicked_pdf_image_tag, and wicked_pdf_javascript_include_tag helpers or to go straight to a CDN (Content Delivery Network) for popular libraries such as jQuery.

wicked_pdf helpers

<!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>

Using wicked_pdf_helpers with asset pipeline raises Asset names passed to helpers should not include the "/assets/" prefix. error. To work around this, you can use wicked_pdf_asset_base64 with the normal Rails helpers, but be aware that this will base64 encode your content and inline it in the page. This is very quick for small assets, but large ones can take a long time.

<!doctype html>
<html>
  <head>
    <meta charset='utf-8' />
    <%= stylesheet_link_tag wicked_pdf_asset_base64("pdf") %>
    <%= javascript_include_tag wicked_pdf_asset_base64("number_pages") %>

  </head>
  <body onload='number_pages'>
    <div id="header">
      <%= image_tag wicked_pdf_asset_base64('mysite.jpg') %>
    </div>
    <div id="content">
      <%= yield %>
    </div>
  </body>
</html>

Webpacker usage

wicked_pdf supports webpack assets.

  • Use wicked_pdf_stylesheet_pack_tag for stylesheets
  • Use wicked_pdf_javascript_pack_tag for javascripts
  • Use wicked_pdf_asset_pack_path to access an asset directly, for example: image_tag wicked_pdf_asset_pack_path("media/images/foobar.png")

Asset pipeline usage

It is best to precompile assets used in PDF views. This will help avoid issues when it comes to deploying, as Rails serves asset files differently between development and production (config.assets.compile = false), which can make it look like your PDFs work in development, but fail to load assets in production.

config.assets.precompile += ['blueprint/screen.css', 'pdf.css', 'jquery.ui.datepicker.js', 'pdf.js', ...etc...]

CDN reference

In this case, you can use that standard Rails helpers and point to the current CDN for whichever framework you are using. For jQuery, it would look somethng like this, given the current versions at the time of this writing.

<!doctype html>
<html>
  <head>
    <%= 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" %>

Advanced Usage with all available options

NOTE: Certain options are only supported in specific versions of wkhtmltopdf.

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:                         '<!doctype html><html><head></head><body>INLINE HTML</body></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+
               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'}, # optionally you can pass plain html already rendered (useful if using pdf_from_string)
               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'}, # optional XSLT stylesheet to use for styling table of contents
               progress: proc { |output| puts output }, # proc called when console output changes
               delete_temporary_files: true             # explicitly delete temporary files, default false
      end
    end
  end
end

By default, it will render without a layout (layout: false) and the template for the current controller and action.

wkhtmltopdf Binary Options

Some of the options above are being passed to wkhtmltopdf binary. They can be used to control the options used in Webkit rendering before generating the PDF.

Examples of those options are:

print_media_type: true        # Passes `--print-media-type`
no_background: true           # Passes `--no-background`

You can see the complete list of options under "Global Options" in wkhtmltopdf usage docs.

Super Advanced Usage

If you need to just create a pdf and not display it:

# create a pdf from a string
pdf = WickedPdf.new.pdf_from_string('<h1>Hello There!</h1>')

# create a pdf file from a html file without converting it to string
# Path must be absolute path
pdf = WickedPdf.new.pdf_from_html_file('/your/absolute/path/here')

# create a pdf from a URL
pdf = WickedPdf.new.pdf_from_url('https://github.com/mileszs/wicked_pdf')

# create a pdf from string using templates, layouts, and content option for header or footer
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'
    )
  }
)

# It is possible to use footer/header templates without a layout, in that case you need to provide a valid HTML document
pdf = WickedPdf.new.pdf_from_string(
  render_to_string('templates/full_pdf_template'),
  header: {
    content: render_to_string('templates/full_header_template')
  }
)

# or from your controller, using views & templates and all wicked_pdf options as normal
pdf = render_to_string pdf: "some_file_name", template: "templates/pdf", encoding: "UTF-8"

# then save to a file
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
  file << pdf
end

# you can also track progress on your PDF generation, such as when using it from within a Resque job
class PdfJob
  def perform
    blk = proc { |output|
      match = output.match(/\[.+\] Page (?<current_page>\d+) of (?<total_pages>\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

If you need to display utf encoded characters, add this to your pdf views or layouts:

<meta charset="utf-8" />

If you need to return a PDF in a controller with Rails in API mode:

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'

Page Breaks

You can control page breaks with CSS.

Add a few styles like this to your stylesheet or page:

div.alwaysbreak { page-break-before: always; }
div.nobreak:before { clear:both; }
div.nobreak { page-break-inside: avoid; }

Page Numbering

A bit of javascript can help you number your pages. Create a template or header/footer file with this:

<html>
  <head>
    <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>
  </head>
  <body onload="number_pages()">
    Page <span class="page"></span> of <span class="topage"></span>
  </body>
</html>

Anything with a class listed in "var x" above will be auto-filled at render time.

If you do not have explicit page breaks (and therefore do not have any "page" class), you can also use wkhtmltopdf's built in page number generation by setting one of the headers to "[page]":

render pdf: 'filename', header: { right: '[page] of [topage]' }

Configuration

You can put your default configuration, applied to all pdf's at "wicked_pdf.rb" initializer.

Rack Middleware

If you would like to have WickedPdf automatically generate PDF views for all (or nearly all) pages by appending .pdf to the URL, add the following to your Rails app:

# in application.rb (Rails3) or environment.rb (Rails2)
require 'wicked_pdf'
config.middleware.use WickedPdf::Middleware

If you want to turn on or off the middleware for certain URLs, use the :only or :except conditions like so:

# 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] ]

If you use the standard render pdf: 'some_pdf' in your app, you will want to exclude those actions from the middleware.

Include in an email as an attachment

To include a rendered pdf file in an email you can do the following:

attachments['attachment.pdf'] = WickedPdf.new.pdf_from_string(
  render_to_string('link_to_view.pdf.erb', layout: 'pdf')
)

This will render the pdf to a string and include it in the email. This is very slow so make sure you schedule your email delivery in a job.

Further Reading

Mike Ackerman's post How To Create PDFs in Rails

Andreas Happe's post Generating PDFs from Ruby on Rails

JESii's post WickedPDF, wkhtmltopdf, and Heroku...a tricky combination

Berislav Babic's post Send PDF attachments from Rails with WickedPdf and ActionMailer

Corsego's 2021 post Complete guide to generating PDFs with gem wicked_pdf

PDFTron's post How to Generate PDFs With Ruby on Rails

StackOverflow questions with the tag "wicked-pdf"

Screencasts

  • SupeRails Screencast [EN]

Ruby on Rails #17 generate, save, send PDFs with gem wicked_pdf

  • codigofacilito Screencast [ES]

Generar PDF con Ruby on Rails - Tutorial

Debugging

Now you can use a debug param on the URL that shows you the content of the pdf in plain html to design it faster.

First of all you must configure the render parameter show_as_html: params.key?('debug') and then just use it like you normally would but add "debug" as a GET param in the URL:

http://localhost:3001/CONTROLLER/X.pdf?debug

However, the wicked_pdf_* helpers will use file:/// paths for assets when using :show_as_html, and your browser's cross-domain safety feature will kick in, and not render them. To get around this, you can load your assets like so in your templates:

<%= params.key?('debug') ? image_tag('foo') : wicked_pdf_image_tag('foo') %>

Gotchas

If one image from your HTML cannot be found (relative or wrong path for example), others images with right paths may not be displayed in the output PDF as well (it seems to be an issue with wkhtmltopdf).

wkhtmltopdf may render at different resolutions on different platforms. For example, Linux prints at 75 dpi (native for WebKit) while on Windows it's at the desktop's DPI (which is normally 96 dpi). Use :zoom => 0.78125 (75/96) to match Linux rendering to Windows.

Security considerations

WickedPdf renders page content on the server by saving HTML and assets to temporary files on disk, then executing wkhtmltopdf to convert that HTML to a PDF file.

It is highly recommended if you allow user-generated HTML/CSS/JS to be converted to PDF, you sanitize it first, or at least disallow requesting content from internal IP addresses and hostnames.

For example, these could potentially leak internal AWS metadata:

<iframe src="http://169.254.169.254/latest/meta-data/"></iframe>
<object data="http://169.254.169.254/latest/meta-data/" type="text/html">

Thank you to Adam Gold from Snyk for reporting this. We are considering adding host allow & block lists and/or potentially HTML element sanitizing. Please open an issue or PR to help us out with this.

Inspiration

You may have noticed: this plugin is heavily inspired by the PrinceXML plugin princely. PrinceXML's cost was prohibitive for me. So, with a little help from some friends (thanks jqr), I tracked down wkhtmltopdf, and here we are.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Run the test suite and check the output (rake)
  4. Add tests for your feature or fix (please)
  5. Commit your changes (git commit -am 'Add some feature')
  6. Push to the branch (git push origin my-new-feature)
  7. Create new Pull Request

Awesome Peoples

Also, thanks to unixmonkey, galdomedia, jcrisp, lleirborras, tiennou, and everyone else for all their hard work and patience with my delays in merging in their enhancements.

wicked_pdf's People

Contributors

adzap avatar antti avatar bsedat avatar corincerami avatar crespire avatar ctrochalakis avatar d4rky-pl avatar figedi avatar fschwahn avatar fwininger avatar gabteles avatar joshuapinter avatar kevinnio avatar lleirborras avatar mathieujobin avatar mikerogers0 avatar mileszs avatar mlitwiniuk avatar orien avatar pedrofurtado avatar reidab avatar rposborne avatar sharpyfox avatar soemo avatar takkanm avatar tiennou avatar toddsiegel avatar unixmonkey avatar wkrsz avatar yui-knk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wicked_pdf's Issues

basic authentication

I recently ran into an issue with pdf generation within a basic authenticated domain, wkhtmltopdf was failling due to authorization required error.

I've done some digging into this and come up with a simple enough solution, since the wkhtmltopdf binary already has options for this matter.

The patch is in this commit if anyone interested!

Dragonfly images

It would be nice to generate pdf files with included images processed by dragonfly. Any possibility to achieve this?

(prawn gem uses open-uri for remote-images)

Does Wicked PDF supports embeding images?

Hi,

Great work you've done with Wicked PDF.

I'm wondering if it supports adding images. I've tried dropping some tags but I'm getting blank boxes, so it seems it recognizes the image tags, but is not capable of embeding them into the PDF.

Is that being supported? If so, how exactly I can achieve?

Thank you.

WickedPDF model callbacks and RVM path issue

A rough example of what I'm trying:

before_save :generate_pdf

def generate_pdf
  pdf = WickedPdf.new.pdf_from_string("<h1>test</h1>")
  save_path = Rails.root.join('public','system','pdfs',domain_name,'filename.pdf')
  File.open(save_path, 'wb') do |file|
    file << pdf
  end
end

When I call that method I see that Rails is looking in the wrong place for wkhtmltopdf

RuntimeError: Failed to execute:
/Users/home/.rvm/gems/ruby-1.9.2-p290@myapp/bin/wkhtmltopdf       -q - -

I can successfully generate PDFs from the standard controller method. This problem only occurs from the model.

Any tips?

How to rewrite helper wicked_pdf_image_tag to work with paperclip images

To works with images from paperclip i rewrite this method

  def wicked_pdf_image_tag(img, options={})
    if img[0].chr == "/" # images from paperclip
      new_image = img.slice 1..-1
      image_tag "file://#{Rails.root.join('public', new_image)}", options
    else
      image_tag "file://#{Rails.root.join('public', 'images', img)}", options
    end
  end

Which unit does SIZE take?

In your README, you use the const SIZE. Does this take valid CSS units, e.g. pt or does it use something like cm or inches?

stylesheet is not displayed in pdf

I used
<%= wicked_pdf_stylesheet_link_tag "pdf" %>
it shows the following output in the html

`

`

But when create the pdf it do not have any style. If i copy all css from the file to the header of the page, it includes all styles. What is the issue and how to solve it.

Does not support cookie option

We're using cookie for access to attachments (rendering attached images) and at the moment wicked_pdf does not pass on this option.

If added, this cannot be a simple string type option as it requires two values (--cookie name value) and it cannot be enclosed into a single 'name value' string. So, there can either be quoted both name and value individually or left without anything like numeric types.

jquery does not execute because wicked_pdf_javascript_include_tag("jquery-1.4.2") does not add ".js" to the path

I'm only raising this because I just spent a couple of hours tracking it down, hoping to save someone else some time:

Here's my initial code:

<%= params[:debug].present? ? javascript_include_tag("jquery-1.4.2") : wicked_pdf_javascript_include_tag("jquery-1.4.2") -%>
    <%= params[:debug].present? ? javascript_include_tag("protovis") : wicked_pdf_javascript_include_tag("protovis") -%>

I could not figure out why jquery was not executing in the .pdf generation, but worked fine when I ran it with show_as_html, and furthermore protovis was working just fine.

Ultimately it was because I was using a javascript file with a version number (jquery-1.4.2.js), but only had the wicked_pdf_javascript_include_tag("jquery-1.4.2") in my header. For javascript files without version numbers (e.g., protovis.js) this works fine. However, when the underlying rails helpers see jquery-1.4.2 they assume .2 is the filename extension and don't add the .js. Trivial, but hard to track, and made worse because the javascript_include_tag part gets it right.

Two suggestions:
a) Edit the README for wicked to suggest using full filenames with the helper functions
b) Add a 'puts(err)' in pdf_from_string in wicked_pdf.rb. Right now it fails silently

def pdf_from_string(string, options={})
    command = "#{@exe_path} #{parse_options(options)}  - - " # -q for no errors on stdout
    p "*"*15 + command + "*"*15 unless defined?(Rails) and Rails.env != 'development'
    pdf, err = Open3.popen3(command) do |stdin, stdout, stderr|
      stdin.binmode
      stdout.binmode
      stderr.binmode
      stdin.write(string)
      stdin.close
      [stdout.read, stderr.read]
    end
    puts(err)
    raise "PDF could not be generated!" if pdf and pdf.rstrip.length == 0
    pdf
  rescue Exception => e
    raise "Failed to execute:\n#{command}\nError: #{e}"
  end

Error with Header and footer options on Windows platform

I have the next problem.

I am working with RoR 2.3.8 on Windows platform. Also the server run on windows.

I am trying to create a pdf from html template, layout and partials.

briefly i will try to explain what i am trying to do:

My site is a shopping site, so I need generate a voucher.pdf

This voucher could have many items.therefore the voucher could have many pages.

I need to create a header and footer for each page in the voucher. There's mention that without these options (header and / or footer) works perfectly

I try this in my controller

def generate_voucher
@order = Order.find(params[:id])

unless @order.blank?

 pdf = render_to_string_with_wicked_pdf({:pdf    => 'generate_voucher.html.erb',
                                          :layout => 'voucher.html',
                                          :header => {:html => { :template => 'shared/voucher_header.html.erb'} 
                                                                                                          # Also i try voucher_header.pdf.erb
                                         })

  @order.save_pdf(pdf)

  redirect_to :action => "payment", :id => order.id
end

end

This message throw:

'Template is missing

Missing template shared/voucher_header.html.erb in view path app/views'

I need to use a header and footer on every pages of the pdf file and not display it.

Also when i render a image with wicked_pdf_image_tag diaplay a empty frame with grey border.

Thanks in advance and excuse me.

Broken Pipe Error in wicked_pdf.rb

We're getting a strange problem where the PDF generation process is producing an error within the wicked_pdf.rb interface. Trace:

Errno::EPIPE (Broken pipe):
    /vendor/plugins/wicked_pdf/lib/wicked_pdf.rb:22:in `write'
    /vendor/plugins/wicked_pdf/lib/wicked_pdf.rb:22:in `pdf_from_string'
    /opt/ruby-enterprise-1.8.7-2010.01/lib/ruby/1.8/open3.rb:86:in `popen3'
    /vendor/plugins/wicked_pdf/lib/wicked_pdf.rb:21:in `pdf_from_string'
    /vendor/plugins/wicked_pdf/lib/pdf_helper.rb:28:in `make_pdf'
    /vendor/plugins/wicked_pdf/lib/pdf_helper.rb:39:in `make_and_send_pdf'
    /vendor/plugins/wicked_pdf/lib/pdf_helper.rb:13:in `render'
    /app/controllers/projects/forms_controller.rb:20

This is happening on a platform where we run Ruby Enterprise Version 1.8.7 2010.01 on Linux but it works fine on Mac OS X with the system Ruby installed. I haven't yet managed to localise it further. This is with the precompiled Linux version of wkhtmltopdf and version 0.10.0 rc1.

Does anybody have any ideas and are seeing a problem like this?

Do you have any working example??

I cant get this plugin to work ;(
i tried even this http://github.com/jordan-brough/heroku-pdf but still with no success (rails 2.3.8 ruby 1.8.7).
The example above generates 10B pdf and when opened i get this:

"Adobe Reader could not open 'hello world.pdf' because its either not a supported file type or because its damaged"

Im using wkhtmltopdf-0.10.0_beta5-static-i386.tar.lzma 10.5 MB on ubuntu 10.4

And in my rails3 ruby 1.8.7 app wicked_pdf generates 4B pdf file and when opened I get the same error as above.

Gem instead of plugin

Hi there, I notice there is a gem available. Are you actively maintaining the gem or is it better to install this as a plugin? :)

Cheers,

Brendon

Various fixes

Hello I have made the following fixes to wicked_pdf, if you want to merge them or cherrypick some of them. Most importantly you can now use the lib as a gem with rails3

-> git line origin/master..
138dfb5 add a gemspec
44e6600 Add railtie, should work with rails3 as well
ddc45b5 -q flag should be passed first for newer versions of wkhtml2pdf
bd3ce9e Use Rails.root && Rails.env

render_to_string doesn't work

doesn't seems to work anymore.

I want to send a File as Attachment, without saving it to the filesystem and using the header-render options.
pdf_helper is not supporting that unfortunately.

Change the wicked_pdf_helper to 3.1 assets paths

I don't have experience on creating and testing rubygems yet. So, I'm gonna just send an idea.

The helper methods are being created using a join with the 'javascript', 'images' and 'stylesheet' paths. One thing that could work in development and production is to remove those directories and receive the asset_path or image_path instead.

Here comes an example:

def wicked_pdf_image_tag(img_path, options={})
  image_tag "file://#{Rails.root.join('public', img_path)}", options
end

and then we could use the helper method like this:

<%= wicked_pdf_image_tag image_path('image.png') %>

can't get wicked_pdf to work on Ubuntu 10.04

I'm using Ubuntu 10.04.
I downloaded and extracted wkhtml2pdf beta 4 and placed it in /usr/local/bin/wkhtml2pdf
I tried running it on a web site and it gave a nice result.
In my rails application (2.3.4) I installed wicked_pdf:
script/plugin install git://github.com/mileszs/wicked_pdf.git
script/generate wicked_pdf
Everything seemed to be ok.
inside script/console I run the following - (with the following output)

wp = WickedPdf.new

=> #<WickedPdf:0xb62f2c70 @exe_path="/usr/local/bin/wkhtmltopdf">

HTML_DOCUMENT = "Hello World"

=> "Hello World"

pdf = wp.pdf_from_string HTML_DOCUMENT

"_/usr/local/bin/wkhtmltopdf - - -q_"

=> "\n\n\n\n\n\n\n\n\n\n"

of course this isn't good. According to the test the result of my last command should start with "%pdf-1.4"

Any idea what I can do?

Images and CSS not displaying - suggestion for fix

I was trying to render a page within my application as a PDF and the images weren't loading and CSS styles weren't being applied. The reason is because wkhtmltopdf doesn't know which server to load them from. The fork at http://github.com/lleirborras/wicked_pdf suggests creating a custom layout for the PDF and specify the request host/port. This works, but is an unnecessary step if you just want to render your standard templates as is. My suggestion is to replace all the paths for things like /stylesheets and /images after render_to_string:

# In make_pdf function of pdf_helper.rb

html_string = externals_to_absolute_path(render_to_string(:template => options[:template], :layout => options[:layout]))

# New function defined in pdf_helper.rb

def externals_to_absolute_path(html) 
  html.gsub(/\/(stylesheets|images|system)\//) {|s| "http://#{request.host_with_port}/#{$1}/" } 
end

I have hardcoded a few different paths that I am using (/system is where paperclip stores uploaded images), but these could easily be added to the options hash. You can do this with javascript files too, but one of the systems I tested on (Centos 5 w/ Ruby 1.8.5) was hanging with that included so I pulled it out.

Using wicked_pdf on unix and windows platform

Hello and excuse me again.

I am developing on windows platform. However the server run UNIX OS. So in my code add the next lines:

In config/initializers/wicked_pdf.rb

if LINUX || MAC #ENVIRONMENT VARIABLES
if I386
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => Rails.root.join('bin/wkhtmltopdf_unix', 'wkhtmltopdf-i386').to_s
}
else
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => Rails.root.join('bin/wkhtmltopdf_unix', 'wkhtmltopdf-amd64').to_s
}
end
else
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => Rails.root.join('bin/wkhtmltopdf', 'wkhtmltopdf.exe').to_s
}
end

in wicked_pdf.rb

if WIN
require 'win32/open3'
else
require 'open3'
end

Also i have created a folder bin in Rails root folder which contains wkhtmltopdf_unix with binaries.

However in production throw this error log:

RuntimeError (Wkhtmltopdf is not executable):
app/controllers/store_controller.rb:99:in generate_voucher' passenger (3.0.0) lib/phusion_passenger/rack/request_handler.rb:96:inprocess_request'
passenger (3.0.0) lib/phusion_passenger/abstract_request_handler.rb:513:in accept_and_process_next_request' passenger (3.0.0) lib/phusion_passenger/abstract_request_handler.rb:274:inmain_loop'
passenger (3.0.0) lib/phusion_passenger/classic_rails/application_spawner.rb:321:in start_request_handler' passenger (3.0.0) lib/phusion_passenger/classic_rails/application_spawner.rb:275:insend'
passenger (3.0.0) lib/phusion_passenger/classic_rails/application_spawner.rb:275:in handle_spawn_application' passenger (3.0.0) lib/phusion_passenger/utils.rb:479:insafe_fork'
passenger (3.0.0) lib/phusion_passenger/classic_rails/application_spawner.rb:270:in handle_spawn_application' passenger (3.0.0) lib/phusion_passenger/abstract_server.rb:357:insend'
passenger (3.0.0) lib/phusion_passenger/abstract_server.rb:357:in server_main_loop' passenger (3.0.0) lib/phusion_passenger/abstract_server.rb:206:instart_synchronously'
passenger (3.0.0) lib/phusion_passenger/abstract_server.rb:180:in start' passenger (3.0.0) lib/phusion_passenger/classic_rails/application_spawner.rb:149:instart'
passenger (3.0.0) lib/phusion_passenger/spawn_manager.rb:219:in spawn_rails_application' passenger (3.0.0) lib/phusion_passenger/abstract_server_collection.rb:132:inlookup_or_add'
passenger (3.0.0) lib/phusion_passenger/spawn_manager.rb:214:in spawn_rails_application' passenger (3.0.0) lib/phusion_passenger/abstract_server_collection.rb:82:insynchronize'
passenger (3.0.0) lib/phusion_passenger/abstract_server_collection.rb:79:in synchronize' passenger (3.0.0) lib/phusion_passenger/spawn_manager.rb:213:inspawn_rails_application'
passenger (3.0.0) lib/phusion_passenger/spawn_manager.rb:132:in spawn_application' passenger (3.0.0) lib/phusion_passenger/spawn_manager.rb:275:inhandle_spawn_application'
passenger (3.0.0) lib/phusion_passenger/abstract_server.rb:357:in _send_' passenger (3.0.0) lib/phusion_passenger/abstract_server.rb:357:inserver_main_loop'
passenger (3.0.0) lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
passenger (3.0.0) helper-scripts/passenger-spawn-server:99

Which could be the error?

simply do i extract tar.bz2 on bin/wkhtmltopdf_unix folder ?

Thanks in advance

Problem with header option

Hi!

When I'm using header option:

:header => {:html => { :template => 'sites/header.pdf.haml'}}

i got:

uninitialized constant PdfHelper::WickedPdfTempfile

Issues with Windows Server

Hello,

I'm trying to get the Wicked_pdf working on a windows server without success.
The best I can get is a very partial pdf (only 7 to 8 lines spread accross 4 pages).

I browsed through the wkhtmltopdf forums and it looks like the issue could come from wkhtmltopdf and not wicked_pdf ?

Has anyone tried wicked_pdf on a windows (Vista) server ?

Can't test on Rails 3.1

After updating to Rails 3.1, wicked_pdf_stylesheet_link_tag doesn't work anymore (it directs to public/stylesheets, not app/assets/stylesheets).

So I forked to create a patch. However, I can't seem to test successfully. I keep getting the following error, which I found nothing about on Google:

test_should_prerender_header_and_footer_:template_options(PdfHelperTest):
NoMethodError: undefined method `env_config' for nil:NilClass
    /Users/kurko/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.0/lib/action_dispatch/testing/test_request.rb:14:in `initialize'
    /Users/kurko/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.0/lib/action_controller/test_case.rb:130:in `initialize'
    /Users/kurko/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.0/lib/action_dispatch/http/request.rb:43:in `new'
    /Users/kurko/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.0/lib/action_dispatch/http/request.rb:43:in `new'
    /Users/kurko/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.0/lib/action_dispatch/testing/test_request.rb:10:in `new'
    /Users/kurko/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.0/lib/action_controller/test_case.rb:457:in `setup_controller_request_and_response'
    /Users/kurko/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.0/lib/active_support/callbacks.rb:404:in `_run_setup_callbacks'
    /Users/kurko/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.0/lib/active_support/callbacks.rb:81:in `run_callbacks'
    /Users/kurko/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.0/lib/active_support/testing/setup_and_teardown.rb:34:in `run'

I get 5 errors like the one above. I have no idea what this env_config is. Have anyone experienced this before?

wicked_pdf generation in a resque queue?

I'm trying to use wicked_pdf generation for use in a resque work queue. I sometimes use wicked_pdf to send off a batch of emails to customers, and would like to trigger that in an app, and then have a worker queue (in resque) do the actual work.

The problem is, in the queue, there's no request object - I'd have to render a pdf to a string somehow. Should I be able to call that on a new wicked_pdf object?

SystemStackError (stack level too deep)

after follow installation guide, i reinit mongrel server and then i got this:
SystemStackError (stack level too deep)
/home/dafevara/proyectos/publientrega/pec/vendor/plugins/wicked_pdf/lib/pdf_helper.rb:16:in render_with_wicked_pdf' /usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/base.rb:1326:indefault_render'
/usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/base.rb:1332:in perform_action' /usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/filters.rb:617:incall_filters'
/usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/filters.rb:610:in perform_action_with_filters' /usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/benchmarking.rb:68:inblock in perform_action_with_benchmark'
/usr/lib/ruby/gems/1.9.1/gems/activesupport-2.3.8/lib/active_support/core_ext/benchmark.rb:17:in block in ms' /usr/lib/ruby/1.9.1/benchmark.rb:309:inrealtime'
/usr/lib/ruby/gems/1.9.1/gems/activesupport-2.3.8/lib/active_support/core_ext/benchmark.rb:17:in ms' /usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/benchmarking.rb:68:inperform_action_with_benchmark'
any body can help me?
/usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/rescue.rb:160:in perform_action_with_rescue' /usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/flash.rb:151:inperform_action_with_flash'
/usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/base.rb:532:in process' /usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/filters.rb:606:inprocess_with_filters'
/usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/base.rb:391:in process' /usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/base.rb:386:incall'
/usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/routing/route_set.rb:438:in `call'

my environment is:
Ruby 1.9.1
Ubuntu 9.10

Can't use footers

I'm using
ruby 1.9.2-p180
rails 3.1.0
wicked_pdf 0.7.2
wkhtmltopdf 0.9.9

On Mac OS X

I'm not crashing when I try to use a footer (or header) - it's just that they don't show up at all. I tried via my own template, or even by passing in left/right/center symbols, and it just doesn't work.

I can see this getting generated in my console app (I was just trying to throw something in the header and footer:

"***/usr/local/bin/wkhtmltopdf --header-center 'center' --header-left 'Thank you for your business!' --header-right 'right' --footer-center 'center' --footer-left 'Thank you for your business!' --footer-right 'right' -q - - ***"

So, it looks like it's getting passed somewhere. It's just not staying there...

Any ideas?

PDF not rendering at all (-q option misplaced?)

Hi,

I use wkhtmltopdf-amd64 0.10.0 beta4 and wiked_pdf 0.5.4

I had a problem with my pdf being rendered as an empty file. This was caused by a wrong order in the way the options are inputed to wkhtmltopdf. In wiked_pdf.rb the line reads "command_for_stdin_stdout = "#{@exe_path} #{options} - - -q". Shouldn't it be "command_for_stdin_stdout = "#{@exe_path} #{options} -q - -"?

Switching the -q option of place solved my problem.

Template format undefined - suggested fix

I had some issues rendering my *.html.erb templates. If I didn't specify the path as an option, it didn't know to to use the html format and would try to load .erb, without the "html. If I did specify the path, but the template loaded a partial called _.html.erb, it would have the same problem. The only solution I can find that works is to specify the template with:

@template.template_format = :html

Since all my templates are html, I have just put this in the make_pdf function within pdf_helper.rb. It could easily be setup as an option if you don't want HTML as the default template format when rendering a PDF.

Problem with streams

Hello

I am using wicked_pdf.

On development I am using windows and on production I am using Unix server (i686).

In Windows i generate pdfs correctly. However in Production the plugin generated a corrupted file.

I debug and found where could be the problem.

IO.open(command) do |stream|
...
end

In windows these lines works but in unix throw a failed to execute error.

In unix when i try to use Open3 library throw the same error too.

I was testing with open5. However throw this error again.

Which could be the error?

Thanks

Can't use headers

Hi, I just started using wicked_pdf and I'm running it on a Windows 7 64bits with Rails 2.3.8 and Ruby 1.8.7

I can't get the header or footer (or both) to work with a template. The PDF can't be generated when I try to use a :html, it only works if I use the other options.

My controller is like this:
render :pdf => "report-file",
:template => "tb_processo_fornecedor_contatos/index.pdf.erb",
:layout => 'pdf.html',
:header => { :html => {:template => "public/header.pdf.erb"} },
:footer => { :center => "Center",
:left => "Left",
:right => "Right"
}

If I try to run this, I get the following error after several seconds:

PDF could not be generated!
Error: Failed loading page http://C:/Users/Helio/AppData/Local/Temp/wicked_pdf_4708_0.html'?page=1&section=&title=&subsection=&frompage=1&subsubsection=&topage=2&doctitle=&webpage=-&time=17:03:06&date=26/11/2010 (sometimes it will work just to ignore this error with --load-error-handling ignore)
Error: Failed loading page http://C:/Users/Helio/AppData/Local/Temp/wicked_pdf_4708_0.html'?page=2&section=&title=&subsection=&frompage=1&subsubsection=&topage=2&doctitle=&webpage=-&time=17:03:06&date=26/11/2010 (sometimes it will work just to ignore this error with --load-error-handling ignore)
QPaintDevice: Cannot destroy paint device that is being painted

If I remove the line:
:header => { :html => {:template => "public/header.pdf.erb"} },

It creates the pdf perfectly with that Standard footer working. The problem is in the :html option.
I tryed to debug and change something on the pdf_helper.rb without any luck.
I did change a couple of things before so I could get the PDF working based on those other issues ( https://github.com/mileszs/wicked_pdf/issues#issue/3 and https://github.com/mileszs/wicked_pdf/issues#issue/1 )on this page:

(Change on the make_pdf method)
html_string = render_to_string(:template => options[:template], :layout => options[:layout])
to
html_string = externals_to_absolute_path(render_to_string(:template => options[:template], :layout => options[:layout]))

and the:
def externals_to_absolute_path(html)
html.gsub(/(src|href)=('|")//) { |s| "#{$1}=#{$2}#{request.protocol}#{request.host_with_port}/" }
end

also on pdf_helper.rb

If I undo this changes, not only my pdf doesn't work with the header/footer but also it doesn't work at all!

My output is like this:
"_C:\wkhtmltopdf\wkhtmltopdf.exe --header-html 'file://C:/Users/Helio/AppData/Local/Temp/wicked_pdf_4708_0.html' --footer-center 'Center' --footer-left 'Left' --footer-right 'Right' -q - -_"

Any help on what I'm doing wrong? Ideas?

Thank you a lot!

--redirect-delay replaced by --javascript-delay in wkhtmltopdf 10

Looks like recent versions of wkhtmltopdf don't include --redirect-delay any longer. Seems it has been replaced by --javascript-delay with slightly different semantics. I couldn't find a change-log entry on the wkhtmltopdf site, but the readme says:

--javascript-delay <msec> Wait some milliseconds for javascript finish (default 200) and makes no mention of the redirect-delay any longer. Fix is trivial, line 143 in wicked_pdf.rb becomes:

r +=make_options(options, [ :javascript_delay,

Changing font-family just doesn't work

Hey,

I'm testing WickedPDF for a while now. Everything works fine, images, CSS, JS etc. However, changing the font-family has absolutely no effect.

The problem

For example, I can change font-size normally, but:

*, body {
    font-family: "Georgia", 'Times New Roman', 'Arial', sans-serif;
}

just doesn't work, causes no effect. It's stuck on the same font type, no matter what. Looks like it's Helvetica (I can't assess what font it is).

How to reproduce

When I render the normal HTML (deleting the appended .pdf extension), it shows Georgia just fine. But the generated PDF doesn't.

I'm using the latest wkhtmltopdf version. WickedPDF is updated too.

I'm on a Mac.

Has anyone ever experienced this problem?

Wicked_pdf and wkhtmltopdf-binary gem on Ubuntu 10.04

Hi there, I have no problem using wkhtmltopdf-binary in development on my mac but when trying to use it on my production server (Ubuntu 10.04) where the app is deployed via capistrano and bundle is managing the gems (Rails 3.1) I get the following error:

RuntimeError (Failed to execute:
/home/deployer/apps/nzswarranty/shared/bundle/ruby/1.9.1/bin/wkhtmltopdf       -q - - 
Error: PDF could not be generated!):
  app/controllers/admin/products_controller.rb:52:in `certificate_example'

I'm not sure if the binary in the folder mentioned above is the one I want or whether I should be going for:

/apps/nzswarranty/shared/bundle/ruby/1.9.1/gems/wkhtmltopdf-binary-0.9.5.3/bin/wkhtmltopdf

Any help would be appreciated :D

Update

Thought it might be because the -binary gem binaries are 32 bit and this is a 64bit install of Ubuntu so I removed the gem and did apt-get install wkhtmltopdf and now the error message is still the same just using the path of the system wkhtmltopdf:

RuntimeError (Failed to execute:
/usr/bin/wkhtmltopdf       -q - - 
Error: PDF could not be generated!):
  app/controllers/admin/products_controller.rb:52:in `certificate_example'

Rails 3.0 – "show_as_html" sending PDF file

Awesome plugin, by the way.

When I send the options[:show_as_html] value as true, the app is still returning a PDF file, although it's simply a text document with the HTML, not an actual PDF. It's behaving as if "send_data" is being called.

App is in Rails3.0 RC2, by the way.

Using wicked_pdf with rails 3

wicked_pdf looks like it will do exactly what I want, but I'm struggling to get it working with rails 3. I'm new to rails, so I may be doing something really dumb. When I get to the install instructions, I figured I needed to do 'rails plugin install ...' instead of 'script/plugin install ...'. The next step is 'script/generate wicked_pdf'. What is the rails 3 equivalent of that? I tried the obvious 'rails generate wicked_pdf' but that says 'Could not find generator wicked_pdf.'.

Can wicked_pdf be used with rails 3 as it is, or am I wasting my time?

Thanks, Mike Wilson

can't generate table of contents

Hi,

I'm unable to generate a table of contents in my pdf unless I set
:book => true

I don't want to use the book settings. It looks like wicked_pdf isn't setting the -t flag when calling wkhtmltopdf.

Here's my toc hash, by the way:

:toc => { :depth => 4,
:l1_font_size => 12,
:l2_font_size => 12,
:l3_font_size => 12,
:l4_font_size => 12,
:disable_links => false,
:disable_back_links => false }

Background image not showing in pdf

I need a background image for one of my pdfs but it doesn't show when I generate it. I'm guessing wicked_pdf doesn't know where to look for the image?? I currently have it in public/images. Any thoughts?

header and footer using html results in nil error

I was getting a strange error when trying to use html headers and footers. It was a can't convert nil to integer error. I traced it back to the WickedPdfTempfile make_tmpname method.

make_tmpname is passed two variables: the basename and n. For whatever reason, my 'n' was nil and so sprintf was crapping out. I changed the method to the following:

def make_tmpname(basename, n)
#    extension = File.extname(basename)
#    sprintf("%s_%d_%d%s", File.basename(basename, extension), $$, n, extension)
    sprintf("%s_%d_%d%s", File.basename(basename, extension), $$, n.to_i, extension)
end

It works now. What do you think?

Cannot generate initializer with gem

I've installed the gem in a Rails 3 app, but when attempting to generate the initializer ("rails g wicked_pdf"), I receive the following error: "Could not find 'wicked_pdf.rb' in any of your source paths." Any ideas? Thanks!

gem provided javascripts

Hi all,

I am new to rails and learning while doing this project. I hope my question will not look to stupid.

I am using gmaps4rails and would like to create a pdf of a page with a Google maps on it.
It uses a few javascripts provided by the gem which are referenced through <%= yield :head %> and <%= yield :scripts %> in the layout.

Can wicked_pdf use them dynamically? If not, where should I copy them to have the map printed within the pdf ?

Thanks for your help.

Could not find generator wicked_pdf

  1. I have installed wkhtmltopdf
  2. rails plugin install git://github.com/mileszs/wicked_pdf.git
  3. rails generate wicked_pdf
    and got error: Could not find generator wicked_pdf.

I see what this generator should do and I just copied wicked_pdf.rb to initializers.
I am using Windows and Rails 3

syntax error on rails 3.0/raby 1.9?

On this block specifically both on the when clause.

def make_option name, value, type=:string
"--#{name.gsub('_', '-')} " + case type
when :boolean: ""
when :numeric: value.to_s
else "'#{value}'"
end + " "
end

Can't get header/footer to work

Hi!

For some reason I can't insert a header or footer into the pdfs I'm creating. This is my code.

    respond_to do |format|
        format.pdf do
            render :pdf => uniquename,
                :layout => "pdf",
                :template => template_path,
                :header => {
                    :center => "TEXT",
                    :font_name => "NAME", #OPTIONAL
                    :font_size => 10, #OPTIONAL
                    :left => "TEXT", #OPTIONAL
                    :right => "TEXT", #OPTIONAL
                    :spacing => 1, #OPTIONAL
                    :line => true #OPTIONAL
                },
                :lowquality => false
        end

Any suggestions?

style issue with rtl

I have added wicked_pdf plugin in my rails applications to generate pdf. It works fine in normal case. But when it is used for rtl (right to left) languages it get zoomed (or may be auto resizing to fit the page is not working in rtl). How can I solve this issue?

spanish chars not showing

hello i'm trying to generate pdf in Spanish but instead of " Año " it shows some weired chars Año
Any help?

Slow to create PDF

I've manually installed wkhtmltopdf 0.10.0 RC2 and 0.9.9 binaries and also 0.9.9 via homebrew, making sure to uninstall the previous binary each time.

If I create a PDF via the rails console it will make and save the file immediately, but if render a pdf from a controller it takes about 5 minutes in several browsers.

I'm using OS X 10.6.7, RVM 1.9.2 and Rails 3.1.0.rc4.

I used pow for the local dev server (same issues apply when running on thin and standard 'rails s').

When using the :show_as_html option, the page loads as expected, immediately and correctly in HTML format.

Could it be a threading issue? If so does anyone know a quick workaround?

Thanks

Encoding issues

Hi,

I've been able to generate PDF documents under Ubuntu and Rails 3.

The problem I'm facing is with latin characters like (á, é, í, ó, ú). They are not being rendered well in the PDF document. Instaed i'm getting the following.

ó => Ã3
é => é

I've tried adding :encoding => "utf8" but nothing happened.

Any workaround?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.