1. 程式人生 > >使用openoffice實現檔案的預覽 使用流的方式實現

使用openoffice實現檔案的預覽 使用流的方式實現

    前段時間,專案需求做一個檔案預覽的功能  通過查資料完成 ,在這裡記錄一下

首先我們用到openoffice服務  下載安裝openoffice   進入安裝openoffice的program目錄下開啟命令視窗.執行

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;"

命令啟動服務 

轉換pdf的工具類

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat; import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import java.io.*; import java.net.ConnectException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Administrator * on 2018/3/12 */ public class Doc2HtmlUtil { private static Doc2HtmlUtil doc2HtmlUtil; /** * 獲取Doc2HtmlUtil例項 */ public static synchronized
Doc2HtmlUtil getDoc2HtmlUtilInstance() { if (doc2HtmlUtil == null) { doc2HtmlUtil = new Doc2HtmlUtil(); } return doc2HtmlUtil; } /** * 轉換檔案成html * * @param fromFileInputStream: * @throws IOException */ public String file2Html(InputStream fromFileInputStream, String toFilePath,String type,String host,int port) throws IOException { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String timesuffix = sdf.format(date); String docFileName = null; String htmFileName = null; if("doc".equals(type)){ docFileName = "doc_" + timesuffix + ".doc"; htmFileName = "doc_" + timesuffix + ".html"; }else if("docx".equals(type)){ docFileName = "docx_" + timesuffix + ".docx"; htmFileName = "docx_" + timesuffix + ".html"; }else if("xls".equals(type)){ docFileName = "xls_" + timesuffix + ".xls"; htmFileName = "xls_" + timesuffix + ".html"; }else if("ppt".equals(type)){ docFileName = "ppt_" + timesuffix + ".ppt"; htmFileName = "ppt_" + timesuffix + ".html"; }else{ return null; } File htmlOutputFile = new File(toFilePath + File.separatorChar + htmFileName); File docInputFile = new File(toFilePath + File.separatorChar + docFileName); if (htmlOutputFile.exists()) htmlOutputFile.delete(); htmlOutputFile.createNewFile(); if (docInputFile.exists()) docInputFile.delete(); docInputFile.createNewFile(); /** * 由fromFileInputStream構建輸入檔案 */ try { OutputStream os = new FileOutputStream(docInputFile); int bytesRead = 0; byte[] buffer = new byte[1024 * 8]; while ((bytesRead = fromFileInputStream.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); fromFileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } OpenOfficeConnection connection = new SocketOpenOfficeConnection(host,port); try { connection.connect(); } catch (ConnectException e) { System.err.println("檔案轉換出錯,請檢查OpenOffice服務是否啟動。"); } // convert DocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(docInputFile, htmlOutputFile); connection.disconnect(); // 轉換完之後刪除word檔案 docInputFile.delete(); return htmFileName; } /** * 轉換檔案成pdf * * @param fromFileInputStream: * @throws IOException */ public String file2pdf(InputStream fromFileInputStream, String toFilePath,String type,String host,int port) throws IOException { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String timesuffix = sdf.format(date); String docFileName = null; String htmFileName = null; if("doc".equals(type)){ docFileName = "doc_" + timesuffix + ".doc"; htmFileName = "doc_" + timesuffix + ".pdf"; }else if("docx".equals(type)){ docFileName = "docx_" + timesuffix + ".docx"; htmFileName = "docx_" + timesuffix + ".pdf"; }else if("xls".equals(type)){ docFileName = "xls_" + timesuffix + ".xls"; htmFileName = "xls_" + timesuffix + ".pdf"; }else if("ppt".equals(type)){ docFileName = "ppt_" + timesuffix + ".ppt"; htmFileName = "ppt_" + timesuffix + ".pdf"; }else{ return null; } File htmlOutputFile = new File(toFilePath + File.separatorChar + htmFileName); File docInputFile = new File(toFilePath + File.separatorChar + docFileName); if (htmlOutputFile.exists()) htmlOutputFile.delete(); htmlOutputFile.createNewFile(); if (docInputFile.exists()) docInputFile.delete(); docInputFile.createNewFile(); /** * 由fromFileInputStream構建輸入檔案 */ try { OutputStream os = new FileOutputStream(docInputFile); int bytesRead = 0; byte[] buffer = new byte[1024 * 8]; while ((bytesRead = fromFileInputStream.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); fromFileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } OpenOfficeConnection connection = new SocketOpenOfficeConnection(host,port); try { connection.connect(); } catch (ConnectException e) { System.err.println("檔案轉換出錯,請檢查OpenOffice服務是否啟動。"); } // convert DocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(docInputFile, htmlOutputFile); connection.disconnect(); // 轉換完之後刪除word檔案 docInputFile.delete(); return htmFileName; } /** * 執行前,請啟動openoffice服務 * 進入$OO_HOME\program下 * 執行soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" * @param xlsfile * @param targetfile * @throws Exception */ public static void fileConvertPdf(String xlsfile, String targetfile,String type,String host,int port) throws Exception { File xlsf = new File(xlsfile); File targetF = new File(targetfile); // 獲得檔案格式 DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry(); DocumentFormat pdfFormat = formatReg.getFormatByFileExtension("pdf"); DocumentFormat docFormat = null; if("doc".equals(type) || "docx".equals(type)){ docFormat = formatReg.getFormatByFileExtension("doc"); }else if("xls".equals(type) || "xlsx".equals(type)){ docFormat = formatReg.getFormatByFileExtension("xls"); }else if("ppt".equals(type)){ docFormat = formatReg.getFormatByFileExtension("ppt"); }else{ docFormat = formatReg.getFormatByFileExtension("doc"); } // stream 流的形式 InputStream inputStream = new FileInputStream(xlsf); OutputStream outputStream = new FileOutputStream(targetF); /** * */ OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100); try { connection.connect(); DocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputStream, docFormat, outputStream, pdfFormat); } catch (ConnectException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); connection = null; } } } /** * 執行前,請啟動openoffice服務 * 進入$OO_HOME\program下 * 執行soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" 或 soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard * @param inputStream * @param outputStream * @throws Exception */ public static void fileConvertPdf(InputStream inputStream, OutputStream outputStream,String type,String host,int port) throws Exception { // 獲得檔案格式 DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry(); DocumentFormat pdfFormat = formatReg.getFormatByFileExtension("pdf"); DocumentFormat docFormat = null; if(".doc".equals(type) || ".docx".equals(type)){ docFormat = formatReg.getFormatByFileExtension("doc"); }else if(".xls".equals(type) || ".xlsx".equals(type)){ docFormat = formatReg.getFormatByFileExtension("xls"); }else if(".ppt".equals(type)){ docFormat = formatReg.getFormatByFileExtension("ppt"); }else if(".txt".equals(type)){ docFormat = formatReg.getFormatByFileExtension("txt"); }else if(".pdf".equals(type)){ docFormat = formatReg.getFormatByFileExtension("pdf"); }else{ docFormat = formatReg.getFormatByFileExtension("doc"); } // stream 流的形式 OpenOfficeConnection connection = new SocketOpenOfficeConnection(host,port); try { connection.connect(); DocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputStream, docFormat, outputStream, pdfFormat); } catch (ConnectException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); connection = null; } } } public static void main(String[] args) throws Exception { URL url=new URL("http://192.168.6.152:9000/group1/M00/00/0A/wKgGmFqaFKKAb6ixAAAYAFWbzCU610.xls");//預設主頁 InputStream is=url.openStream();//獲取網路流 /*//獲取網路資源,編碼格式不同會出現亂碼**************** byte[] flush=new byte[1024]; int len=0; while(-1!=(len=is.read(flush))) { System.out.println(new String(flush,0,len)); } is.close(); //獲取網路資源,編碼格式不同會出現亂碼*****************/ //解決亂碼的方法,轉換流 BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));//解碼方式,utf-8 String msg=null; BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\poi-test\\1.xls"),"utf-8")); while((msg=br.readLine())!=null) { bw.append(msg); bw.newLine(); } bw.flush(); bw.close(); br.close(); /*Doc2HtmlUtil coc2HtmlUtil = getDoc2HtmlUtilInstance(); String a = "D:\\poi-test\\exportExcel.xls"; String b = "D:\\poi-test\\exportExcel.pdf"; InputStream inputStream = new FileInputStream(a); OutputStream outputStream = new FileOutputStream(b); coc2HtmlUtil.fileConvertPdf(inputStream,outputStream,"xls");*/ /* File file = null; FileInputStream fileInputStream = null; file = new File("D:\\poi-test\\exportExcel.xls"); fileInputStream = new FileInputStream(file); // coc2HtmlUtil.file2Html(fileInputStream, "D:/poi-test/openOffice/xls","xls"); coc2HtmlUtil.file2pdf(fileInputStream, "D:\\poi-test\\openOffice\\xls","xls");*/ /* file = new File("D:/poi-test/test.doc"); fileInputStream = new FileInputStream(file); // coc2HtmlUtil.file2Html(fileInputStream, "D:/poi-test/openOffice/doc","doc"); coc2HtmlUtil.file2pdf(fileInputStream, "D:/poi-test/openOffice/doc","doc"); file = new File("D:/poi-test/週報模版.ppt"); fileInputStream = new FileInputStream(file); // coc2HtmlUtil.file2Html(fileInputStream, "D:/poi-test/openOffice/ppt","ppt"); coc2HtmlUtil.file2pdf(fileInputStream, "D:/poi-test/openOffice/ppt","ppt"); file = new File("D:/poi-test/test.docx"); fileInputStream = new FileInputStream(file); // coc2HtmlUtil.file2Html(fileInputStream, "D:/poi-test/openOffice/docx","docx"); coc2HtmlUtil.file2pdf(fileInputStream, "D:/poi-test/openOffice/docx","docx");*/ } }

控制層訪問的方法  只需要傳入要進行預覽檔案的url即可

    @RequestMapping("/seeFile")
    public void seeFile(String fileUrl,HttpServletResponse response)  {
        try {
            FastDFSClient fastDFSClient = null;
fastDFSClient = new FastDFSClient("fdfs_client.properties");
//  String fileUrl = "group1/M00/00/03/wKgGmFp8ROeAQZ_TAAA_UmBde7I00.docx";
String extName = fileUrl.substring(fileUrl.lastIndexOf("."));
//            if (".pdf".equals(extName)){
////                File pdfFormat = new File(fileUrl);
////                File docFormat = new File(fileUrl);
//                Doc2HtmlUtil coc2HtmlUtil = Doc2HtmlUtil.getDoc2HtmlUtilInstance();
//                coc2HtmlUtil.fileConvertPdf(fileUrl,fileUrl,extName,"127.0.0.1",8100);
//            }
byte[] bytes = fastDFSClient.downloadFile(fileUrl);
InputStream inputStream = new ByteArrayInputStream(bytes);
OutputStream outputStream = response.getOutputStream();
Doc2HtmlUtil coc2HtmlUtil = Doc2HtmlUtil.getDoc2HtmlUtilInstance();
coc2HtmlUtil.fileConvertPdf(inputStream,outputStream,extName,"127.0.0.1",8100); //openoffice的IP和埠
}catch (Exception e){
            e.printStackTrace();
}

    }

頁面的js程式碼

yuLan: function (url) {
    //   location.href = "/followRecord/seeFile";
var index = url.lastIndexOf(".");
var fileType = url.substring(index);
// debugger
if (".pdf" == fileType) {
        $.ajax({
            url: "/task/getFilePath",
type: 'POST',
// async:false,
data: {
                "url": url
            },
dataType: "text",
error: function () {
                // layer.msg("獲取pdf檔案路徑出錯");
alert("獲取pdf檔案路徑出錯")
            },
success: function (data) {
                console.log(data);
window.open(data)
            }
        });
} else {
        window.open("/followRecord/seeFile?fileUrl=" + url);
}
},

相關推薦

前端接收資料實現圖片效果--ajax 請求二進位制 圖片 檔案 XMLHttpRequest 請求並處理二進位制資料 之最佳實踐

本文為轉載文章 原文連結:https://www.cnblogs.com/cdemo/p/5225848.html 首先要謝謝這位大神的無私貢獻!解決了我的問題也完美表達了我當時的心路歷程 ajax 請求二進位制流 圖片 檔案 XMLHttpRequest 請求並處理二進位制流資料 之最佳實踐

JAVA Web專案中用OpenOffice+Swftools+Flexpaper實現線上,txt檔案出現亂碼!

在幼兒園管理系統中,實現線上預覽功能。當上傳word、ppt、excel、pdf的時候,不會出現亂碼;當上傳txt檔案的時候(編碼除UTF-8之外),會出現亂碼。當時有兩個方案。 方案一: 在上傳txt檔案的時候,判斷其編碼是否為UTF-8,如果不是,提示框:提示使用者上傳

java 使用openoffice 轉換文件,成.pdf,實現線上效果

1. 下載 openoffice 地址     https://pan.baidu.com/s/1dfpoG6zlawoW1pqpDvBL0A 密碼: v4ej     如果上面的地址無法訪問請訪問這個地址:下載地址如下:http://www.openof

ionic3專案實現線上PDF檔案

這裡參考了大牛提供的預覽外掛完成自己需要實現的功能,ng2-pdf-viewer,該外掛不支援ionic3的懶載入,廢話少說,直接擼程式碼。 第一步,安裝 ng2-pdf-viewer npm install ng2-pdf-viewer --save 第二步,在專案中新建頁面

Java實現線上--openOffice實現

Java實現線上預覽–openOffice實現 簡介 之前有寫了poi實現線上預覽的文章,裡面也說到了使用openOffice也可以做到,這裡就詳細介紹一下。 我的實現邏輯有兩種: 一、利用jodconverter(基於OpenOffice服務)將檔案(.doc、.docx、.xls、.pp

centos6.5下安裝openoffice+jodconverter+swftool+flexpaper工具實現線上文件功能

作用:linux下文件伺服器上傳文件轉換成pdf文件,再由swftool工具轉換成swf檔案實現線上預覽 環境:OS   centos6.5           java環境 軟體包:Apac

input file 方式上傳圖片並實現實時

用普通的html的 <input type="file"/> 標籤是不能實現實時預覽功能的,獲取表單的值可以得到圖片所在路徑:C:\fakepath\test.png,如果將它直接賦值給img標籤的href屬性,會報錯:Not allowed to load lo

前端實現線上pdf、word、xls、ppt等檔案

1、前端實現pdf檔案線上預覽功能 方式一: 通過a標籤href屬性實現 pdf檔案理論上可以在瀏覽器直接開啟預覽但是需要開啟新頁面。在僅僅是預覽pdf檔案且UI要求不高的情況下可以直接通過a標籤href屬性實現預覽 <a href="文件地址"></

怎麼簡便地去掉html中難看的檔案上傳按鈕並實現圖片功能?

問題描述 通常的檔案上傳按鈕是這樣的: 選擇了檔案過後是這樣的: 很顯然,這樣的按鈕並不好看。 解決方法 用一個label標籤來裝載樣式,其for屬性指向type=file的inp

(一)Android camera2 實現相機及獲取幀資料

一、本文重點說明 本文基於 android camera2 實現視訊預覽,暫未相容 camera1 API,基礎實現可以參考 googlesample Camera2 例子 android-Camera2Basic ,本文以工具類形式實現一步呼叫。 谷歌例子中沒有具體指

java實現附件openoffice+swftools+flexpaper)

先附上本人蔘考的文章,基於的 flexpaper版本 為 1.5,本人由於使用的是 2.1.9 ,故之後說明: 已經支援載入中文檔名 程式碼下載 1.概述 主要原理 1.通過第三方工具openoffice,將word、excel、pp

Asp.net MVC 利用(aspose+pdfobject.js) 實現線上word、excel、ppt、pdf檔案

線上預覽word、excel、ppt利用aspose動態生成html 主要程式碼 private bool OfficeDocumentToHtml(string sourceDoc, string saveDoc) { bool result = false;

利用FileReader和FormData實現圖片和上傳(base64轉二進位制檔案)

業務有個需求,要做圖片預覽上傳,過去都是客戶端上傳給後端,後端返回 url 前端進行預覽,現在其實可以不依賴後端做預覽,最後在上傳,這主要依賴 FileReader 和 FormData 這兩個物件和 JavaScript 處理二進位制的能力。 OK,Show cod

通過位元組方式實現檔案下載以及其中的編碼問題

關鍵程式碼 頁面程式碼 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding

C#實現Windows資源管理器檔案

上一篇文章大致介紹了一下C++實現Windows檔案預覽的方法,這裡介紹一下通過.NET方式實現檔案預覽。 其實原理還是一樣,需要通過實現系統定義的COM介面,包括 IInitializeWithFile,IObjectWithSite, IOleWi

Java實現線上openOffice實現

Java實現線上預覽–openOffice實現 簡介 之前有寫了poi實現線上預覽的文章,裡面也說到了使用openOffice也可以做到,這裡就詳細介紹一下。 我的實現邏輯有兩種: 一、利用jodconverter(基於OpenOffice服務)將檔案(

通過Aspose對Word,Excel檔案進行Pdf轉換,實現線上

解決思路:1.利用AsposeCells,AsposeWords相關Jar包提供的轉換功能,將Excel及Word型別文件轉換為Pdf檔案,並存於當前專案目錄下2.通過瀏覽器的iframe標籤功能,直接訪問應用下的相關Pdf檔案,目前主流瀏覽器均支援直接在頁面上瀏覽Pdf檔案

office(如:Word、Excel、PPT 等)檔案輕鬆實現線上

解決方案有很多,比如可以先將檔案轉圖片或者pdf然後再網頁中顯示, 我在這裡說的可能並不適合大家,這裡簡單說下幾個快捷的方式 方案一: 可以直接使用第三方服務,不過這個需要收費的,我在這列幾個 http://www.yozodcs.com/ htt

jquery.media.js 外掛實現線上PDF檔案

 程式碼: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content

jsp實現線上pdf、word、xls、ppt等檔案

最近在做一個共享數字化平臺,一些所涉功能知識記錄一下。 、其他教程寫得太老了,可能到如今已經不再適用。 1、jsp實現pdf檔案線上預覽功能 方式一、pdf檔案理論上可以在瀏覽器直接開啟預覽但是需要開啟新頁面。在僅僅是預覽pdf檔案且UI要求不高的情況下可以直