java实现openoffice在线预览文档

news/2024/11/30 11:27:16/

1.openoffice需要导入的jar包

jodconverter-core-3.0-beta-4.jar
juh-3.2.1.jar
jurt-3.2.1.jar
ridl-3.2.1.jar
unoil-3.2.1.jar**加粗样式**

2.js

function windowopenfile(urlp,billid,name){var url=urlp+"?billid="+billid+"&storagetype="+name;window.open(url);}

3.后台代码

//在线打开预览文档@RequestMapping("/fileview")public String fileview(Model model,String filepath,String sourceid) throws Exception{ filepath="关.doc";//sourceid=new Base64Util().decodeToString(sourceid);final String path =request.getSession().getServletContext().getRealPath("/view/word") ;fileExists(path);final String pfdpath =request.getSession().getServletContext().getRealPath("/view/filetopdf/") ;fileExists(pfdpath);String filename=request.getSession().getServletContext().getRealPath("/vod/mp4");FileToPdf fileToPdf=new FileToPdf();String	wordfilename= StringUtils.substringBeforeLast(filepath, ".");//String wordfilename = filepath.substring(0, filepath.lastIndexOf("."));File  file=new File(pfdpath+"/"+wordfilename+".pdf");if(!file .exists()){fileToPdf.docToPdf(new File(filename+"/"+filepath),new File(pfdpath+"/"+wordfilename+".pdf"));}System.out.println("fileToPdfpath"+pfdpath+"/"+wordfilename+".pdf");String osName = System.getProperty("os.name");if(osName.toLowerCase().indexOf("windows")>-1){model.addAttribute("pdfname","/SCMS/view/filetopdf/"+wordfilename+".pdf");}else{model.addAttribute("pdfname","/view/filetopdf/"+wordfilename+".pdf");}return "/admin/manage/pdf/exportPdf.ftl";}/*** 判断文件是否存在* */public static void fileExists(String path){File file =new File(path);  //如果文件夹不存在则创建    if  (!file .exists()  && !file .isDirectory())      {       file .mkdir();    }}

FileToPdf

package com.ams.util;import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.tools.Tool;import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import com.ams.ServiceConfig;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;public class FileToPdf {@Autowiredprivate HttpServletRequest request;public void docToPdf(File inputFile, File outputFile) {ServiceConfig serverconfig = new Tools().getConfig();String IP = serverconfig.getIP();System.out.println(IP);// 启动服务String OpenOffice_HOME = "";String command = "";String osName = System.getProperty("os.name");Process pro = null;OpenOfficeConnection connection = null;// 启动OpenOffice的服务/*if(osName.toLowerCase().indexOf("windows")>-1){command = OpenOffice_HOME + "program/soffice.exe --headless--accept=\"socket,host=127.0.0.1,port=8100;urp;\"";}else{command = OpenOffice_HOME + "program/startup.sh";command = OpenOffice_HOME + "program/soffice --headless--accept=\"socket,host=127.0.0.1,port=8100;urp;\"--nofirststartwizard &";}*/// System.out.println("command"+command);// connect to an OpenOffice.org instance running on port 8100try {connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);connection.connect();if (outputFile.exists()) {} else {DocumentConverter converter = new OpenOfficeDocumentConverter(connection);System.out.println(inputFile + "=" + outputFile);converter.convert(inputFile, outputFile);}} catch (Exception ex) {System.out.println("程序出错了");ex.printStackTrace();} finally {// close the connectionif (connection != null) {connection.disconnect();// connection = null;}// pro.destroy();}System.out.println("生成" + outputFile.getName());}// 生产pdf线程static class TestThread extends java.lang.Thread {private File inputFile;private File outputFile;public void run() {FileToPdf t = new FileToPdf();t.docToPdf(inputFile, outputFile);System.out.println(outputFile.getName() + "文件已生成");}public void setInputFile(File inputFile) {this.inputFile = inputFile;}public void setOutputFile(File outputFile) {this.outputFile = outputFile;}}// 将pdf转换为图片public String pdftoimage(Model model, String filepath, String pdfimage, String wordfilename) throws Exception {String filename = filepath;File file = new File(filename);String imghtml = "";try {PDDocument doc = PDDocument.load(file);PDFRenderer renderer = new PDFRenderer(doc);int pageCount = doc.getNumberOfPages();for (int i = 0; i < pageCount; i++) {File file1 = new File(pdfimage +"/"+ wordfilename + i + ".png");// 如果文件夹不存在则创建if (file1.exists()) {} else {BufferedImage image = renderer.renderImageWithDPI(i, 296);// BufferedImage image = renderer.renderImage(i, 2.5f);ImageIO.write(image, "PNG", new File(pdfimage +"/"+wordfilename + i + ".png"));}String osName = System.getProperty("os.name");if (osName.toLowerCase().indexOf("windows") > -1) {imghtml += "<img src=\'" + "/SCMS/view/filetopdf/pdfimage/" + wordfilename + i + ".png"+ "\' οndragstart=\"return false;\" style=\'width:740px;height:740px;vertical-align:text-bottom;\'><br>";} else {imghtml += "<img src=\'" + "/view/filetopdf/pdfimage/" + wordfilename + i + ".png"+ "\' οndragstart=\"return false;\" style=\'width:740px;height:740px;vertical-align:text-bottom;\'><br>";}}} catch (IOException e) {e.printStackTrace();}String pdfhtml = "<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body><div style=\"height:740px;overflow:auto\">"+ imghtml + "</div></body></html>";return pdfhtml;}}

4.下载openoffice软件
5.找到openoffice软件根目录
eg:C:\Program Files (x86)\OpenOffice 4\program
6.cmd进入黑窗口
执行C:\Program Files (x86)\OpenOffice 4\program回车
执行soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard回车
7.js页面预览文档(exportPdf.ftl)(第一种)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HEAD><#assign ctx = request.contextPath />
<META content="IE=7.0000" http-equiv="X-UA-Compatible">
<TITLE>文档预览</TITLE>
<META content="text/html; charset=UTF-8" http-equiv=content-type>
<META content=text/css http-equiv=Content-Style-Type>
<LINK rel=stylesheet type=text/css href="${ctx}/assets-web/pdf/jq.css" media=screen>
<STYLE type=text/css>
#main {TEXT-ALIGN: center; MARGIN: 20px; BACKGROUND: #fff
}
A.media {DISPLAY: block
}
DIV.media {MARGIN: auto; FONT-SIZE: small
}
DIV.media DIV {FONT-STYLE: italic; COLOR: #888
}
#lr {BORDER-BOTTOM: #eee 1px solid; BORDER-LEFT: #eee 1px solid; MARGIN: auto; BORDER-TOP: #eee 1px solid; BORDER-RIGHT: #eee 1px solid
}
DIV.example {BORDER-BOTTOM: #ccc 1px dashed; TEXT-ALIGN: left; BORDER-LEFT: #ccc 1px dashed; PADDING-BOTTOM: 20px; MARGIN: 15px 0px; PADDING-LEFT: 20px; PADDING-RIGHT: 20px; BACKGROUND: #ffe; CLEAR: left; BORDER-TOP: #ccc 1px dashed; BORDER-RIGHT: #ccc 1px dashed; PADDING-TOP: 20px
}
</STYLE><SCRIPT type=text/javascript 
src="${ctx}/assets-web/pdf/jquery.min.js"></SCRIPT><SCRIPT type=text/javascript 
src="${ctx}/assets-web/pdf/chili-1.7.pack.js"></SCRIPT><SCRIPT type=text/javascript 
src="${ctx}/assets-web/pdf/jquery.media.js"></SCRIPT><SCRIPT type=text/javascript 
src="${ctx}/assets-web/pdf/jquery.metadata.js"></SCRIPT><SCRIPT type=text/javascript>$(function() {$('a.media').media({width:1200, height:850});});
</SCRIPT><META name=GENERATOR content="MSHTML 9.00.8112.16520"></HEAD>
<BODY><!--${ctx}/vod/mp4/-->
<A class=media href="${(pdfname)!}">PDF File</A> 
<SCRIPT type=text/javascript src="${ctx}/assets-web/pdf/urchin.js"></SCRIPT></BODY></HTML>

7.js页面预览文档(exportPdf.ftl)(第二种)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HEAD><#assign ctx = request.contextPath /><META content="IE=7.0000" http-equiv="X-UA-Compatible"><TITLE>文档预览</TITLE><META content="text/html; charset=UTF-8" http-equiv=content-type><META content=text/css http-equiv=Content-Style-Type><LINK rel=stylesheet type=text/css href="${ctx}/assets/pdf/jq.css" media=screen>
<BODY><script type="text/javascript">window.onload=function (ev) {PDFObject.embed("${(pdfname)!}","body");}</script><script type="text/javascript" src="${ctx!}/assets/pdf/pdfobject.min.js" ></script>
</BODY></HTML>

pdfobject.min.js

/*PDFObject v2.0.201604172https://github.com/pipwerks/PDFObjectCopyright (c) 2008-2016 Philip HutchisonMIT-style license: http://pipwerks.mit-license.org/UMD module pattern from https://github.com/umdjs/umd/blob/master/templates/returnExports.js
*/
(function(root,factory){if(typeof define==="function"&&define.amd){define([],factory)}else if(typeof module==="object"&&module.exports){module.exports=factory()}else{root.PDFObject=factory()}})(this,function(){"use strict";if(typeof window==="undefined"||typeof navigator==="undefined"){return false}var pdfobjectversion="2.0.201604172",supportsPDFs,createAXO,isIE,supportsPdfMimeType=typeof navigator.mimeTypes["application/pdf"]!=="undefined",supportsPdfActiveX,buildFragmentString,log,embedError,embed,getTargetElement,generatePDFJSiframe,isIOS=function(){return/iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase())}(),generateEmbedElement;createAXO=function(type){var ax;try{ax=new ActiveXObject(type)}catch(e){ax=null}return ax};isIE=function(){return!!(window.ActiveXObject||"ActiveXObject"in window)};supportsPdfActiveX=function(){return!!(createAXO("AcroPDF.PDF")||createAXO("PDF.PdfCtrl"))};supportsPDFs=supportsPdfMimeType||isIE()&&supportsPdfActiveX();buildFragmentString=function(pdfParams){var string="",prop;if(pdfParams){for(prop in pdfParams){if(pdfParams.hasOwnProperty(prop)){string+=encodeURIComponent(prop)+"="+encodeURIComponent(pdfParams[prop])+"&"}}if(string){string="#"+string;string=string.slice(0,string.length-1)}}return string};log=function(msg){if(typeof console!=="undefined"&&console.log){console.log("[PDFObject] "+msg)}};embedError=function(msg){log(msg);return false};getTargetElement=function(targetSelector){var targetNode=document.body;if(typeof targetSelector==="string"){targetNode=document.querySelector(targetSelector)}else if(typeof jQuery!=="undefined"&&targetSelector instanceof jQuery&&targetSelector.length){targetNode=targetSelector.get(0)}else if(typeof targetSelector.nodeType!=="undefined"&&targetSelector.nodeType===1){targetNode=targetSelector}return targetNode};generatePDFJSiframe=function(targetNode,url,pdfOpenFragment,PDFJS_URL,id){var fullURL=PDFJS_URL+"?file="+encodeURIComponent(url)+pdfOpenFragment;var scrollfix=isIOS?"-webkit-overflow-scrolling: touch; overflow-y: scroll; ":"overflow: hidden; ";var iframe="<div style='"+scrollfix+"position: absolute; top: 0; right: 0; bottom: 0; left: 0;'><iframe  "+id+" src='"+fullURL+"' style='border: none; width: 100%; height: 100%;' frameborder='0'></iframe></div>";targetNode.className+=" pdfobject-container";targetNode.style.position="relative";targetNode.style.overflow="auto";targetNode.innerHTML=iframe;return targetNode.getElementsByTagName("iframe")[0]};generateEmbedElement=function(targetNode,targetSelector,url,pdfOpenFragment,width,height,id){var style="";if(targetSelector&&targetSelector!==document.body){style="width: "+width+"; height: "+height+";"}else{style="position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 100%; height: 100%;"}targetNode.className+=" pdfobject-container";targetNode.innerHTML="<embed "+id+" class='pdfobject' src='"+url+pdfOpenFragment+"' type='application/pdf' style='overflow: auto; "+style+"'/>";return targetNode.getElementsByTagName("embed")[0]};embed=function(url,targetSelector,options){if(typeof url!=="string"){return embedError("URL is not valid")}targetSelector=typeof targetSelector!=="undefined"?targetSelector:false;options=typeof options!=="undefined"?options:{};var id=options.id&&typeof options.id==="string"?"id='"+options.id+"'":"",page=options.page?options.page:false,pdfOpenParams=options.pdfOpenParams?options.pdfOpenParams:{},fallbackLink=typeof options.fallbackLink!=="undefined"?options.fallbackLink:true,width=options.width?options.width:"100%",height=options.height?options.height:"100%",forcePDFJS=typeof options.forcePDFJS==="boolean"?options.forcePDFJS:false,PDFJS_URL=options.PDFJS_URL?options.PDFJS_URL:false,targetNode=getTargetElement(targetSelector),fallbackHTML="",pdfOpenFragment="",fallbackHTML_default="<p>This browser does not support inline PDFs. Please download the PDF to view it: <a href='[url]'>Download PDF</a></p>";if(!targetNode){return embedError("Target element cannot be determined")}if(page){pdfOpenParams.page=page}pdfOpenFragment=buildFragmentString(pdfOpenParams);if(forcePDFJS&&PDFJS_URL){return generatePDFJSiframe(targetNode,url,pdfOpenFragment,PDFJS_URL,id)}else if(supportsPDFs){return generateEmbedElement(targetNode,targetSelector,url,pdfOpenFragment,width,height,id)}else{if(PDFJS_URL){return generatePDFJSiframe(targetNode,url,pdfOpenFragment,PDFJS_URL,id)}else if(fallbackLink){fallbackHTML=typeof fallbackLink==="string"?fallbackLink:fallbackHTML_default;targetNode.innerHTML=fallbackHTML.replace(/\[url\]/g,url)}return embedError("This browser does not support embedded PDFs")}};return{embed:function(a,b,c){return embed(a,b,c)},pdfobjectversion:function(){return pdfobjectversion}(),supportsPDFs:function(){return supportsPDFs}()}});

http://www.ppmy.cn/news/706259.html

相关文章

JAVA进阶之路-openoffice+pfd.js实现在线预览文档

首先我们需要准备需要的文件 1、pdf.js的文件,可以直接百度去官网下载&#xff0c;下载下来官网还会自带一个demo。 2、下载openoffice并安装好. 1)windos环境下的直接百度下载安装就好了。 2)linux下载的安装可以参考这个https://blog.csdn.net/u013132051/article/detail…

java在线编辑word_JavaWebOffice在线编辑.doc

Java?Web?Office?文档在线编辑 1、创建页面Office在线编辑 function CreateDoc() { document.all.OA1.CreateNew( "Word.Document"); } function CreateExcel() { document.all.OA1.CreateNew( "Excel.Sheet"); } function CreatePPT() { document.all.…

OpenOffice+JodConverter实现Office文件到PDF的转换

OpenOffice简介 OpenOffice自从2002年发布第一个版本1.0.1以来已经过去了15个年头&#xff0c;在2011年移转至ASF&#xff0c;更在2012年底正式成为Apache顶级项目之一。而OpenOffice.org的名头也转换为了Apache OpenOffice。 作为Office工具的翻版&#xff0c;OpenOffice在文…

onlyoffice online二次开发:(一)环境搭建

前言 onlyoffice 提供各种强大组件实现对office文档编辑功能&#xff0c;关键是跨平台不局限Windows系统&#xff0c;其中Document Server 可作为在线编辑文档服务器&#xff0c;我们只需要通过调用其提供的API&#xff0c;就能实现我们所需功能。 官网&#xff1a;https://w…

java 基于 openOffice 实现在线预览功能

1 原理 将 office 文档转换为 pdf &#xff0c;返回文件流给前端实现预览 2 controller 代码 ApiOperation(value "系统文件在线预览接口")GetMapping("/onlinePreview")public void onlinePreview(RequestParam("url") String url, HttpServ…

使用openoffice转pdf,详细

近期由于项目的需求&#xff0c;需要word文档转pdf在线预览&#xff0c;由于一直没有接触这块&#xff0c;所以花了将近四天时间才弄明白。 写这篇文章的主要目的是加深自己的记忆&#xff0c;同时方便以后在用。 &#xff08;最近有使用了这个功能&#xff0c;发现这篇文章有…

springboot集成openoffice实现office转PDF在线预览

1、下载官网 OpenOffice 下载地址 Apache OpenOffice - Official Download 2、安装启动服务 window环境: 进入openoffice安装目录&#xff1a;/program/ 开启服务&#xff1a;cmd命令 soffice -headless -accept“socket,host127.0.0.1,port8100;urp;” -nofirststartw…

用java实现,office文件转成pdf文件

实现环境&#xff1a;要求可以在linux环境下运行&#xff0c;开源插件 &#xff0c; 跨平台 以下有五种方法&#xff1a; 结论&#xff1a; office不支持跨平台&#xff0c; aspose收费&#xff0c; 基于pioitext转换后会严重失真&#xff0c; 基于libreOffice不支持插入图…