尝试编写一个测试(mocha)来检查从我的api端点返回的PDF是否保存了正确的数据,看起来应该是这样。 PDF是在服务器上生成的。当手动命中端点时,它会“正确地”返回,但是想要编写一些测试。我在我的测试套件中上传了一个“正确的”PDF示例,我可以用hummus js解析并提取必要的方面进行比较。
我想向我的终端发出请求(使用superagent),然后将响应(pdf)传送到临时pdf中。然后我将解析PDF(上传完美的一个,以及从我的端点返回的那个),并确保它们匹配。
我的请求代码:
it('Should look like the proposed pdf', function (done) {
request(app)
.get(url) //var that sets the path earlier
.expect(200)
.end(function (err, res) {
if(err) return done(err);
var writeStream = fs.createWriteStream('./test/materials/tmp.pdf');
writeStream.pipe(res); //ERROR can't pipe
writeStream.on('end', function() {
console.log('complete');
done();
})
});
});
当我运行我的测试时,我得到:未捕获错误:无法管道。不可读。我对节点很新,所以我不确定导致错误的原因。当我控制res时,我得到一个大的二进制编码混乱,所以可能这是问题?我尝试了几件事 - 使用hummus pdfWriter,试图用
进行解码等等......但仍然没有运气。我相信我为这些操作安装了所有必需的软件包,它似乎是一个管道/解码/超级问题。谢谢你的帮助! 编辑:我误解了管道。您只需将响应写入文件:new Buffer(res,'base64')
fs.writeFile('./test/materials/test_tmp.pdf', new Buffer(res.text, 'ascii'));
在这种情况下转换为ascii。我现在离我很近,但仍然挂在编码片上。这会创建一个空白PDF。当我在sublime中观察文件内容时,它们看起来与我正在比较的PDF相同,但具有不同的编码。有谁知道如何匹配原始PDF的编码或弄清楚它是如何编码的?或者如果这是可能的话?我使用PDFkit来构建PDF。
答案 0 :(得分:0)
我不认为(或知道)本地执行此操作的方法。如果您愿意使用其他模块,请选择look at pdfkit
您可以执行类似
的操作var pdf = new PDFDocument;
pdf.pipe(fs.createWriteStream('./test/materials/tmp.pdf'));
EDIT
道歉,我认为你的问题有点不对劲。该模块有一些例子。例如,他们的文档 -
PDFDocument = require 'pdfkit'
# Create a document
doc = new PDFDocument
# Pipe it's output somewhere, like to a file or HTTP response
# See below for browser usage
doc.pipe fs.createWriteStream('output.pdf')
# Embed a font, set the font size, and render some text
doc.font('fonts/PalatinoBold.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100)
# 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()