Generating a PDF when a document is created in Firebase Cloud Firestore

Viewed 997

I'm developing an app that creates a PDF based on a web form.

I am currently attempting to use pdfmake to generate the PDFs based on a firestore document create trigger

import * as functions from 'firebase-functions';
const admin = require('firebase-admin);
admin.initializeApp();
const PdfPrinter = require('pdfmake');
const fs = require('fs');

export const createPDF = functions.firestore
    .document('pdfs/{pdf}')
    .onCreate(async (snap, context) => {

        var pdfName  = context.params.pdf;
        var printer = new PdfPrinter();

        var docDefinition = {
        // Pdf Definitions
        };

        var options = {
        // Pdf Options
        };

        var pdfDoc = printer.createPdfKitDocument(docDefinition, options);
        pdfDoc.pipe(fs.createWriteStream('tempDoc.pdf'));
        await pdfDoc.end();


        // Upload to Firebase Storage
        const bucket = admin.storage().bucket('myproject.appspot.com');
        bucket.upload('tempDoc.pdf', {
            destination: pdfName + '.pdf',
        });

        return fs.unlinkSync('document.pdf');
    });

The trigger is called, however i get the error "Error: ENOENT: no such file or directory, stat 'document.pdf'"

I have tried it with the onCreate function being async and without.

Any help is greatly appreciated

1 Answers

It's not possible to write to any file location in Cloud Functions outside of /tmp. If your code needs to write a file, it should build paths off of os.tmpdir() as described in the documentation:

The only writeable part of the filesystem is the /tmp directory, which you can use to store temporary files in a function instance. This is a local disk mount point known as a "tmpfs" volume in which data written to the volume is stored in memory. Note that it will consume memory resources provisioned for the function.

The rest of the file system is read-only and accessible to the function.

Related