用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

<dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/outlib/aspose-words-16.8.0-jdk16.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/outlib/aspose-cells-8.5.2(1).jar</systemPath>
        </dependency>


        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-slides</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/outlib/aspose.slides-15.9.0.jar</systemPath>
        </dependency>
        
        
  		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-core</artifactId>
			<version>5.6.5</version>
		</dependency>

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

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
    sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>

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直接返回一个写死文件路径的输出流

前端获取展示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>pdf预览</title>
</head>
<body>
<h1 onclick="onLineReadPDF()" style="cursor: pointer;color:blue">在线阅读PDF文件</h1>

<script>
    function onLineReadPDF() {
       	var id=$("#id").val();
	var addPage =layer.open({
		type : 2,
		title : '预览',
		maxmin : true,
		shadeClose : false, // 点击遮罩关闭层
		area : [ '600px', '460px' ],
		content : '/mypdf/web/viewer.html?file=/xiewai/api/file/onlinePreview/'+id 
		//content : prefix + '/api/file/onlinePreview/'+id // iframe的url
	});
	 layer.full(addPage);
    }
</script>
</body>
</html>

 /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<String, Object> parm=new HashMap<String, Object>();
		parm.put("id", id);
		List<XieWaiDO>  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<XieWaiDO> list,String id,String showname) throws Exception {
			// 创建数据
			//Map<String, Object> dataMap = new HashMap<String, Object>();
			//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<json.size();i++){
						Map map = new HashMap();
					    JSONObject job =json.getJSONObject(i);  //
					    String name=(String) job.get("name");
					    if(i!=0&&i!=job.size()-1){
					    	sb.append("、");
					    }
					    sb.append(name);
					  }
				}
			dataMap.setXwMjInfo(sb.toString());
			}
			Date now=new Date();
			String nowDate=sdf2.format(now);
			dataMap.setReceiveTime(nowDate);
			dataMap.setRemarks(showname);
			
			
			Configuration configuration = new Configuration();
			configuration.setDefaultEncoding("utf-8");
			configuration.setDirectoryForTemplateLoading(new File(loadAddress));
			System.out.println(this.getClass().getResource(""));
			Template t = null;
			String tem=sdf3.format(new Date());
			String tt=id+""+tem;
			String name = "\\han_"+tt+".docx";
			String ftl="han.ftl";
			File file = new File(loadAddress + name);
			try {
				t = configuration.getTemplate(ftl);
				t.setEncoding("UTF-8");
				Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(loadAddress + name), "UTF-8"));
				t.process(dataMap, out);
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TemplateException e) {
				e.printStackTrace();
			}
			return name;
		}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值