Table: RailsNotes
User: dreamable
Created at: 2020-11-02 23:53:43 UTC
Updated at: 2021-01-25 10:00:21 UTC
Reference:(Table ID 3, Record ID 1)

标题 :
wicked_pdf
笔记 :

采用wicked_pdf产生PDF文档

  1. Gemfile

    gem 'wicked_pdf'
    gem 'wkhtmltopdf-binary'
    #gem 'wkhtmltopdf-binary-edge' # fork of wkhtmltopdf-binary,不需要
    
  2. install libxrender1

    • Error, error while loading shared libraries: libXrender.so.1
    • Solution: Need to install sudo apt-get install libxrender1
  3. in config/initializers/mime_types.rb

    Mime::Type.register "application/pdf", :pdf 
    
    • Optional? PDF may be builtin for new version.
  4. define template in app/views/layouts/pdf.html.erb

        <!doctype html>
        <html>
        <head>
            <meta charset='utf-8' />
            <%= javascript_include_tag "https://code.jquery.com/jquery-3.3.1.slim.min.js" %>
            <%= javascript_include_tag "http://code.jquery.com/ui/1.10.3/jquery-ui.min.js" %>
            <%= javascript_include_tag "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" %>
            <%= javascript_include_tag "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" %>
        </head>
        <body onload='number_pages'>
            <div id="header">
            </div>
            <div id="content">
            <%= yield %>
            </div>
        </body>
        </html>
    
    • NOTE: In the official guide, you can include local css/js, but you need to define it and pre-compile it for production. Otherwise, the missing assets could be OK in development but failed in production
        <%= wicked_pdf_stylesheet_link_tag "pdf" -%>
        <%= wicked_pdf_javascript_include_tag "number_pages" %>
    
    • although include jquery & bootstrap cdn in pdf.html.erb, but seems not work.
  5. specify template

    • define default template in config/initlializers/wicked_pdf.rb
       layout: 'pdf.html'
    
    • specify in page view when using it.
  6. Use it in controllers

    in  app/controller/records_controller.rb
      format.pdf do
        render pdf: "records",
        template: "records/index.html.erb"
    #        layout: "pdf.html"
      end
    
    • You could customized layout template here.
  7. If you use assets, pre-compile it for production. in config/initializers/assets.rb. e.g.

    Rails.application.config.assets.precompile += ['blueprint/screen.css', 'pdf.css', 'jquery.ui.datepicker.js', 'pdf.js']
    
    • Not used and tested yet.
  8. Chinese character problem.

    • set UTF8 in layout <meta charset='utf-8' />
    • install font: sudo apt-get install fonts-wqy-zenhei
Tag: