在Node.js的Canvas中将PNG图像转换为PDF

4
我需要从画布(canvas)创建一份PDF文档,有人能帮我吗?
以下是我尝试过的方法:
var http = require('http'), fs = require('fs'),
Canvas = require('canvas');
var ht = require('https');
http.createServer(function (req, res) {
 dr();
function dr()
{

    fs.readFile(__dirname + '/temp.jpg', function(err, data) {
        if (err) throw err;
        var img = new Canvas.Image; // Create a new Image
        img.src = data;

        var canvas = new Canvas(img.width, img.height,'pdf');
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);
        res.writeHead(200, {'content-type' : 'application/pdf'}); 
        canvas.toDataURL('application/pdf', function(err, str){

        res.write( str );

        res.end();

        });

    });

}

}).listen(8124);

什么不起作用?你期望什么输出? - Paul Mougel
我需要在网页上显示PDF文件。res.writeHead(200, {'content-type' : 'application/pdf'});但是出现错误:目前仅支持image/png格式。是否有其他方法? - SHIN
1
@WiredPrairie,node-canvas文档中提到,如果我使用enablepdf=yes配置mu cairo,则可以支持pdf。我需要创建带有pdf标志的画布(var canvas = new Canvas(img.width, img.height,'pdf');),我已经这样做了,但无法将其作为pdf发送回网页或在服务器上保存到我的驱动器上。 - SHIN
此处引用的 canvas.toDataURL('application/pdf', function(err, str) 仅支持 png 格式,这就是我卡住的地方。 - SHIN
1
你能否使用示例使PDF正常工作:https://github.com/LearnBoost/node-canvas/blob/2354d9bb8c7d030ea85796541f0ff82d2207a611/examples/small-pdf.js - WiredPrairie
显示剩余2条评论
1个回答

3
这段代码对我有效。
var http = require('http'), fs = require('fs'),
Canvas = require('canvas');
var ht = require('https');
http.createServer(function (req, res) {
 dr();
function dr()
{

    fs.readFile(__dirname + '/temp.jpg', function(err, data) {
        if (err) throw err;
        var img = new Canvas.Image; // Create a new Image
        img.src = data;

        var canvas = new Canvas(img.width, img.height, 'pdf');
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);

        res.writeHead(200, {'content-type' : 'application/pdf'});
    res.write( canvas.toBuffer() );
    res.end();  
    });

}

}).listen(8124);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接