I am new to javascript and I'm trying to make a PDF file from a firebase function using pdfkit. Below is my function code.
const pdfkit = require('pdfkit');
const fs = require('fs');
exports.PDFTest = functions.https.onRequest((req, res) => {
var doc = new pdfkit();
var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in...';
doc.y = 320;
doc.fillColor('black')
doc.text(loremIpsum, {
paragraphGap: 10,
indent: 20,
align: 'justify',
columns: 2
});
doc.pipe( res.status(200) )
});
The function starts but then a timeout error happens. Is this the best way of going about creating a pdf file in firebase? I have some html that I want made into a pdf file.
I worked on this too and here below you can find a sample of cloud function that is creating a PDF file from a template HTML hosted on firebase storage. It uses Hanldebars to apply some data to the template and then upload it again on firebase storage. I used node-html-pdf here.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const pdf = require('html-pdf');
const gcs = require('@google-cloud/storage')({
projectId: '[YOUR PROJECT ID]',
//key generated from here https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk?authuser=1
keyFilename: '[YOUR KEY]'
});
const handlebars = require('handlebars');
const path = require('path');
const os = require('os');
const fs = require('fs');
const bucket = gcs.bucket('[YOUR PROJECT ID].appspot.com');
admin.initializeApp(functions.config().firebase);
exports.helloWorld = functions.https.onRequest((request, response) => {
// data to apply to template file
const user = {
"date": new Date().toISOString(),
"firstname" : "Guillaume",
};
const options = {
"format": 'A4',
"orientation": "portrait"
};
const localTemplate = path.join(os.tmpdir(), 'localTemplate.html');
const localPDFFile = path.join(os.tmpdir(), 'localPDFFile.pdf');
bucket.file('template.html').download({ destination: localTemplate }).then(() => {
console.log("template downloaded locally");
const source = fs.readFileSync(localTemplate, 'utf8');
const html = handlebars.compile(source)(user);
console.log("template compiled with user data", html);
pdf.create(html, options).toFile(localPDFFile, function(err, res) {
if (err){
console.log(err);
return response.send("PDF creation error");
}
console.log("pdf created locally");
return bucket.upload(localPDFFile, { destination: user.name + '.pdf', metadata: { contentType: 'application/pdf'}}).then(() => {
response.send("PDF created and uploaded!");
}).catch(error => {
console.error(error);
response.send("PDF created and uploaded!");
});
});
});
});
Hope this will help the next one doing this :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With