preface

Two or three years ago, when I first started my internship, the project manager asked me to study the dynamic generation of Word and PDF template files. Recently, I turned them out when I was sorting out my notes

steps

Introduction of depend on

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
Copy the code

Convert word template files to FTL files

Click save as an.xml file

Rename to information table. FTL

Convert FTL files to DOCX files

The following code

import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.*; import java.util.Date; import java.util.HashMap; import java.util.Map; public class DocUtil { private Configuration configuration = null; public DocUtil() { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); } /** ** @param dataMap Input data * @param ftlPath Path where FTL files are stored (excluding the file name) * @param ftlName FTL file name * @param outfile Generated docx file * @throws UnsupportedEncodingException */ public void createDoc(Map<String, Object> dataMap, String outfile, String ftlPath, String ftlName) throws UnsupportedEncodingException {/ / dataMap data to fill in the template files // Set the template device method and path. FreeMarker supports multiple template loading methods. You can reload servlets, classpath, database loads, / / here we template is placed under the template package / / configuration setClassForTemplateLoading (enclosing getClass (), ftlPath); Template template = null; Try {//test.ftl is the template to load // based on the file system. For example, load a template file under /home/user/template. configuration.setDirectoryForTemplateLoading(new File(ftlPath)); template = configuration.getTemplate(ftlName); } catch (IOException e) { e.printStackTrace(); } File outFile = new File(outFile); Writer out = null; FileOutputStream fos = null; try { fos = new FileOutputStream(outFile); OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8"); // This place is indispensable to the encoding of the stream. It should work when called by main () alone, but if exported by web request, the word document will not open and the package XML file will be wrong. The main reason is that the encoding format is not correct and cannot be parsed. //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile))); out = new BufferedWriter(oWriter); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { template.process(dataMap, out); out.close(); fos.close(); } catch (TemplateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws UnsupportedEncodingException { String tmpFilePath = "C:"+ File.separator+"tmp"+File.separator; String ftlPath ="C:"+File.separator+"ftl"+File.separator; Map<String, Object> dataMap = new HashMap<>(); long time = new Date().getTime(); String ftlFile = "FTL "; String outDocFile = tmpFilePath+" info "+time+".docx"; // String outPdfFile = tmpFilePath+" info "+time +".pdf"; // String outPdfFile = tmpFilePath+" info "+time +".pdf"; Datamap. put("name","joahyan"); dataMap.put("birthay","Oct 23th 1995"); DataMap. Put (" sex ", "male"); dataMap.put("age","24"); DocUtil docUtil = new DocUtil(); docUtil.createDoc(dataMap,outDocFile,ftlPath,ftlFile); }}Copy the code

Generated Word file

Word to PDF

public Result downloadEnglishProficiency(@RequestBody AbilityProofDTO abilityProofDTO) throws IOException { AttributeValue attributeValue = attributeValueService.getAttributeByKey("CUHK_OAL_ENGLISH"); String attachmenturl = attributeValueService.getAttributeByKey("UCM_PRE_DOWNLOAD_URL").getPropertyValue(); Date currentDate = new Date(); String birthday = null; SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM yyyy", Locale.ENGLISH); String folderId = attributeValue.getPropertyValue(); Integer apId = Integer.parseInt(abilityProofDTO.getApId()); String itName = null; ApplicationVO applicationVO = null; if (apId ! = null) { applicationVO = applicationService.queryAllDetails(apId); birthday = dateFormat.format(applicationVO.getBirthday()); } else { return ResultUtil.error(); } DocUtil docUtil = new DocUtil(); DocToPdfUtil docToPdfUtil =new DocToPdfUtil(); Map<String, Object> dataMap = new HashMap<>(); // FTL Datamap. put("CurrentDate",dateFormat.format(CurrentDate)); dataMap.put("StudentName",applicationVO.getPinyinName()); dataMap.put("BirthDay",birthday); FileInputStream fileInputStream = null; String outDocFile = tmpFilePath+"Statement of English Language Proficiency"+ CurrentDate.getTime ()+".docx"; String outPdfFile = tmpFilePath+"Statement of English Language Proficiency"+currentDate.getTime()+".pdf"; FileUtils fileUtil = new FileUtils(); File tmpFile = new File(tmpFilePath); File outDoc = new File(outDocFile); File outPdf = new File(outPdfFile); // Delete the last stored files and directories if (! tmpFile.exists()){ tmpFile.mkdir(); } else { fileUtil.deleteDirectory(tmpFilePath); tmpFile.mkdir(); } try { Map<String, String> attrs = new HashMap<String, String>(); Docutil.createdoc (dataMap, outDocFile); / / returns an input stream, the file into the database a fileInputStream. = DocToPdfUtil convertDocxToPDF (outDocFile outPdfFile); String attachmentSize = String.valueOf(fileInputStream.available()); RidcHandler rh = new RidcHandler("sysadmin"); LocalDate nowDate = LocalDate.now(); String yearAndMouth = nowDate.toString().substring(0, 7); String childFolderId = ""; List<ContentEntry> folderList = rh.getFileList(folderId, "FOLDER"); if (null == folderList || folderList.isEmpty()){ childFolderId = rh.createFolder(yearAndMouth, folderId); } else { Optional<ContentEntry> childFolder = folderList.stream().filter( folder -> yearAndMouth.equals(folder.getContentName())).findAny(); if (childFolder.isPresent()){ childFolderId = childFolder.get().getContentId(); } else { childFolderId = rh.createFolder(yearAndMouth, folderId); } } String result = rh.createPublicFile("Statement of English Language Proficiency"+"-"+applicationVO.getStudentId()+"-"+ currentDate.getTime()+".pdf", fileInputStream, childFolderId); CertificateDTO CertificateDTO = new CertificateDTO(); CertificateDTO.setCertificateUrl(attachmenturl + result); CertificateDTO.setCertificateSize(attachmentSize); CertificateDTO.setVoId(abilityProofDTO.getVoId()); int resultValue = applicationService.updateCertificateUrl(CertificateDTO); If (resultValue == 1) {return resultutil. success(" resultutil. success "); } return resultutil. error(" generate English ability proof failed "); } catch (Exception e) { logger.info(e.getMessage()); Return resultutil. error(" conversion failed "); } finally { if (fileInputStream ! = null) { fileInputStream.close(); }}}Copy the code