PDF reports and attachments

I had a use case to generate a PDF report with images and then needed to save it as an attachment in the DB.
The journey pdf-reports module is great for this!

This little snippet shows how you can use the toBase64() function from the report to save a generated PDF in the DB, for use in the app:

const generatedPdf = await pdf.generatePdf({ html: pdfHtml });
var base64_prepresentation = await generatedPdf.toBase64()
db_obj.attachment_property = await Attachment.create({filename: "certificate.pdf", base64: base64_prepresentation, mediaType:'application/pdf'})

The other fun thing to do is to then take an attachment and add it to a PDF report: (showing an image in the PDF)

const pdfTemplate = handlebars.compile(`
<!DOCTYPE html>
    <h1>HTML pdf</h1>
    <img src="{{url_to_attachment}}">
const pdfHtml = pdfTemplate({ url_to_attachment: db_obj.attachment_property.url() });
const generatedPdf = await pdf.generatePdf({ html: pdfHtml })

Any input on better practices here would be grealy appreciated!

1 Like

@reggiepret This looks great

One thing I would add is to remember that attachments are last on the sync priority. What this means practically is that the rest of an object can be synched to the Cloud with the attachment still not synched/ “stuck” on the user’s device. And for this reason it is good practice to check the “state” of the attachment field before trying to access the url - check this post for more information

1 Like