Java freemarker生成word模板文件(如合同文件)及轉pdf文件方法
創建模板文件
ContractTemplate.docx
ContractTemplate.xml
導入的Jar包
compile("junit:junit")
compile("org.springframework:spring-test")
compile("org.springframework.boot:spring-boot-test")
testCompile 'org.springframework.boot:spring-boot-starter-test'
compile 'org.freemarker:freemarker:2.3.28'
compile 'fakepath:aspose-words:19.5jdk'
compile 'fakepath:aspose-cells:8.5.2'
Java工具類 xml文檔 轉換 Word XmlToDocx.java
package com.test.docxml.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; /** * xml文檔 轉換 Word */ public class XmlToDocx { /** * * @param documentFile 動態生成數據的docunment.xml文件 * @param docxTemplate docx的模板 * @param toFilePath 需要導出的文件路徑 * @throws Exception */ public static void outDocx(File documentFile, String docxTemplate, String toFilePath,String key) throws Exception { try { File docxFile = new File(docxTemplate); ZipFile zipFile = new ZipFile(docxFile); Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries(); FileOutputStream fileOutputStream = new FileOutputStream(toFilePath); ZipOutputStream zipout = new ZipOutputStream(fileOutputStream); int len = -1; byte[] buffer = new byte[1024]; while (zipEntrys.hasMoreElements()) { ZipEntry next = zipEntrys.nextElement(); InputStream is = zipFile.getInputStream(next); // 把輸入流的文件傳到輸出流中 如果是word/document.xml由我們輸入 zipout.putNextEntry(new ZipEntry(next.toString())); if ("word/document.xml".equals(next.toString())) { InputStream in = new FileInputStream(documentFile); while ((len = in.read(buffer)) != -1) { zipout.write(buffer, 0, len); } in.close(); } else { while ((len = is.read(buffer)) != -1) { zipout.write(buffer, 0, len); } is.close(); } } zipout.close(); } catch (Exception e) { e.printStackTrace(); } } }
Java工具類 word文檔 轉換 PDF WordToPdf.java
package com.test.docxml.utils; import com.aspose.cells.*; import com.aspose.cells.License; import com.aspose.words.*; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; /** * word文檔 轉換 PDF */ public class WordToPdf { /** * 獲取license許可憑證 * @return */ private static boolean getLicense() { boolean result = false; try { String licenseStr = "<License>\n" + " <Data>\n" + " <Products>\n" + " <Product>Aspose.Total for Java</Product>\n" + " <Product>Aspose.Words for Java</Product>\n" + " </Products>\n" + " <EditionType>Enterprise</EditionType>\n" + " <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" + " <LicenseExpiry>20991231</LicenseExpiry>\n" + " <SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\n" + " </Data>\n" + " <Signature>0nRuwNEddXwLfXB7pw66G71MS93gW8mNzJ7vuh3Sf4VAEOBfpxtHLCotymv1PoeukxYe31K441Ivq0Pkvx1yZZG4O1KCv3Omdbs7uqzUB4xXHlOub4VsTODzDJ5MWHqlRCB1HHcGjlyT2sVGiovLt0Grvqw5+QXBuinoBY0suX0=</Signature>\n" + "</License>"; InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8")); License asposeLic = new License(); asposeLic.setLicense(license); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * word文檔 轉換為 PDF * @param inPath 源文件 * @param outPath 目標文件 */ public static File doc2pdf(String inPath, String outPath) { //驗證License,獲取許可憑證 if (!getLicense()) { return null; } //新建一個PDF文檔 File file = new File(outPath); try { //新建一個IO輸出流 FileOutputStream os = new FileOutputStream(file); //獲取將要被轉化的word文檔 Document doc = new Document(inPath); // 全面支持DOC, DOCX,OOXML, RTF HTML,OpenDocument,PDF, EPUB, XPS,SWF 相互轉換 doc.save(os, com.aspose.words.SaveFormat.PDF); os.close(); } catch (Exception e) { e.printStackTrace(); } return file; } public static void main(String[] args) { doc2pdf("D:/1.doc", "D:/1.pdf"); } }
Java單元測試類 XmlDocTest.java
package com.test.docxml; import com.test.docxml.utils.WordToPdf; import com.test.docxml.utils.XmlToDocx; import freemarker.template.Configuration; import freemarker.template.Template; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import java.io.File; import java.io.PrintWriter; import java.io.Writer; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * 本地單元測試 */ @RunWith(SpringJUnit4ClassRunner.class) //@RunWith(SpringRunner.class) @SpringBootTest(classes= TemplateApplication.class) @WebAppConfiguration public class XmlDocTest { //短租 @Test public void testContract() throws Exception{ String contractNo = "1255445544"; String contractCorp = "銀河宇宙無敵測試soft"; String contractDate = "2022-01-27"; String contractItem = "房地產交易中心"; String contractContent = "穩定發展中的文案1萬字"; //doc xml模板文件 String docXml = "ContractTemplate.xml"; //使用替換內容 //xml中間臨時文件 String xmlTemp = "tmp-ContractTemplate.xml"; //生成文件的doc文件 String toFilePath = contractNo + ".docx"; //模板文檔 String docx = "ContractTemplate.docx"; //生成pdf文件 String toPdfFilePath = contractNo + ".pdf";; String CONTRACT_ROOT_URL = "/template"; Resource contractNormalPath = new ClassPathResource(CONTRACT_ROOT_URL + File.separator + docXml); String docTemplate = contractNormalPath.getURI().getPath().replace(docXml, docx); //設置文件編碼(注意點1) Writer writer = new PrintWriter(new File(xmlTemp),"UTF-8"); Configuration configuration = new Configuration(Configuration.VERSION_2_3_28); configuration.setEncoding(Locale.CHINESE, Charset.forName("UTF-8").name()); //設置配置(注意點3) configuration.setDefaultEncoding("UTF-8"); String filenametest = contractNormalPath.getURI().getPath().replace(docXml, ""); System.out.println("filenametest=" + filenametest); configuration.setDirectoryForTemplateLoading(new File(filenametest)); // Template template = configuration.getTemplate(ContractConstants.CONTRACT_NORMAL_URL+orderType+type+".xml"); //設置模板編碼(注意點2) Template template = configuration.getTemplate(docXml,"UTF-8"); //絕對地址 Map paramsMap = new HashMap(); paramsMap.put("contractCorp",contractCorp); paramsMap.put("contractDate",contractDate); paramsMap.put("contractNo",contractNo); paramsMap.put("contractItem",contractItem); paramsMap.put("contractContent",contractContent); template.process(paramsMap, writer); XmlToDocx.outDocx(new File(xmlTemp), docTemplate, toFilePath, null); System.out.println("do finish"); //轉成pdf WordToPdf.doc2pdf(toFilePath,toPdfFilePath); } }
創建成功之后的文件如下: