我遇到了我想要实现的心理模型的问题,如果情况确实如此,我可能会完全错误并道歉。
我正在构建一个处理预算产品的全栈应用程序,我所拥有的是一个React客户端,它发送一个“预算”对象,其中包含有关发布请求的所有相关信息到我的服务器,它看起来像像:
let budget = {
name: 'John Doe',
phone: 12345,
email: 'johndoe@gmail.com'
cart: [Object with name, quantity, and price of product, etc, another object that represents another product],
subTotal: 100,
tax: 12,
total: 112
}
我将该数据发送到我的NodeJS / Express服务器,我在其中使用PDFKit来帮助我创建PDF,我想将其发送回客户端,以便用户可以下载/打印/查看PDF格式的预算,服务器中的代码看起来像这样
const pdf = require('pdfkit');
const fs = require('fs');
exports.makeBudgetPDF = (req, res) => {
let myDoc = new pdf;
myDoc.pipe(res);
myDoc.font('Times-Roman')
.fontSize(12)
.text(`this is a test budget`);
myDoc.end();
res.setHeader('access-control-allow-origin', '*');
res.status(200);
}
这一切都很好,我正在通过请求的响应发送回客户端,但我不知道如何从那里显示它,我得到一个数据对象(我正在使用axios来处理请求客户端)看起来像这样,我完全不知道该怎么做
Object
data:
"%PDF-1.3↵%����↵5 0 obj↵<<↵/Type /Page↵/Parent 1 0 R↵/MediaBox [0 0 612 792]↵/Contents 3 0 R↵/Resources 4 0 R↵>>↵endobj↵4 0 obj↵<<↵/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]↵/Font <<↵/F2 6 0 R↵>>↵>>↵endobj↵7 0 obj↵<<↵/Producer (PDFKit)↵/Creator (PDFKit)↵/CreationDate (D:20170623192634Z)↵>>↵endobj↵6 0 obj↵<<↵/Type /Font↵/BaseFont /Times-Roman↵/Subtype /Type1↵/Encoding /WinAnsiEncoding↵>>↵endobj↵2 0 obj↵<<↵/Type /Catalog↵/Pages 1 0 R↵>>↵endobj↵1 0 obj↵<<↵/Type /Pages↵/Count 1↵/Kids [5 0 R]↵>>↵endobj↵3 0 obj↵<<↵/Length 200↵/Filter /FlateDecode↵>>↵stream↵x��O9NA�����.OK#$Ȑ:C0G6��?Y�j�@�ڲ�\�g=H>є������=��R(�B�4�S��㫒(��|��P4��OT+��s8*�!�&�f�V
��3\�g�&]`X1+��슯$�pe������bK��jK��n�?����^��m8��8s�q2K�Jv$;JS}O�����'��~.��T�↵endstream↵endobj↵xref↵0 8↵0000000000 65535 f ↵0000000448 00000 n ↵0000000399 00000 n ↵0000000505 00000 n ↵0000000119 00000 n ↵0000000015 00000 n ↵0000000300 00000 n ↵0000000208 00000 n ↵trailer↵<<↵/Size 8↵/Root 2 0 R↵/Info 7 0 R↵>>↵startxref↵777↵%%EOF↵"
headers:
Object
request:
XMLHttpRequest
status:
200
statusText:
"OK"
我一直在研究很多但似乎无法找到答案
答案 0 :(得分:0)
我不熟悉PDFKit,但一直在使用PDFMake。 您可能需要在标题中设置回复的内容类型,类似于:
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-disposition': 'attachment;filename=[your-filename].pdf',
'Content-Length': response.ContentLength
});
这将强制在用户的浏览器中下载。
将[your-filename]换成你想要命名的文件。 response.ContentLength
是前一个回调的PDF缓冲区大小,在我的示例中未显示。将其替换为文档的内容大小。
[编辑]只是记住,我有问题管道到res。您可能最终将PDF写入缓冲区然后调用:
res.end(Buffer.from([your pdf buffer]));
答案 1 :(得分:0)
也许是老问题,但我遇到了类似的问题并找到了答案。
首先当你创建新的 pdf 时使用:
const myDoc = pdf();
对我有用的代码看起来像这样:
const pdfName = "generated.pdf";
const generatedPdfPath = path.join("dist", "temp", pdfName); // depending where you want your pdf
const doc = new pdf();
res.setHeader("Content-Type", "application/pdf");
res.setHeader("Content-Disposition", `inline; filename=${pdfName}`);
doc.pipe(fs.createWriteStream(generatedPdfPath));
doc.pipe(res);
doc.text('some text or anything else you want');
// in my case I was adding multiple images and it also worked fined
doc.end();