Home > Software design >  jsPDF Error: autoTable is not a function in SAP UI5
jsPDF Error: autoTable is not a function in SAP UI5

Time:01-23

I am using the jsPDF library for converting a table into a PDF file. The current code that I have used is giving off an error, that autoTable is not a function. Here is the code.

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel",
    "sap/ui/core/util/Export",
    "sap/ui/core/util/ExportTypeCSV"
],

    function (Controller, JSONModel, Export, ExportTypeCSV) {
        "use strict";

        return Controller.extend("c.g.modalproject1.controller.Root", {
            onInit: function () {

                var oModel1 = new JSONModel("./model/vegetableDataJSON.json");
                this.getView().setModel(oModel1, "veg");
                console.log("data : ", oModel1);

            },

            openDialog1: function () {
                if (!this.pdialog1) {
                    this.pdialog1 = this.loadFragment({
                        name: "c.g.modalproject1.fragments.mTables"
                    });
                }
                this.pdialog1.then(function (oDialog) {
                    oDialog.open();
                })
                new sap.m.MessageToast.show("Table Loaded");
            },

            closeDialog: function () {
                this.byId("newDialog1").close();
                sap.m.MessageToast.show("Table closed ! ");

                // var vegTable = this.getView().byId("vegiesMTable");
                // vegTable.setGrowing(false);
                // vegTable.setGrowingScrollToLoad(false);

            },

            downloadCSV: function () {
                // Show a toast message to indicate that the file is downloading
                sap.m.MessageToast.show("Downloading Excel..");
                // Create a new Export object with the specified export type and options
                var oExport = new Export({
                    exportType: new ExportTypeCSV({
                        separatorChar: ","
                    }),
                    models: this.getView().getModel("veg"),
                    rows: {
                        path: "/vegetablesRootNode"
                    },
                    columns: [{
                        name: "Title",
                        template: {
                            content: "{title}"
                        }
                    },
                    {
                        name: "Type",
                        template: {
                            content: "{type}"
                        }
                    },
                    {
                        name: "Description",
                        template: {
                            content: "{description}"
                        }
                    },
                    {
                        name: "Price",
                        template: {
                            content: "{price}"
                        }
                    },
                    {
                        name: "Rating",
                        template: {
                            content: "{rating}"
                        }
                    }]
                });
                // Save the file and handle any errors that may occur
                oExport.saveFile().catch(function (oError) {
                    sap.m.MessageToast.show("Error when downloading data. Browser might not be supported!\n\n"   oError);
                }).then(function () {
                    // Destroy the export object
                    oExport.destroy();
                });
            },

            downloadPDF:function()
            {
                sap.m.MessageToast.show("Downloading into PDF started !");
                var oModel2 = this.getView().getModel("veg");
                console.log("check data = ", oModel2);

                var oColumns = ["Title","Type","Description","Price","Rating"];

                var oRows = [];
                oRows = oModel2.oData.vegetablesRootNode;
                console.log(oColumns);
                console.log(oRows);

                //var pdfDoc = new jsPDF('p', 'pt', 'letter');
                var pdfDoc = new jsPDF();

                pdfDoc.text(20, 20, "Vegetables Table");
                pdfDoc.autoTable(oRows, oColumns);

                pdfDoc.save("test.pdf");

                //pdfDoc.output("save","t.pdf");
            }

        });
    });

The last function is the code that runs to save the table data into PDF. Can you please help.

These are the files that are included in my project folder.

Manifest.json

Adding just text, and most of the functionality that is available (via methods) from jsPDF works fine. I have created PDFs with just text from this app as well. It works fine for adding text and downloads fine. But for Table data, it doesnt work.

I tried various ways but didn't get to solve it at all.

CodePudding user response:

I tried to make a POC with this library and it works :-)

  1. Configure the framework so that it can load the libraries
sap.ui.loader.config({
    // activate real async loading and module definitions
    async: true,

    // load thirparty from cdn
    paths: {
        "thirdparty/jsPDF": "https://unpkg.com/[email protected]/dist/jspdf.umd.min",
        "thirdparty/jsPDFautoTable": "https://unpkg.com/[email protected]/dist/jspdf.plugin.autotable"
    },

    // provide dependency and export metadata for non-UI5 modules
    shim: {
        
        "thirdparty/jsPDF": {
            amd: true,
            exports: "jspdf"
        },
        "thirdparty/jsPDFautoTable": {
            amd: true,
            exports: "jspdf",
            deps: ["thirdparty/jsPDF"]
        }
    }
});

You can put that code on top on your Component.js file Idea is to configure the framework to load libraries from CDN as AMD module with dependencies.

It's a bit tricky in your case and I'm not sure I understand the mechanism; what I imagine is that autoTable is a jsPDF plugin so we need jsPDF (dependency); the plugin overload jsPDF and returns jsPDF object

For sap.ui.loader here the official doc. : https://sapui5.hana.ondemand.com/sdk/#/api/sap.ui.loader/methods/sap.ui.loader.config

  1. Loads and consumes libraries
sap.ui.require(["thirdparty/jsPDFautoTable"], (jsPDFautoTable) => {
  var doc = new jsPDFautoTable.jsPDF();
  doc.autoTable({ html: '#my-table' });
  doc.save('table.pdf');
});

Either with sap.ui.define or sap.ui.require to load the library on the fly when needed

  • Related