Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a PDF document from firebase cloud functions

I am quite new to firebase cloud functions and I am trying to get a PDF document generated and saved (either locally, in the firebase storage or even in the browser to then be sent to the user via nodemailer).

Below is the code I have so far but nothing gets created/ generated. I just get a 'crash' response on the Firebase log when the function is run:

const functions = require("firebase-functions");
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
const cors = require('cors')({origin: true});
var pdf = require('pdfmake');

var printer = new pdf();
var fs = require('fs');
var BUCKET = 'gs://mpca-19527.appspot.com'
admin.initializeApp();

exports.createWill = functions.https.onRequest((req, res) => {
    var docDefinition = {
        pageSize: 'A4',
        pageMargins: [ 40, 60, 40, 60 ],
        content: [
        'First paragraph',
        'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
        ]
        };

      var pdfDoc = printer.createPdfKitDocument(docDefinition);
      let file_name = 'facture.pdf';
      const myPdfFile = storage.bucket(BUCKET).file(file_name);
      pdfDoc.pipe(fs.createWriteStream('document.pdf'));    
      pdfDoc.end()
      
});

This is just a test snippet to even see how the PDFmake works and I cannot seem to get it to work. Can a pdf be generated and stored locally off a http request?

like image 669
Deji James Avatar asked Nov 20 '25 07:11

Deji James


1 Answers

so I'm posting my code here incase someone else needs it:

    const functions = require("firebase-functions");
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
const {Storage} = require('@google-cloud/storage');
admin.initializeApp();
const PdfPrinter = require('pdfmake/src/printer');
const BUCKET = 'INSERTLINK HERE FROM FIREBASE.appspot.com'

//CREATED A NEW FONTS FOLDER MANUALLY

const fonts = {
    Roboto: {
      normal: 'fonts/Roboto-Regular.ttf',
      bold: 'fonts/Roboto-Medium.ttf',
      bolditalics: 'fonts/Roboto-MediumItalic.ttf'
    }
  };



const printer = new PdfPrinter(fonts);
    const fs = require('fs'); 
    const storage = new Storage({
        projectId: 'INSERT YOUR PROJECT ID' });
        const cors = require('cors')({origin: true});

    let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '[email protected]',
            pass: 'INSERT PASSWORD'
        }
    });

exports.createWill = functions.https.onRequest((req, res) => {
    
var docDefinition = {
    content: [
        'First paragraph',
        'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines',
        
    ]
};

      var pdfDoc = printer.createPdfKitDocument(docDefinition);   
      let file_name = 'facture.pdf';
    const myPdfFile = storage.bucket(BUCKET).file(file_name);
    pdfDoc.pipe(myPdfFile.createWriteStream())
    .on('finish', function (){
      cors(req, res, () => {
        // getting dest email by query string
        const dest = 'INSERT DESTINATION [email protected]';
        const mailOptions = {
            from: 'NAME <MY [email protected]>', 
            to: dest,
            subject: 'I\'M A PICKLE!!!', 
            html: `<p style="font-size: 16px;">Pickle Riiiiiiiiiiiiiiiick!!</p>
                <br />`,
                attachments: [
                    {   
                        filename: 'facture.pdf',
                        contentType: 'application/pdf',
                        content: myPdfFile.createReadStream()
                    }
                ]  
        };
  
        // returning result
        return transporter.sendMail(mailOptions, (erro, info) => {
            if(erro){
                return res.send(erro.toString());
            }
            return res.send('Sent');
        });
    });  
    })
    .on('error', function(err){
      console.log('Error during the wirtestream operation in the new file');
     // res.send('Error: something goes wrong ! '+ err);
    });
    
    pdfDoc.end();
});
});
like image 108
Deji James Avatar answered Nov 22 '25 02:11

Deji James