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