用JAVA如何实现word文档在线预览

1.思路,利用FTL(freemarker)生成word文档

2.利用免费工具aspose将word转换PDF

3使用PDF.JS在线预览。

第一步比较多,就不一一代码。本次主要讲2,3步

源码如下:AsposeUtil.java,把word转换PDF,存放本地,

1.需要JAR包

百度网盘 请输入提取码 提取码: 630z

2.配置POM.xml


            com.aspose
            aspose-words
            0.0.1-SNAPSHOT
            system
            ${project.basedir}/outlib/aspose-words-16.8.0-jdk16.jar
        

        
            com.aspose
            aspose-cells
            0.0.1-SNAPSHOT
            system
            ${project.basedir}/outlib/aspose-cells-8.5.2(1).jar
        


        
            com.aspose
            aspose-slides
            0.0.1-SNAPSHOT
            system
            ${project.basedir}/outlib/aspose.slides-15.9.0.jar
        
        
        
  		
			cn.hutool
			hutool-core
			5.6.5
		

 3.配置,防止乱码, license.xml代码内容


    
        
            Aspose.Total for Java
            Aspose.Words for Java
        
        Enterprise
        20991231
        20991231
        8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7
    
    
    sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    

4.WORD转PDF源码:

package com.bootdo.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;

public class AsposeUtil {
    /**
     * 获取license
     *
     * @return
     */
    public static boolean getLicense(int type) {
        boolean result = false;
        try {
            InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            if (type == 1) {//excel
                com.aspose.cells.License aposeLic = new com.aspose.cells.License();
                aposeLic.setLicense(is);
                result = true;
            } else if (type == 2) {//word
                com.aspose.words.License aposeLic = new com.aspose.words.License();
                aposeLic.setLicense(is);
                result = true;
            } else {//ppt
                com.aspose.slides.License aposeLic = new com.aspose.slides.License();
                aposeLic.setLicense(is);
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void Excel2Pdf(String officePath,String OutPutPath,String officeName) {
        // 验证License
        if (!getLicense(1)) {
            return;
        }
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
//            long old = Sysout.currentTimeMillis();
            Workbook wb = new Workbook(officePath);// 原始excel路径
            File pdfFile = new File(OutPutPath+officeName);// 输出路径
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            //wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
            wb.save(fileOS, pdfSaveOptions);
//            long now = Sysout.currentTimeMillis();
//            Sysout.println("共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception {
        AsposeUtil bean = new AsposeUtil();
//        bean.word2Pdf2("D:\\pdf\\12.docx","D:\\pdf\\12.pdf");
        bean.word2Pdf2("C:\\wordTemple\\han.docx","C:\\wordTemple\\1234.pdf");
    }
    
    public  void word2Pdf2(String inpath,String outpath) throws Exception {
        if (!getLicense(2)) {
            System.out.println("非法------------");
            return;
        }

        long old = System.currentTimeMillis();
        File file = new File(outpath);

        FileOutputStream os = new FileOutputStream(file);

        //解决乱码
        //如果是windows执行,不需要加这个
        //TODO 如果是linux执行,需要添加这个*****
        //FontSettings.setFontsFolder("/usr/share/fonts",true);

        Document doc = new Document(inpath);

        //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
        doc.save(os, SaveFormat.PDF);

        long now = System.currentTimeMillis();
        System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
    }


    public static void Word2Pdf(String officePath,String OutPutPath,String officeName) {
        // 验证License
        if (!getLicense(2)) {
            return;
        }
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Document doc = new Document(officePath);// 原始word路径
            File pdfFile = new File(OutPutPath+officeName);// 输出路径
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void PPT2Pdf(String officePath,String OutPutPath,String officeName) {
        // 验证License
        if (!getLicense(3)) {
            return;
        }
        try {
            File PathFile = new File(OutPutPath);
            if (!PathFile.exists()) {
                PathFile.mkdirs();
            }
            InputStream slides = new FileInputStream(new File(officePath));// 原始ppt路径
            Presentation pres = new Presentation(slides);
            File file = new File(OutPutPath+officeName);// 输出pdf路径
            FileOutputStream fileOS = new FileOutputStream(file);
            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String OfficeToPdf(String officePath) {

        //G:/product/WebApp/fwis_develop/com/is/flywings/oa/attchfile/1000000000/i0002/101951.docx⌒101951.docx⌒feiyu.docx
        String[] split = officePath.split("⌒");
        int lastIndex = split[0].lastIndexOf(".");
        int lastNameIndex = split[0].lastIndexOf("/");

        String officeType = split[0].substring(lastIndex+1);
        String officeName = split[0].substring(lastNameIndex+1,lastIndex)+".pdf";
        String OutPutPath = split[0].substring(0,lastNameIndex+1)+"office/";

        File file = new File(split[0]);
        File pdfFile = new File(OutPutPath+officeName);
        //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
        if(pdfFile.exists()){
            return OutPutPath+officeName;
        }

        if (file.exists()) {

            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);

            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String MB = df.format(megabytes);
            Double Size = Double.parseDouble(MB);
            if(Size>10){
                return Size+"MB";
            }
            //"doc", "docx", "xls","xlsx", "ppt", "pptx"
            try {
                if(officeType.equals("doc")||officeType.equals("docx")){
                    Word2Pdf(split[0],OutPutPath,officeName);
                }else if(officeType.equals("xls")||officeType.equals("xlsx")){
                    Excel2Pdf(split[0],OutPutPath,officeName);
                }else if(officeType.equals("ppt")||officeType.equals("pptx")){
                    PPT2Pdf(split[0],OutPutPath,officeName);
                }else{
                    System.out.println("无法识别该文件!");
                    return "Error";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return "NotExists";
        }
        return OutPutPath+officeName;
    }

}

      第二步就完成了,接下来下载PDF.js  

  1. pdf.js文件 下载后放入到项目静态文件夹(下载地址:PDF.js)
  2. 可运行的springboot项目

首先为了直观的展示,springboot直接返回一个写死文件路径的输出流

前端获取展示




    
    pdf预览


在线阅读PDF文件

 /mypdf/web/viewer.html是下载的PDF文件包(放在static文件路径下),后面的路径是接口的方法,可通过传id等参数查询生成word

我的方法是:

//生成采集文件文档
	@GetMapping("/api/file/onlinePreview/{id}")
	void   onlinePreview(@PathVariable("id") String id, HttpServletResponse response, HttpServletRequest request,HttpSession session,Model model) throws Exception{
		//生成word文档
		Random rd=new Random();
		String url="docs/xiewai.docx";
		HashMap parm=new HashMap();
		parm.put("id", id);
		List  list=warningRecordService.listXiewai(parm);
		DocumentHandler dh=new DocumentHandler();
	    response.setContentType("text/html;charset=utf-8");
	    request.setCharacterEncoding("UTF-8");
	    String filename = dh.createTaskReportDoc(list,id);
	    model.addAttribute("filename",tem+"files/"+filename);
	    AsposeUtil bean = new AsposeUtil();
//      bean.word2Pdf2("D:\\pdf\\12.docx","D:\\pdf\\12.pdf");
	    String inpath=loadAddress+"\\"+filename;
	    String curr="X"+System.currentTimeMillis()+rd.nextInt(1000);
	    String outPath=loadAddress+"\\"+curr+".pdf";
        bean.word2Pdf2(inpath,outPath);  
        File f = new File(outPath);
        if (f.exists()) {
            byte[] data = null;
            FileInputStream input=null;
            try {
                input= new FileInputStream(f);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常:" + e);
            }finally{
                try {
                    if(input!=null){
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
	}

这样就可以在线预览了

另外附上生成word 表格的代码,填充word的数据

public String createHanReportDoc(List list,String id,String showname) throws Exception {
			// 创建数据
			//Map dataMap = new HashMap();
			//dataMap =getTaskReportData(dataMap, list);
			XieWaiDO dataMap = new XieWaiDO();
			dataMap	=list.get(0);	
			// 获取模板
			String mjinfoJson=dataMap.getXwMjInfo();
			StringBuffer sb=new StringBuffer();
			List mjInfo = new ArrayList();
			if(mjinfoJson!=null&&!mjinfoJson.equals("")){
				JSONArray json=JSONArray.parseArray(mjinfoJson);
				if(json.size()>0){
					  for(int i=0;i

你可能感兴趣的:(JAVA基础,word)