I wrote a node.js server to generate and PDF using pdfkit and return it without saving to a file:
var http = require('http');
var PDFDocument = require('pdfkit');
var server = http.createServer();
server.on('request', function(request, response) {
console.log('request - ' + new Date());
buildReport(request, response);
});
server.listen(3000);
console.log('Servidor iniciado em localhost:3000. Ctrl+C para encerrar…');
function buildReport(request, response) {
var PDFDoc = new PDFDocument();
response.writeHead(200, {
'Content-Type': 'application/pdf',
'Access-Control-Allow-Origin': '*'
});
PDFDoc.pipe(response);
PDFDoc.font('fonts/DroidSans.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
// Finalize PDF file
PDFDoc.end();
}
If I go to the browser and type http:\\localhost:3000
it works fine. The PDF appears on the browser window.
But the problem is that I have to put the result of this request inside an iframe. This next line works:
$('#iframe').attr('src', 'http://localhost:3000');
But since I have to pass parameters to the server I'm using ajax and then it does not work. On the client side I have:
$.ajax({
url: 'http://localhost:3000',
data: {
reportData: reportData,
reportMetadata: reportMetadata,
reportLogo: reportLogo
}
}).done(function(data) {
$('#iframe').attr('src', data);
});
but this does not work. I tried alter the done function to:
.done(function(data) {
var PDFOutput = 'data:application/pdf;charset=UTF-8,'+data;
$('#iframe').attr('src', PDFOutput);
});
but it does not work either...
The value returned to the data variable inside done
function is a string that starts with:
"%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:20151010210841Z) >> endobj 9 0 obj << /Type /FontDesc (...)
What am I missing?
Thanks in advance!