6

我在 nodejs 上有一个函数,它从许多图像中生成图像,然后从中生成一个 pdf 文件。我只尝试一张图片,但我需要添加更多,但这似乎不起作用

function HelperHandler() {
  this.pdf = function(req, res, next) {
    var doc = new PDFDocument;
    mergeImages(function(err, image) {
      if (err)
        return res.json(err);

      doc.image(image, 100, 100);
      doc.output(function(string) {
        res.contentType = "application/pdf";
        res.send(string);
      });
    })
  }
}

var mergeImages = function(callback) {
  var Canvas = require("canvas")
    , fs     = require("fs");

  fs.readFile(global.root_path + "/images/bg.jpg", function(err, data) {
    if (err)
      callback("error loading image");
    else {
      var canvas = new Canvas(408, 939)
        , img    = new Canvas.Image(data);
      ctx = canvas.getContext("2d");
      img.onload = function() {
        ctx.drawImage(img, 0, 0, 408, 939);
      }
      canvas.toDataURL('image/png', function(err, str) {
        callback(null, str);
      });
    }
  });
}

错误

Error: ENAMETOOLONG, name too long 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZgAAAOrCAYAAABqSpB/AAAABmJLR0QA/wD/AP+gvaeTAAAF5UlEQVR4nO3BMQEAAADCoPVPbQo/oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICjAWckAAHF4EUcAAAAAElFTkSuQmCC'
    at Object.openSync (fs.js:427:18)
    at Object.readFileSync (fs.js:284:15)
    at Function.open (/Users/jtomasrl/code/app/server/node_modules/pdfkit/js/image.js:27:28)
    at PDFDocument.image (/Users/jtomasrl/code/app/server/node_modules/pdfkit/js/mixins/images.js:27:26)
    at /Users/jtomasrl/code/app/server/lib/handler/current/helper.js:15:11
    at /Users/jtomasrl/code/app/server/lib/handler/current/helper.js:41:9
    at /Users/jtomasrl/code/app/server/node_modules/canvas/lib/canvas.js:217:7
4

1 回答 1

9

可以使用缓冲区或路径对 PDFKit 图像

但是您不能使用 base64 URL,您需要将此字符串解码为缓冲区。

要使用 base64 数据:

doc.image(new Buffer(image.replace('data:image/png;base64,',''), 'base64'), 100, 100); // this will decode your base64 to a new buffer

有关使用 Node Buffer 进行 base64 解码/编码的更多信息,请点击此处

于 2014-03-11T21:28:47.247 回答