How do I create PDFs in the DB from CC

I have a requirement of Downloading the PDF file, naming it and then saving it as an attachment on a model field in a cloudecode task on the fly while fetching records.

PDF download link will be like “http://www.africau.edu/images/default/sample.pdf"

Could you please help me to figure out the best way to achieve this functionality.

In order to save a PDF to the DB from CC you will need to use the Backend API from within CC. It is not currently possible to create so-called attachment data types (photo, signature, pdf, etc.) directly on a DB object from CC, but you can do it using the standard Backend API.

Backend API reference here

Field representation for attachments reference here

CC task code

export async function run() {
    // Your code here
    const pdf2base64 = require('pdf-to-base64');
    let pdfUrl = 'http://www.africau.edu/images/default/sample.pdf';
    let jaBaseURL = 'https://run-testing-us.journeyapps.com/api/v4/';
    let jaBackedID = 'my_account_id_here'
    let jaBackendAuthToken = 'O:mytoken';
let base64 = await pdf2base64(pdfUrl);
console.log("Base 64: ", base64);

// This assumes a model named 'pdf' with a field named 'name' of type 'text' and a field named 'generated_pdf' of type 'attachment'
var newPDF = {
    pdf: {
        name: `CC create: ${(new Date).toLocaleString()}`,
        generated_pdf: {
            base64: base64,
            filename: "cc_created_pdf.pdf"
        }
    }
}


let options = {
    method: 'POST',
    headers: {
        "Content-Type": "application/json",
        "Authorization": `Token ${jaBackendAuthToken}`
    },
    body: JSON.stringify(newPDF)
}

let result = await fetch(`${jaBaseURL}/${jaBackedID}/objects/pdf.json`, options);

let response = await result.json();

console.log("Done - Result: ", JSON.stringify(response));

}

@tielman You can now do it a lot easier. Assuming you are using the same objects as in your example you can now do the following in CloudCode v1.10.1:

async function saveReport(pdf, generatedPdf) {
    const generated_pdf = await Attachment.create({base64: base64, mediaType:'application/pdf', filename: 'job_report.pdf'});
    pdf.generated_pdf = generated_pdf;
}
5 Likes