簡體   English   中英

如何將創建的 PDF 文件中的 base64 字符串發送到客戶端?

[英]How to send base64 String from created PDF file to client?

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

經過一番玩耍,我找到了一個可行的解決方案。

// 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 文件客戶端:

如何顯示base64編碼的pdf?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM