Use PHANTOMJS to generate PDFs in Ruby on Rails

Source: Internet
Author: User
Tags ruby on rails

First, the new project

Rails new App--skip-bundle

Modify Gemfile file after completion: Vim Gemfile

Change source to Taobao or Ruby-china.

Add to this file: Gem ' Phantomjs '

Then run: Bundle install

So the project is new and completed.

Second, generate PDF

Create a controller to add require ' PHANTOMJS ' to the head and add a get method for getting the PDF: get_pdf

Add the following code to this method:

Phantomjs.base_dir = "/path/project_name/bin/phantomjs/" #phantomjs将要安装的目录
Phantomjs.run ('/path/project_name/public/generate_pdf.js ')

Send_file ("Public/mypdf.pdf",: filename = "mypdf.pdf",: type = "Application/pdf")

Add the following code to Generate_pdf.js:

var page = require (' webpage '). Create ();
Page.open (' http://www.baidu.com ');
page.onloadfinished = function () {
Page.render (' public/mypdf.pdf ');
Phantom.exit ();
}

Third, the operation

Start Service: Rails s

Enter http://localhost:3000/controller/get_pdf in the address bar

The first time this method is requested, it installs the directory Phantomjs to/path/project_name/bin/phantomjs/.

Once the installation is complete, you can see the PDF that you saved:

  

So this is a success.

Note: This exported PDF does not contain background and background images in CSS styles.

  

Use PHANTOMJS to generate PDFs in Ruby on Rails

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.