Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this tutorial, we will follow the guideline for developing a plugin to develop our Download PDF Datalist Action plugin. Please also refer to the very first tutorial วิธีการพัฒนา Bean Shell Hash Variable for more details steps.

1. What is the problem?

We require the ability to download form data as a PDF file from the datalist.

2. How to solve the problem?

We will develop a Datalist Action Plugin to display a button to generate a form PDF file. 

3. What is the input needed for your plugin?

To develop a PDF Download Datalist Action plugin, we will consider providing the following as input.

  1. Form ID : The form that will be used to generate the PDF file.
  2. Record ID Column : Use the id of the datalist row or a column value to load the record.
  3. Formatting options : Options to format and customise the PDF output. 

4. What is the output and expected outcome of your plugin?

When the PDF Download Datalist Action is used as a datalist row action or column action, a normal user will see a link to download the PDF file in every row of the datalist. Once the link is clicked, a PDF file will be prompted for downloaded for that specific row.

When the plugin is used for multiple datalist rows (whole list action), a zip file containing all the generated PDFs of every selected rows will be prompted for download when the button is clicked.

5. Are there any resources/API that can be reused?

To develop the PDF Download Datalist Action plugin, we can reuse the methods in FormPdfUtil to generate a form as PDF. We can also refer to the source code of the Datalist Form Data Delete Action plugin as well. Other than that, we can refer to the Export Form Email Tool on what kind of plugin properties options we can provide in the plugin as the Export Form Email Tool are using the methods in FormPdfUtil as well.

6. Prepare your development environment

We need to always have our Joget Workflow Source Code ready and builded by following this guideline

...

Open the maven project with your favourite IDE. I will be using NetBeans.  

7. Just code it!

a. Extending the abstract class of a plugin type

Create a "DownloadPdfDatalistAction" class under "org.joget.tutorial" package. Then, extend the class with org.joget.apps.datalist.model.DataListActionDefault abstract class. Please refer to Datalist Action Plugin.

b. Implement all the abstract methods

As usual, we have to implement all the abstract methods. We will using AppPluginUtil.getMessage method to support i18n and using constant variable MESSAGE_PATH for message resource bundle directory.

...

Code Block
languagejava
    public DataListActionResult executeAction(DataList dataList, String[] rowKeys) {
        // only allow POST
        HttpServletRequest request = WorkflowUtil.getHttpServletRequest();
        if (request != null && !"POST".equalsIgnoreCase(request.getMethod())) {
            return null;
        }
        
        // check for submited rows
        if (rowKeys != null && rowKeys.length > 0) {
            try {
                //get the HTTP Response
                HttpServletResponse response = WorkflowUtil.getHttpServletResponse();
                if (rowKeys.length == 1) {
                    //generate a pdf for download
                    singlePdf(request, response, rowKeys[0]);
                } else {
                    //generate a zip of all pdfs
                    multiplePdfs(request, response, rowKeys);
                }
            } catch (Exception e) {
                LogUtil.error(getClassName(), e, "Fail to generate PDF for " + ArrayUtils.toString(rowKeys));
            }
        }
        
        //return null to do nothing
        return null;
    }
    
    /**
     * Handles for single pdf file
     * @param request
     * @param response
     * @param rowKey
     * @throws IOException 
     * @throws javax.servlet.ServletException 
     */
    protected void singlePdf(HttpServletRequest request, HttpServletResponse response, String rowKey) throws IOException, ServletException {
        byte[] pdf = getPdf(rowKey);
        writeResponse(request, response, pdf, rowKey+".pdf", "application/pdf");
    }
    
    /**
     * Handles for multiple files download. Put all pdfs in zip.
     * @param request
     * @param response
     * @param rowKeys 
     * @throws java.io.IOException 
     * @throws javax.servlet.ServletException 
     */
    protected void multiplePdfs(HttpServletRequest request, HttpServletResponse response, String[] rowKeys) throws IOException, ServletException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(baos);
        
        try {
            //create pdf and put in zip
            for (String id : rowKeys) {
                byte[] pdf = getPdf(id);
                zip.putNextEntry(new ZipEntry(id+".pdf"));
                zip.write(pdf);
                zip.closeEntry();
            }
 
            zip.finish();
            writeResponse(request, response, baos.toByteArray(), getLinkLabel() +".zip", "application/zip");
        } finally {
            baos.close();
            zip.flush();
        }
    }
    
    /**
     * Generate PDF using FormPdfUtil
     * @param id
     * @return 
     */
    protected byte[] getPdf(String id) {
        AppDefinition appDef = AppUtil.getCurrentAppDefinition();
        String formDefId = getPropertyString("formDefId");
 
        Boolean hideEmptyValueField = null;
        if (getPropertyString("hideEmptyValueField").equals("true")) {
            hideEmptyValueField = true;
        }
        Boolean showNotSelectedOptions = null;
        if (getPropertyString("showNotSelectedOptions").equals("true")) {
            showNotSelectedOptions = true;
        }
        Boolean repeatHeader = null;
        if ("true".equals(getPropertyString("repeatHeader"))) {
            repeatHeader = true;
        }
        Boolean repeatFooter = null;
        if ("true".equals(getPropertyString("repeatFooter"))) {    
            repeatFooter = true;
        }
        String css = null;
        if (!getPropertyString("formatting").isEmpty()) {
            css = getPropertyString("formatting");
        }
        String header = null; 
        if (!getPropertyString("headerHtml").isEmpty()) {
            header = getPropertyString("headerHtml");
            header = AppUtil.processHashVariable(header, null, null, null);
        }
        String footer = null; 
        if (!getPropertyString("footerHtml").isEmpty()) {
            footer = getPropertyString("footerHtml");
            footer = AppUtil.processHashVariable(footer, null, null, null);
        }
        
        return FormPdfUtil.createPdf(formDefId, id, appDef, null, hideEmptyValueField, header, footer, css, showNotSelectedOptions, repeatHeader, repeatFooter);
    }
    
    /**
     * Write to response for download
     * @param response
     * @param bytes
     * @param filename
     * @param contentType
     * @throws IOException 
     */
    protected void writeResponse(HttpServletRequest request, HttpServletResponse response, byte[] bytes, String filename, String contentType) throws IOException, ServletException {
        OutputStream out = response.getOutputStream();
        try {
            String name = URLEncoder.encode(filename, "UTF8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename="+name+"; filename*=UTF-8''" + name);
            response.setContentType(contentType+"; charset=UTF-8");
            
            if (bytes.length > 0) {
                response.setContentLength(bytes.length);
                out.write(bytes);
            }
        } finally {
            out.flush();
            out.close();
            
            //simply foward to a 
            request.getRequestDispatcher(filename).forward(request, response);
        }
    }

c. Manage the dependency libraries of your plugin

Our plugin is using javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse class, so we will need to add jsp-api library to our POM file.

Code Block
languagexml
<!-- Change plugin specific dependencies here -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
</dependency>
<!-- End change plugin specific dependencies here -->

d. Make your plugin internationalization (i18n) ready

We are using i18n message key in getLabel and getDescription method. We will use i18n message key in our properties options definition as well. Then, we will need to create a message resource bundle properties file for our plugin.

...

Code Block
org.joget.tutorial.DownloadPdfDatalistAction.pluginLabel=Download PDF
org.joget.tutorial.DownloadPdfDatalistAction.pluginDesc=Support to download form PDF from datalist
datalist.downloadPdf.download=Download
datalist.downloadPdf.config=Configure Download PDF Action
datalist.downloadPdf.label=Label
datalist.downloadPdf.form=Form
datalist.downloadPdf.recordIdColumn=Record Id Column
datalist.downloadPdf.recordIdColumn.desc=Default to the primary key of the configured binder
datalist.downloadPdf.confirmationMessage=Confirmation Message
datalist.downloadPdf.hideEmptyValueField=Hide field that without value
datalist.downloadPdf.showNotSelectedOptions=Show unselected options for multi options field
datalist.downloadPdf.advanced=Advanced
datalist.downloadPdf.formatting=Formatting (CSS)
datalist.downloadPdf.headerHtml=Header (HTML)
datalist.downloadPdf.repeatHeader=Repeat header on every page?
datalist.downloadPdf.footerHtml=Footer (HTML)
datalist.downloadPdf.repeatFooter=Repeat footer on every page?

e. Register your plugin to the Felix Framework

Next, we will have to register our plugin class in the Activator class (Auto generated in the same class package) to tell the Felix Framework that this is a plugin.

Code Block
languagejava
    public void start(BundleContext context) {
        registrationList = new ArrayList<ServiceRegistration>();
        //Register plugin here
        registrationList.add(context.registerService(DownloadPdfDatalistAction.class.getName(), new DownloadPdfDatalistAction(), null));
    }

f. Build it and test

Let's build our plugin. Once the building process is done, we will find a "download_pdf_datalist_action-5.0.0.jar" file created under "download_pdf_datalist_action/target" directory.

...

When the whole list action is clicked, a zip file is downloaded.

8. Take a step further, share it or sell it

You can download the source code from download_pdf_datalist_action.zip.

...