最近做的功能要求是Java 调用ftl模板生成Word文件,再将Word文件转为PDF
1、首先是ftl模板生成Word文件。Java 利用ftl模板生成Word用的技术是freemarker,相关技术可以网上自查。
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class DocumentHandler {
private Configuration configuration = null;
public DocumentHandler() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
/**
* @author
* @desc 根据类别和类型导出相应
* @param dataMap
* type
* @return pd
* @throws IOException
* @throws Exception
*/
public File createDoc(Map<String,Object> dataMap,int lb) throws IOException {
configuration.setClassForTemplateLoading(this.getClass(), "/ftl/template/");
String fileName = "temp"+(int)(Math.random()*1000)+".doc";
Template t=null;
try {
//test.ftl为要装载的模板
t = configuration.getTemplate("test.ftl");
} catch (IOException e) {
e.printStackTrace();
}
//输出文档路径及名称
File outFile = new File(fileName);
try {
Writer w = new OutputStreamWriter(new FileOutputStream(outFile), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception e1) {
e1.printStackTrace();
}
return outFile;
}
2、Word转为PDF。将Word转为PDF 用到的是aspose.works
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
public static void main(String[] args) {
License aposeLic = new License();
try {
// Map<String,Object> map = setMap();
// DocumentHandler documentHandler = new DocumentHandler();
// File file = documentHandler.createWorkflowDoc(map,5);
//破解aspose,以防PDF文件添加水印
InputStream license = Test.class.getClassLoader().getResourceAsStream("license.xml");
aposeLic.setLicense(license);
String in = "E:\\xxx\\aaa.doc";
File file = new File(in);
InputStream fin = new FileInputStream(file);
long old = System.currentTimeMillis();
Document doc = new Document(fin);
String test = "E:\\2019work\\ceshi.pdf";
File outputFile = new File(test);
FileOutputStream fileOS = new FileOutputStream(outputFile);
doc.save(fileOS, SaveFormat.PDF);
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + outputFile.getPath());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}