如何从创建的PDF文件中将base64字符串发送到客户端?

时间:2019-02-16 09:47:50

标签: javascript node.js express node-pdfkit

我有一个node.js / express.js应用程序,其中的路由使用pdfkit创建了pdf文件。这可行,并且pdf文件作为文件写入我的文件系统中。 但是,我需要的流程是无需将文件写入文件系统中,而是可以将base64字符串发送给客户端。

但是,以下方法为我创建了一个有效的pdf文件,但base64字符串始终为空。该怎么办?

const PDFDocument = require('pdfkit');
// Create a document
const doc = new PDFDocument;

// Add an image, constrain it to a given size, and center vertically and horizontally

doc.pipe( fs.createWriteStream('out.pdf') );

// Add another page
 doc.addPage()
 .fontSize(25)
 .text('Here is some vector graphics...', 100, 100);

 // Draw a triangle
 doc.save()
 .moveTo(100, 150)
 .lineTo(100, 250)
 .lineTo(200, 250)
 .fill("#FF3300");

 // Apply some transforms and render an SVG path with the 'even-odd' fill rule
  doc.scale(0.6)
  .translate(470, -380)
  .path('M 250,75 L 323,301 131,161 369,161 177,301 z')
  .fill('red', 'even-odd')
  .restore();

// Add some text with annotations
 doc.addPage()
  .fillColor("blue")
  .text('Here is a link!', 100, 100)
  .underline(100, 100, 160, 27, {color: "#0000FF"})
  .link(100, 100, 160, 27, 'http://google.com/');

  // Finalize PDF file
  doc.end();

// Create base64
 function base64Encode(file) {
   var body = fs.readFileSync(file);
  return body.toString('base64');
}


 var base64String = base64Encode('out.pdf');
 console.log(base64String);

// API result object to be sent to client
res.status(200).json({
 status: "success",
 data: base64String, 
 message: "Congrats! "
 });

1 个答案:

答案 0 :(得分:0)

经过一番摸索,我找到了一个可行的解决方案。

// you pdf settings here.
let options = {
  margins: 50
}

// create doc with settings
const doc = new PDFDocument(options);
// create stream and pipe doc
let out = fs.createWriteStream('output.pdf')
doc.pipe(out);

// create the pdf content
doc.addPage()
   .fontSize(25)
   .text('Here is some vector graphics...', 100, 100);

 // finalize document
 doc.end();

 // Stream on finish event handling after document construction ended
 out.on('finish', function() {

  // read pdf file as base64
  fs.readFile('output.pdf', 'base64', function(err, data) {
  if (err) throw err;
  console.log(data);

  // Send base64 pdf to client
    res.status(200).json({
      status: "success",
      data: data,
      message: "Congrats! "
    });
});
});

我使用这里的答案(@CHACO)从base64字符串构造pdf文件客户端:

how to display base64 encoded pdf?