【问题标题】:How to send base64 String from created PDF file to client?如何将base64字符串从创建的PDF文件发送到客户端?
【发布时间】:2019-07-10 07:59:27
【问题描述】:

我有一个 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! "
 });

【问题讨论】:

    标签: javascript node.js express node-pdfkit


    【解决方案1】:

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

    // 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?

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2018-10-27
      • 2020-07-15
      • 1970-01-01
      相关资源
      最近更新 更多