Java web 線上預覽--參考二__html5

來源:互聯網
上載者:User

http://blog.csdn.net/qq_28533563/article/details/72676425

這位博主提供2種思路,

主要實現方式就是 (openoffice+swftools+flexpaper)和(aspose+pdfjs預覽)。

第一種就是上一篇文章的實現,第二種便是這位博主的主要實現


備份原文:

Java實現線上預覽附件 office轉換PDF

因為項目是做OA這一塊,有很多附件需要實現線上預覽附件,在網上也看了很多相關的資料。主要實現方式就是 (openoffice+swftools+flexpaper)和(aspose+pdfjs預覽)。

主要步驟:
1.需要先將文檔轉換為PDF檔案。
2.用pdfjs預覽PDF檔案

轉換步驟:
* 使用OpenOffice/Aspose 將ppt、word、excel、txt類型的檔案轉換為pdf

預覽步驟:
* 高版本瀏覽器上,使用pdf.js直接預覽PDF檔案
* 低版本瀏覽器上,使用swftools將PDF檔案轉換為swf檔案,再使用flexpaper預覽swf(沒有做這個步驟)

組件安裝:
Aspose
由於OpenOffice的轉換效果並不太佳,這裡選擇了Aspose
在Aspose官網下載Aspose的Java版本,主要選擇
* Aspose.words
* Aspose.cells(Excel)
* Aspose.slides(PPT)
* Aspose.pdf
下載完成後,在工程中引用jar包即可。

功能實現:
這裡採用的所有組件版本為:
名稱 版本
Aspose.words 16.8.0
Aspose.cells 9.0.0
Aspose.slides 116.7.0
Aspose.pdf 11.8.0
文檔轉換為PDF

使用Aspose進行文檔轉換很簡單,直接引入相應的jar包,調用save方法,轉換為PDF即可。

注意:
1. 使用Aspose時,每一個模組(words,cells)都可能有相同的類,如License類,SaveOptions類,SaveFormat類。而在各自模組使用時,一定要用對應模組的類,這個坑我已爬過。
使用Aspose時,需要每次進行轉換操作前調用設定License方法。

package com.ybg.pf.oamodule.work.module.convert.util;import org.apache.log4j.Logger;import java.io.FileInputStream;import java.io.InputStream;/** * Aspose註冊工具 * * @author zhumin * @version 1.0.0 *          2017年05月16日 15:58 * @since Jdk1.7 */public class AsposeLicenseUtil {    private static InputStream inputStream = null;    private static Logger logger = Logger.getLogger(AsposeLicenseUtil.class);    /**     * 擷取License的輸入資料流     *     * @return     */    private static InputStream getLicenseInput() {        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();        try {            String path = contextClassLoader.getResource("license.xml").toURI().getPath();            inputStream = new FileInputStream(path);        } catch (Exception e) {            logger.error("license not found!", e);        }        return inputStream;    }    /**     * 設定License     *     * @return true表示已成功設定License, false表示失敗     */    public static boolean setWordsLicense() {        InputStream licenseInput = getLicenseInput();        if (licenseInput != null) {            try {                com.aspose.words.License aposeLic = new com.aspose.words.License();                aposeLic.setLicense(licenseInput);                return aposeLic.getIsLicensed();            } catch (Exception e) {                logger.error("set words license error!", e);            }        }        return false;    }    /**     * 設定License     *     * @return true表示已成功設定License, false表示失敗     */    public static boolean setCellsLicense() {        InputStream licenseInput = getLicenseInput();        if (licenseInput != null) {            try {                com.aspose.cells.License aposeLic = new com.aspose.cells.License();                aposeLic.setLicense(licenseInput);                return true;            } catch (Exception e) {                logger.error("set cells license error!", e);            }        }        return false;    }    /**     * 設定License     *     * @return true表示已成功設定License, false表示失敗     */    public static boolean setSlidesLicense() {        InputStream licenseInput = getLicenseInput();        if (licenseInput != null) {            try {                com.aspose.slides.License aposeLic = new com.aspose.slides.License();                aposeLic.setLicense(licenseInput);                return aposeLic.isLicensed();            } catch (Exception e) {                logger.error("set ppt license error!", e);            }        }        return false;    }    /**     * 設定Aspose PDF的license     * @return true表示設定成功,false表示設定失敗     */    public static boolean setPdfLicense() {        InputStream licenseInput = getLicenseInput();        if (licenseInput != null) {            try {                com.aspose.pdf.License aposeLic = new com.aspose.pdf.License();                aposeLic.setLicense(licenseInput);                return true;            } catch (Exception e) {                logger.error("set pdf license error!", e);            }        }        return false;    }}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

word文檔轉碼執行個體:

package com.ybg.pf.oamodule.work.module.convert.service.impl;import com.aspose.words.Document;import com.aspose.words.PdfSaveOptions;import com.aspose.words.SaveFormat;import com.ybg.pf.oamodule.work.module.convert.domain.ConvertStatus;import com.ybg.pf.oamodule.work.module.convert.service.File2PdfService;import com.ybg.pf.oamodule.work.module.convert.util.AsposeLicenseUtil;import org.apache.log4j.Logger;import java.io.InputStream;import java.io.OutputStream;/** * 將doc文檔轉換為pdf檔案 * * @author zhumin * @version 1.0.0 *          2017年05月16日 15:58 * @since Jdk1.7 */public class Doc2PdfServiceImpl implements File2PdfService {    private Logger logger = Logger.getLogger(getClass());    @Override    public ConvertStatus convert2Pdf(InputStream inputStream, OutputStream outputStream) {        try {            if (AsposeLicenseUtil.setWordsLicense()) {                Document doc = new Document(inputStream);//                insertWatermarkText(doc, "浮水印浮水印"); // 添加浮水印                PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();                pdfSaveOptions.setSaveFormat(SaveFormat.PDF);                pdfSaveOptions.getOutlineOptions().setHeadingsOutlineLevels(3); // 設定3級doc書籤需要儲存到pdf的heading中                pdfSaveOptions.getOutlineOptions().setExpandedOutlineLevels(1); // 設定pdf中預設展開1級                doc.save(outputStream, pdfSaveOptions);                inputStream.close();                outputStream.flush();                outputStream.close();                return ConvertStatus.SUCCESS;            } else {                return ConvertStatus.LICENSE_ERROR;            }        } catch (Exception e) {            return ConvertStatus.CONVERT_DOC2PDF_ERROR;        }    }}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

其他格式就不附下面會提供代碼下載。

預覽流程:先在後台下載附件到項目指定臨時目錄,在讀取下載檔案轉換為PDF儲存到臨時目錄


這是目錄結構:convertFile附件下載存放目錄 outputFilePDF儲存目錄

package com.ybg.pf.oamodule.common.util;import com.ybg.pf.framework.library.util.FileRWUtils;import com.ybg.pf.framework.library.util.LogUtil;import com.ybg.pf.oamodule.work.module.convert.domain.ConvertStatus;import com.ybg.pf.oamodule.work.module.convert.service.File2PdfService;import com.ybg.pf.oamodule.work.module.convert.service.impl.Doc2PdfServiceImpl;import com.ybg.pf.oamodule.work.module.convert.service.impl.Excel2PdfServiceImpl;import com.ybg.pf.oamodule.work.module.convert.service.impl.PPT2PdfServiceImpl;import org.apache.commons.lang.StringUtils;import java.io.*;import java.net.HttpURLConnection;import java.net.URL;/** * Created by Administrator on 2017/5/11. * 線上預覽工具類 * 檔案下載工具 */public class PreviewUtils {    //轉換服務    private static File2PdfService fileConvertService;    /**     * office轉換PDF     * @param fileName 需要轉換的檔案名稱     * @return     * @throws Exception     */    public static ConvertStatus officeConversionPDF(String fileName) throws Exception{        //擷取檔案尾碼        String suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());        String fileNames = fileName.substring(0,fileName.lastIndexOf("."));        //根據尾碼判斷檔案類型執行個體化對應服務層        if (StringUtils.equalsIgnoreCase(suffix,"docx") || StringUtils.equalsIgnoreCase(suffix,"doc")){            fileConvertService = new Doc2PdfServiceImpl();        }else if (StringUtils.equalsIgnoreCase(suffix,"pptx") || StringUtils.equalsIgnoreCase(suffix,"ppt")){            fileConvertService = new PPT2PdfServiceImpl();        }else if (StringUtils.equalsIgnoreCase(suffix,"xlsx") || StringUtils.equalsIgnoreCase(suffix,"xls")){            fileConvertService = new Excel2PdfServiceImpl();        }        ConvertStatus convertStatus = null;        //擷取需要轉換文檔的所在路徑        File officeFile = new File(savePath()+File.separator+fileName);        File outputFile = new File(outPDFPath(fileNames) +File.separator+ fileNames+".pdf");//PDF儲存檔案路徑        //如果檔案是 PDF 不用轉換直接複製到指定目錄        if (StringUtils.equalsIgnoreCase(suffix,"pdf")){            FileRWUtils.copyFile(officeFile.getPath(),outPDFPath(fileNames));            return convertStatus;        }        if (!outputFile.exists()){            InputStream inputStream = new FileInputStream(officeFile);            OutputStream outputStream = new FileOutputStream(outputFile);            //開始轉換            convertStatus = fileConvertService.convert2Pdf(inputStream, outputStream);        }        return convertStatus;    }    /**     * 根據PDF檔案名稱擷取PDF儲存地址     * @param fileName PDF檔案名稱     * @return     *  沒有加.toURI() 有可能中文路徑會亂碼 加上擷取會出錯     */    public static String outPDFPath(String fileName) throws Exception{        String pathName = PreviewUtils.class.getClassLoader().getResource("").getPath();        //檔案儲存位置 如果檔案夾不存在建立檔案夾        File saveDir = new File(pathName+File.separator+"outputFile");        if(!saveDir.exists()){            saveDir.mkdir();        }        return saveDir.getPath();    }    /**     * 擷取檔案儲存路徑     * @return     */    public static String savePath(){        String pathName = PreviewUtils.class.getClassLoader().getResource("").getPath();        //檔案儲存位置 如果檔案夾不存在建立檔案夾        File saveDir = new File(pathName+File.separator+"convertFile");        if(!saveDir.exists()){            saveDir.mkdir();        }        return saveDir.getPath();    }    /**     * 從網路Url中下載檔案     * @param urlStr 下載地址     * @param fileName 檔案名稱     * @param savePath  儲存地址     * @throws IOException     */    public static boolean  downLoadFromUrl(String urlStr,String fileName,String savePath){        File file = new File(savePath+File.separator+fileName);        //檔案是否已存在        if(file.exists()){            return true;        }        try {            URL url = new URL(urlStr);            HttpURLConnection conn = (HttpURLConnection)url.openConnection();            //設定逾時間為30秒            conn.setConnectTimeout(30*1000);            //防止屏蔽程式抓取而返回403錯誤            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");            //得到輸入資料流            InputStream inputStream = conn.getInputStream();            //擷取自己數組            byte[] getData = readInputStream(inputStream);            FileOutputStream fos = new FileOutputStream(file);            if (getData == null){                return false;            }            fos.write(getData);            if(fos!=null){                fos.close();            }            if(inputStream!=null){                inputStream.close();            }            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){                return true;            }        } catch (IOException e) {            LogUtil.error("附件下載轉換PDF出錯!",e);        }        return false;    }    /**     * 從輸入資料流中擷取位元組數組     * @param inputStream     * @return     * @throws IOException     */    public static  byte[] readInputStream(InputStream inputStream) throws IOException {        byte[] buffer = new byte[1024];        int len = 0;        ByteArrayOutputStream bos = new ByteArrayOutputStream();        while((len = inputStream.read(buffer)) != -1) {            bos.write(buffer, 0, len);        }        bos.close();        return bos.toByteArray();    }}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

由於我們要整合到自己的工程中來,所以此處直接copy了viewer.html頁面,修改為了我們工程需要的view_pdfjs.jsp ,其中做了一些修改刪除了部分不需要的功能
下面是我修改過後的預覽頁面 效果圖:

<%@ page import="com.ybg.pf.oamodule.common.constant.JspCommonConstant" %><%@ page contentType="text/html;charset=UTF-8" language="java" %><%    String qiyehaoProjectpath = JspCommonConstant.getProjectBasePath();%><!DOCTYPE html><!--Copyright 2012 Mozilla FoundationLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.Adobe CMap resources are covered by their own copyright but the same license:Copyright 1990-2015 Adobe Systems Incorporated.See https://github.com/adobe-type-tools/cmap-resources--><html dir="ltr" mozdisallowselectionprint moznomarginboxes><head>    <meta charset="utf-8">    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.