Using PDF-LIB in JavaScript Action

0
I'm trying to build javascript actions for PDF using https://pdf-lib.js.org/, I've downloaded the js from NPM and now I'm trying to use it, but with no success. If I add those files to the module folder in "javascriptsource" and then add them to the import list import { PDFDocument, StandardFonts, rgb } from '../pdf-lib' then I can build and run the project. But I get the following error when trying to execute the action _pdf_lib__WEBPACK_IMPORTED_MODULE_3__.PDFDocument is undefined O/<@http://localhost:8080/mxclientsystem/mxui/mxui.js?637362954966831127:80:298177 When I try it in the way as described in the documentation https://docs.mendix.com/howto/extensibility/best-practices-javascript-actions#2-2-6-using-external-dependencies-in-the-browser I can't even run my project.
asked
1 answers
5

Hi Jelle,

Please try to install your node module in the folder <project>javascriptsource\<module>\actions

Then you can use the normal import

import { PDFDocument } from "pdf-lib"

Be careful check if the node_module folder is ignored SVN when you commit your project.

Please note the node_modules folder could be huge sometimes… slowing down your svn commits. Therefor you can remove all unused files. 

import { PDFDocument } from "pdf-lib"

// BEGIN EXTRA CODE
function saveDocument(imageObject, filename, blob) {
    return new Promise((resolve, reject) => {
       const guid = imageObject.getGuid();
       const onSuccess = () => resolve();
       const onError = (error) => reject(error.message);
       mx.data.saveDocument(guid, filename, {}, blob, onSuccess, onError);
    });
}
// END EXTRA CODE

/**
 * @param {MxObject} file
 * @returns {Promise.<void>}
 */
export async function CreatePDF(file) {
    // BEGIN USER CODE
    const pdfDoc = await PDFDocument.create();
    const page = pdfDoc.addPage();
    page.drawText('You can create PDFs!');
    const pdfBytes = await pdfDoc.save();
    return saveDocument(file, "my file.pdf", new Blob([pdfBytes]));
    // END USER CODE
}

Cheers, Andries

 

answered