1. 程式人生 > >【Aspose-words】匯出html到word

【Aspose-words】匯出html到word

1、由於Mavenzh中央倉庫中對於com.aspose.words jar包的缺乏,小編本地maven整合下載的 aspose-words-16.4.0-jdk16.jar

2、

package com.xw.ssm.util.word;

import com.alibaba.fastjson.JSONObject;
import com.aspose.words.*;
import com.xw.ssm.util.UUIDUtil;
import com.xw.ssm.util.resultObj.RespMsg;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class WordUtil {

    private static String filePath = "/paper";

    public static JSONObject exportWord(HttpServletRequest request, HttpServletResponse response, String html, String titleName) {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        File filePaper = null;
        try {
            // 判斷資料夾是否存在;不存在則建立
            File file1 = new File(filePath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            File outputFile = null;
            String fileName = UUIDUtil.getUUID() + ".doc";
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            outputFile = new File(filePath + "/" + fileName);
            // 判斷檔案是否存在;不存在則建立
            if (!outputFile.exists()) {
                outputFile.createNewFile();
            }
            // 定義輸出文件
            Document doc = new Document();
            DocumentBuilder docBuilder = new DocumentBuilder(doc);

            // 設定文件屬性
            BuiltInDocumentProperties pro = doc.getBuiltInDocumentProperties();
            pro.setTitle("測試文件");
            pro.setSubject("測試文件");
            pro.setComments("");
            pro.setVersion(1);

            // 裝訂線
            docBuilder.startBookmark("裝訂線");

            docBuilder.endBookmark("裝訂線");

            String paperSize = "A4";
            SectionCollection sections = doc.getSections();
            switch (paperSize) {
//                case "A4H":
//                    for (Section section : sections) {
//                        PageSetup setup = section.getPageSetup();
//                        setup.setPaperSize(PaperSize.A4);
//                        setup.setOrientation(Orientation.LANDSCAPE);
//                        TextColumnCollection column = setup.getTextColumns();
//                        column.setCount(2);
//                        column.setEvenlySpaced(true);
//                        column.setLineBetween(true);
//                        // setup.setLeftMargin(3.35);
//                        // setup.setRightMargin(0.99);
//                    }
//                    break;
                case "A4":
                    for (Section section : sections) {
                        PageSetup setup = section.getPageSetup();
                        setup.setPaperSize(PaperSize.A4);
                        setup.setOrientation(Orientation.PORTRAIT);
                        setup.setVerticalAlignment(PageVerticalAlignment.TOP);
                    }
                    break;

//                case "A3H":
//                    for (Section section : sections) {
//                        PageSetup setup = section.getPageSetup();
//                        setup.setPaperSize(PaperSize.A3);
//                        setup.setOrientation(Orientation.LANDSCAPE);
//                        TextColumnCollection column = setup.getTextColumns();
//                        column.setCount(2);
//                        column.setEvenlySpaced(true);
//                        column.setLineBetween(true);
//                    }
//                    break;
//                case "A3":
//                    for (Section section : sections) {
//                        PageSetup setup = section.getPageSetup();
//                        setup.setPaperSize(PaperSize.A4);
//                        setup.setOrientation(Orientation.PORTRAIT);
//                    }
//                    break;
//                case "KH8":
//                    for (Section section : sections) {
//                        PageSetup setup = section.getPageSetup();
//                        setup.setPageWidth(36.4);
//                        setup.setPageHeight(25.7);
//                        setup.setOrientation(Orientation.LANDSCAPE);
//                        TextColumnCollection column = setup.getTextColumns();
//                        column.setCount(2);
//                        column.setEvenlySpaced(true);
//                        column.setLineBetween(true);
//                        // setup.setLeftMargin(3.35);
//                        // setup.setRightMargin(0.99);
//                    }
//                    break;
//                case "B4":
//                    for (Section section : sections) {
//                        PageSetup setup = section.getPageSetup();
//                        setup.setPaperSize(PaperSize.B4);
//                        setup.setOrientation(Orientation.PORTRAIT);
//                    }
//                    break;
//                case "K16":
//                    for (Section section : sections) {
//                        PageSetup setup = section.getPageSetup();
//                        setup.setPaperSize(PaperSize.B5);
//                        setup.setOrientation(Orientation.PORTRAIT);
//                    }
//                    break;
            }
            // 試卷標題
            docBuilder.getPageSetup().setVerticalAlignment(PageVerticalAlignment.CENTER);
            docBuilder.insertHtml(html);
            outputStream = new FileOutputStream(outputFile);
            doc.save(outputStream, SaveFormat.DOC);
            filePaper = new File(filePath + "/" + fileName);
            if (!filePaper.exists()) {
                return RespMsg.FAIL("檔案生成失敗,請聯絡管理員");
            }
            inputStream = new FileInputStream(filePaper);
            titleName = titleName + ".doc";
            downloadFile(request, response, titleName, inputStream);
            return RespMsg.SUCCESS();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(inputStream);
            if(filePaper != null){
                filePaper.delete();
            }
        }
        return RespMsg.FAIL();
    }


    /**
     * 下載
     *
     * @param request
     * @param response
     * @param filename
     * @param inputStream
     * @throws IOException
     */
    public static void downloadFile(HttpServletRequest request,
                                    HttpServletResponse response,
                                    String filename,
                                    InputStream inputStream) throws IOException {
        OutputStream toClient = null;
        try {
            String userAgent = request.getHeader("USER-AGENT");
            if (StringUtils.contains(userAgent, "MSIE")) {//IE瀏覽器
                filename = URLEncoder.encode(filename, "UTF-8");
            } else if (StringUtils.contains(userAgent, "Mozilla")) {//google,火狐瀏覽器
                filename = new String(filename.getBytes(), "ISO8859-1");
            } else {
                filename = URLEncoder.encode(filename, "UTF-8");//其他瀏覽器
            }
            response.reset();
            // 設定response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Content-Length", "" + inputStream.available());
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");

            // IOUtils.copy(inputStream, toClient);
            byte[] buff = new byte[1024];
            while (true) {
                int read = inputStream.read(buff);
                if (read == -1)
                    break;
                toClient.write(buff, 0, read);
            }
            toClient.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(toClient);
            IOUtils.closeQuietly(inputStream);
        }
    }
}