4

I need to create a pdf from canvas. can any body help me ?

this is what i tried

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);
Damodaran
  • 10,882
  • 10
  • 60
  • 81
SHIN
  • 386
  • 2
  • 13
  • What doesn't work? What output do you expect? – Paul Mougel Nov 26 '13 at 10:07
  • i need to display the pdf back to webpage res.writeHead(200, {'content-type' : 'application/pdf'}); but Error: currently only image/png is supported. is there any otherway – SHIN Nov 26 '13 at 10:09
  • You didn't actually do any conversion to PDF in the code. You basically just changed the mime type. Find a PDF creation library for NodeJS that can take an image you've generated. Canvas can't do it. – WiredPrairie Nov 26 '13 at 11:52
  • 1
    @WiredPrairie the node-canvas doc says they have pdf support if i configure mu cairo with enablepdf=yes. and i need to create canvas with pdf flag ( var canvas = new Canvas(img.width, img.height,'pdf'); ) i did it but not able to send it back to webpage or save on my drive on server as pdf – SHIN Nov 26 '13 at 11:55
  • more over the canvas.toDataURL('application/pdf', function(err, str) is supporting only png. thats where i stuck. – SHIN Nov 26 '13 at 11:57
  • 1
    Can you get PDF to work with a sample: https://github.com/LearnBoost/node-canvas/blob/2354d9bb8c7d030ea85796541f0ff82d2207a611/examples/small-pdf.js – WiredPrairie Nov 26 '13 at 11:59

1 Answers1

3

This code working for me.

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);
SHIN
  • 386
  • 2
  • 13