【发布时间】:2015-05-24 22:35:44
【问题描述】:
我想使用 PhantomJS 从 Jade 中的模板创建 PDF,我可以创建 PDF 文档,但 CSS 不适用,我创建了两条路由,第一个将模板渲染到 Web 浏览器,第二个生成使用完全相同的jade模板de PDF,在浏览器中一切正常,但PDF不应用CSS。
我的 app.js 是:
var express = require('express'),
routes = require('./routes'),
http = require('http'),
path = require('path'),
bodyParser = require('body-parser');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(express.static(path.join(__dirname, 'public')));
app.post('/api/cotizacion/generar', routes.cotizacion.generar);
app.get('/api/cotizacion/generar', routes.cotizacion.testGenerar);
app.all('*', function(req, res) {
res.send(404);
});
http.createServer(app).listen(app.get('port'), function(){
console.info('Express server listening on port ' + app.get('port'));
});
控制器文件是cotizacion.js:
var phantom = require('phantom');
exports.generar = function(req, res, next){
if(!req.body.cotizacion){
return next(new Error('No se enviaron datos de cotización'));
}
var cotizacion = req.body.cotizacion;
req.app.render('test', {cotizacion: cotizacion}, function(err, html){
generarPDF(cotizacion, html, function(){
res.send("1");
});
});
};
exports.testGenerar = function(req, res, next){
res.render('test', {});
};
generarPDF = function(cotizacion, html, callback){
phantom.create(function(ph){
ph.createPage(function(page){
page.set('paperSize', { format: 'Letter' });
page.set('content', html);
page.render(__dirname + '/test.pdf', function(err){
ph.exit();
callback();
});
});
});
}
最后我的 test.jade 是:
doctype html
html
head
title Cotización PDF
link(rel='stylesheet', href='/css/pdf.css')
body
h1 Test
以下工作,但有点烦人
doctype html
html
head
title Cotización PDF
| <style type="text/css">
| body{ color: green; }
| </style>
body
h1 Test
项目结构为:
/
app.js
public/
css/
pdf.css
routes/
index.js
cotizador.js
views/
test.jade
【问题讨论】:
-
您解决了这个问题吗?一段时间以来,我们一直在为同样的问题苦苦挣扎……但不知道出了什么问题!
标签: css node.js pdf phantomjs pug