Thank you very much for this amazing lib! Great job!
I would like to use pdf-lib in my express.js app. Below is a working example of an express.js app sending a Hello World pdf which Chrome reads just fine.
Am I doing things correctly?
'use strict';
var PdfLib = require('pdf-lib');
var PDFDocument = PdfLib.PDFDocument;
var StandardFonts = PdfLib.StandardFonts;
var rgb = PdfLib.rgb;
var express = require('express');
var app = express();
var port = 3000;
async function createPdf() {
var pdfDoc = await PDFDocument.create();
var timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);
var page = pdfDoc.addPage();
var { width, height } = page.getSize();
var fontSize = 30;
page.drawText('Hello World', {
x: 50,
y: height - 4 * fontSize,
size: fontSize,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
var pdfBytes = await pdfDoc.save();
var pdfBuffer = Buffer.from(pdfBytes.buffer, 'binary');
return pdfBuffer;
}
app.get('/', function(req, res) {
createPdf().then(function(pdfBuffer) {
res.status(200);
res.type('pdf');
res.send(buffer);
}).catch(function (err) {
res.status(500);
res.send(err.message);
});
});
app.listen(port, function() {
console.log(`Example app listening on port ${port}!`);
});
Hello @dhollenbeck!
Your implementation looks good to me. Are you running into any problems with this? Or did you just want a sanity check of your code?
The example code above works correctly with no problems. I just posted it in case it helps others. @Hopding your work is awesome. Thank you so much.
Thank you for leaving this. Allowed me to finally get express up and running after 3 days of frustration.
One slight modification to the code:
createPdf().then(function(pdfBuffer) {
res.status(200);
res.type('pdf');
res.send(pdfBuffer);
})
Thanks for this example! It seems that by default express doesn't handle Uint8Array nicely and returns the data in a weird format. Solution seems to be to return a Buffer: https://github.com/expressjs/express/issues/2910
Most helpful comment
The example code above works correctly with no problems. I just posted it in case it helps others. @Hopding your work is awesome. Thank you so much.