Java–Aspose.word–freemarker templated export of word documents

Java uses Aspose.word to export word individually or in batches

 During the development process, most of us will import and export some data, of which excel tables account for a large proportion, followed by some word exports. However, the word export process may involve some word typesetting. We hope that the exported word can be forward and backward. There are format settings left and right. For example, exporting a resume requires formatting, so templated export is available.

Introduction to Aspose

Aspose has many functions and supports different programming languages. It has a dedicated website. If you are interested, you can visit Baidu. The link is: https://docs.aspose.com. In the application, the first step is to introduce relevant dependencies and configure them. With this, we can export the rendered page in the form of word.

Freemarker introduction

Freemarker is a template engine that can be used to create front-end pages in the early days when the front-end and back-end are not separated. It mainly defines the page layout, fills it in with data generated by the backend, and then renders it to present it.

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>

Export steps and process

First we create a new export interface, as follows:

@PostMapping("/export")
public void export(HttpServletResponse response, @RequestBody ExportParam param) {<!-- -->
    exportService.export(response, param);
}

Create a new exported interface and implementation

@Override
    public void export(HttpServletResponse response, ExportParam param) {<!-- -->
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ServletOutputStream servletOutputStream = response.getOutputStream()) {<!-- -->
            //Create a Configuration object and create a new object directly. The parameter of the construction method is the version number of freemarker.
            Configuration configuration = new Configuration(Configuration.getVersion());
            //Set the path where the template file is located (usually placed in the subdirectory under resources)
            configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/template/"));
            // Set the character set used by the template file to be the same as the charset in the template, otherwise the characters will be garbled.
            configuration.setDefaultEncoding("utf-8");
            //Load a template and create a template object.
            Template template = configuration.getTemplate("/jianli.ftl");
            //Create a data set used by the template, which can be a pojo or a map. Usually Map.
            Map<String, Object> dataModel = new HashMap<>();
            
            ....
            //todo adds data to the data set, queries the relevant data based on the input parameters, and puts it into the dataModel.
            // dataModel.put("data", query data);
....
            
            //Create a Writer object, generally create a FileWriter object and specify the generated file name.
            Writer out = new StringWriter();
            //Call the process method of the template object to output the file.
            template.process(dataModel, out);
            // Close the stream.
            Document document = new Document();
            DocumentBuilder builder = new DocumentBuilder(document);
            builder.insertHtml(out.toString());
            document.save(outputStream, SaveFormat.DOCX);
            // Return the document as a response to the front end
            byte[] documentBytes = outputStream.toByteArray();
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=d.docx");
            response.setContentLength(documentBytes.length);
            servletOutputStream.write(documentBytes);
        } catch (Exception e) {<!-- -->
            log.error("Export exception", e);
            throw new Exception("Export exception!");
        }
    }

This is the code required for the entire export process. However, when exporting, you will find that your document is watermarked. Searching the Internet, there are some examples of cracking. If you need it, you can learn about it yourself and leave a private message. It will not be shown here. . At this point, the Java code module is over. The more detailed point is the writing of freemarker. The writing of this template may require the help of front-end students to beautify the page with styles. Here are some examples of how to use freemarker. Of course, you can refer to it on Baidu yourself.

<#assign alphabetMap = ['1', '2', 'C']> #Define a set
<#assign object = {'1':'A', '2':'b', 'C':'r'}> #Define object
<#assign single= 222> #Define a single value
${data.field} #Get the field field value in the data passed in the background
<#list items as item> #Loop items collection
<#if item.type=="1"> #Determine the type field value of item
·····
<#elseif item.type=='2'>
····
<#else>
·····
</#if>
${item_index} #Get the index of the collection where the current item is located
<#assign options = item.experience?eval_json /> #Format the experience string json in the item
</#list>
The following is part of the resume jianli.ftl:
<body class='typora-export os-windows'>
<div class='typora-export-content'>
<div id='write' class=''>
<p>
<span> </span>
<span>Resume</span>
\t\t\t</p>
<p>
<span>Name: ${data.name}</span>
\t\t\t</p>
<p>
<span>Experience:</span>
\t\t\t</p>
<#assign items= data.experience?eval_json />
<#list items as item>
<p>
<span>${item_index + 1}.${item.projectName}</span>
<span>${item.projectDes}</span>
\t\t\t\t</p>
</#list>
</div>
</div>
</body>

Batch export, add multiple word documents into a compressed package and export them together

@Override
    public void exportAllExamContent(HttpServletResponse response, List<ExportParam> params) {<!-- -->
        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {<!-- -->
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=a.zip");
            //Query the list to be exported
            for (ExportParam param : params) {<!-- -->
                //todo business data query data
                outputStream.reset();
                byte[] documentBytes = getBytes(data, outputStream);//Here you can combine the single export method to convert the data into a byte array, and then write it to ZipOutputStream
                zos.putNextEntry(new ZipEntry(param.getName() + ".docx"));
                zos.write(documentBytes);
                zos.closeEntry();
            }
        } catch (Exception e) {<!-- -->
            log.error("Batch export exception", e);
            throw new Exception("Export exception!");
        }
    }

Summary

The entire export process is to use html to write a formatted word page. The html will be written in whatever word document we need, and then use freemarker to transfer the parts that need to be changed according to the background data through the freemarker syntax through the background. The value is dynamically obtained, loaded and rendered, and finally Aspose.word is used to convert and export the html to word.