Use Pdfkit to generate PDFs in Ruby on Rails

Source: Internet
Author: User
Tags wkhtmltopdf ruby on rails

Said is the use of pdfkit, in fact, the work is still wkhtmltopdf.

First, the new project

Rails New Mypdf--skip-bundle

Enter project: CD mypdf, open Gemfile:vim gemfile

Modify Source to Https://ruby.taobao.com

Added: Gem ' Pdfkit '

Run Bundle Install

Second, the configuration

Add the Pdfkit.rb file to the Config/initializers in the project directory with the following modifications:

Pdfkit.configure do |config|
config.wkhtmltopdf = '/path/wkhtmltopdf '
End

Config.wkhtmltopdf is configured with the Wkhtmltopdf path, make sure Pdfkit can find it.

Other configuration Please refer to: Http://wkhtmltopdf.org/usage/wkhtmltopdf.txt, the inside of the horizontal bar with the underline instead.

Third, the use

In the controller, add the corresponding position:

Raw PDF with rendered template content:

html = render_to_string (: template = "Pdf_template.erb",: Layout = False)

Kit = pdfkit.new (HTML)
Kit.stylesheets << "#{rails.root}/app/assets/assets/stylesheets/pdf.css"
#kit. to_pdf # inline PDF
#kit. To_file ('/path/pdf.pdf ')
Send_data (kit.to_pdf,: filename = "mypdf.pdf",: type = "Application/pdf")
#render: Text = kit.to_pdf

To generate a PDF with the contents of the URL:

url = "Http://www.baidu.com"
Kit = pdfkit.new (URL)
# kit.stylesheets << ' #{rails.root}/app/assets/assets/stylesheets/pdf.css ' # CSS styles are not available when using URLs.
#kit. to_pdf # inline PDF
#kit. To_file ('/path/pdf.pdf ')
Send_data (kit.to_pdf,: filename = "mypdf.pdf",: type = "Application/pdf")

Note: Kit = pdfkit.new (URL, cookie: {"cookie_name" + "Cookie_content"}), you can use cookies if you need to log in. Cookies can be obtained by themselves.

So it can be used.

  

Use Pdfkit to generate PDFs in Ruby on Rails

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.