java中生成word文档,并转换成pdf文件

生成word文档

使用freemarker,通过xml模板生成word文档.

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.net.ConnectException;
import java.util.Map;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

public class WordUtil {

	/**
	 * 将xml模板转换为后缀为doc文件,本质仍是属于xml
	 * @param dataMap	需要填充到模板的数据
	 * @param templetFilePath	模板文件路径
	 * @param targetFilePath	目标文件保存路径
	 */
	public static String xml2XmlDoc(Map<String,Object> dataMap, String templetFilePath, String targetFilePath) throws IOException, TemplateException {
		// 将模板文件路径拆分为文件夹路径和文件名称
		String tempLetDir = templetFilePath.substring(0,templetFilePath.lastIndexOf("/"));
		// 注意:templetFilePath.lastIndexOf("/")中,有的文件分隔符为:\ 要注意文件路径的分隔符
		String templetName = templetFilePath.substring(templetFilePath.lastIndexOf("/")+1);
		// 将目标文件保存路径拆分为文件夹路径和文件名称
		String targetDir = targetFilePath.substring(0,targetFilePath.lastIndexOf("/"));
		String targetName = targetFilePath.substring(targetFilePath.lastIndexOf("/")+1);
		@SuppressWarnings("deprecation")
		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("UTF-8");
		// 如果目标文件目录不存在,则需要创建
		File file = new File(targetDir);
		if(!file.exists()){			file.mkdirs();
		}
		// 加载模板数据(从文件路径中获取文件,其他方式,可百度查找)
		configuration.setDirectoryForTemplateLoading(new File(tempLetDir));
		// 获取模板实例
		Template template = configuration.getTemplate(templetName);
		File outFile = new File(targetDir + File.separator + targetName);
		//将模板和数据模型合并生成文件
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
		//生成文件
		template.process(dataMap, out);
		out.flush();
		out.close();
		String pdfFile = targetFilePath.substring(0,targetFilePath.lastIndexOf(".")) + ".pdf";
		/*boolean officeOpenPDF = officeOpenPDF(targetFilePath,pdfFile);
		if(!officeOpenPDF){
			return "";
		}*/
		Doc2Pdf.doc2pdf(targetFilePath,pdfFile);
		return pdfFile;
	}
	
	
	/**
	 * 通过oppenOffice进行转换
	 * @param inputFile  需要转的文件路径
	 * @param pdfFile    生成后的pdf文件路径
	 * @author hkl
	 * @date 2020年3月31日 下午5:12:15
	 */
	public static boolean officeOpenPDF(String inputFile, String pdfFile) {
		OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
		File inputFiles = new File(inputFile);
		File outputFile = new File(pdfFile);
		try {
			connection.connect();
			//DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
			DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
			converter.convert(inputFiles, outputFile);
			connection.disconnect();
			//删除原文件
			//inputFiles.delete();
		} catch (ConnectException e) {
			e.printStackTrace();
			return false;
		}finally {
			if(connection!=null){
				connection.disconnect();
				connection = null;
			}
		}
		return true;
	}
}

word文档转换pdf文件

方法挺多,比如jacob调用office组件完成转换, 使用openoffice, 使用conver for java
这里使用最后一种
需引用jar包 链接: aspose-words-15.8.0-jdk16.jar.       提取码: hn8s
license.xm文件l 链接: license.xml.      提取码: 4jsm

import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.aspose.words.*;
import org.nky.framework.config.MyConfig;

public class Doc2Pdf {

    public static void main(String[] args) {
        doc2pdf("D:/桌面/conver/sellPlan.docx","D:/桌面/conver/sellPlan.pdf");
    }

    public static boolean getLicense() {
        boolean result = false;
        try {
            File file = new File(MyConfig.filePath+"/license.xml"); // 新建一个空白pdf文档
            InputStream is = new FileInputStream(file); // license.xml找个路径放即可。
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void doc2pdf(String inPath, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            os.close();

            File docxFile = new File(inPath);
            docxFile.delete();

            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  1. jacob调用office组件word转换pdf
    完整demo 下载.      提取码: icj3
    在这里插入图片描述
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值