网上虽然有各种在线文档制作的教程但却没有一个集大成的,经过小亮同学不辞辛苦勤奋耕耘下终于制作出了相关的雏形,然后在下在稍加润色,这样一篇完整的博客便横空出世了- -,   下面则是分类进行介绍。

  在分开介绍前先给出后台的文件控制函数,这个函数就是简单的根据请求参数中包含的文件类型来具体调用相关的方法。代码如下:

  

    /*** 文件显示的控制函数,由此来判断文件类型并调用相关方法* @return*/public String lookUpfileValue(){//获取web上下文对象ServletContext sc = ServletActionContext.getServletContext();//获得服务器上文件所在地址String realPath = sc.getRealPath("/upload");//获得文件全路径String filePath = realPath + File.separatorChar +ftObj.getStoreFileName() ;String strFileName = ftObj.getStoreFileName().substring(0, ftObj.getStoreFileName().lastIndexOf("."));//获得文件扩展名String extensions =ftObj.getStoreFileName().substring(ftObj.getStoreFileName().lastIndexOf("."),ftObj.getStoreFileName().length());//创建FileTable该类用来封装文件的属性包括作者,文件名等FileTable fileTableObj=new FileTable();String filename1 =strFileName.substring(0,strFileName.length()-13);fileTableObj.setFileName(filename1);fileTableObj.setAuthor(ftObj.getAuthor());ftObj =fileTableObj;/*** 以下为根据后缀判断文件类型并进行方法调用*/try {//如果是excel文件if(extensions.equals(".xls")){//获得文件放置路径String fWPath = sc.getRealPath("/fileManagement");fWPath = fWPath+"\\";//生成临时文件的字符串String fWPath2 =fWPath+ "temp.pdf";try {//保存临时文件
                        saveExcelAsPdf(filePath,fWPath2);//创建临时File file=new File(fWPath2); //将Pdf转成图片pdfStrList  =reapdf(file,realPath);System.gc();//删除临时文件boolean success = file.delete();System.out.println(success);} catch (Throwable e) {}return "lookupPdf";}else if(extensions.equals(".doc")){String fWPath = sc.getRealPath("/fileManagement");try {readword(filePath,fWPath);} catch (Throwable e) {}}else if(extensions.equals(".pdf")){File fobj = new File (filePath);fname = FileTableAction.getTextFromPdf(filePath);pdfStrList  =reapdf(fobj,realPath);return "lookupPdf";}else{fname = FileTableAction.readTxt(filePath);return "lookupnohtml";}} catch (Exception e) {}return "lookup";}

  该方法注释写的很清楚在这里不多做解释。

1.制作txt在线文档

  txt 文档相对来说比较简单,因为基本都是文本的东西,这里先说明下展示的逻辑,我们将服务器上的文本文档经后台读入到缓存中染后经过控制的bean传送到前台界面显示。

  

/*** 读取txt文档的方法* @param txt* @return*/public static String readTxt(String txt){StringBuffer sb = new StringBuffer();try {// 创建文件字符流对象FileReader read = new FileReader(new File(txt));//创建字符缓存char ch[] = new char[1024];//将文件读入到缓存int d = read.read(ch);while(d!=-1){String str = new String(ch,0,d);sb.append(str);d = read.read(ch);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return sb.toString();}

  这里只是单纯将文本文档的内容读取出来传值到前台,并无其他难点。前台部分界面接收值的样式如下<textarea>${news.newsContent}</textarea>,可以看到读出来的文本文档被封装为news实体的一个field。

2.制作word在线文档 

  这里是把word 转成jsp 后显示,其余的前端界面请自行百度。相关java后台代码如下

  

//读起word文档public static void  readword(String filepath,String fwpath) throws Throwable{//获得文件的路径String path = filepath.substring(0,filepath.lastIndexOf("\\"))+"\\";//创建输入流InputStream input = new FileInputStream(filepath);//创建HWPFDocument对象,这里用了第三方的插件poiHWPFDocument wordDocument = new HWPFDocument(input);//创建word到html的转换对象WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());//设置word到html的转换对象的图像管理属性wordToHtmlConverter.setPicturesManager(new PicturesManager() {public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {return suggestedName;}});wordToHtmlConverter.processDocument(wordDocument);//获得该word中所有的图片List pics = wordDocument.getPicturesTable().getAllPictures();if (pics != null) {for (int i = 0; i < pics.size(); i++) {Picture pic = (Picture) pics.get(i);try {pic.writeImageContent(new FileOutputStream(path + pic.suggestFullFileName()));} catch (FileNotFoundException e) {e.printStackTrace();}}}//由    word到html的转换对象创建dom对象Document htmlDocument = wordToHtmlConverter.getDocument();//创建字节输出输出流ByteArrayOutputStream outStream = new ByteArrayOutputStream();//创建dorm的数据源对象DOMSource domSource = new DOMSource(htmlDocument);//创建结果输出流StreamResult streamResult = new StreamResult(outStream);//创建转化工厂TransformerFactory tf = TransformerFactory.newInstance();Transformer serializer = tf.newTransformer();/*** 以下为编码,样式的属性设置*/serializer.setOutputProperty(OutputKeys.ENCODING, "GBK");serializer.setOutputProperty(OutputKeys.INDENT, "yes");serializer.setOutputProperty(OutputKeys.METHOD, "html");serializer.transform(domSource, streamResult);outStream.close();//获得内容的字符串对象String content = new String(outStream.toByteArray());
        String temp = "<%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"utf-8\"%><br> <%@taglib prefix=\"s\"  uri=\"/struts-tags\"%>";temp =temp + content.replace("<img src=\"","<img src=\""+"${pageContext.request.contextPath}/upload/");
//        System.out.println(temp);String itemp = temp.replace("</style>", ".SelectId{" +"-webkit-user-select:none; /* Webkit */ " +" -moz-user-select:none; /* Firefox */" +" -ms-user-select:none; /* IE10+ */ " +"} </style>");itemp = itemp.replace("<body class=\"b1 b2\">", "<body class=\"b1 b2\"> \r <div style=\"margin-left:100px;;margin-top:20px;\" class=\"SelectId\">");itemp =itemp.replace("</body>", "</div> </body>");//写回文件到前端显示FileUtils.write(new File(fwpath, "abc.jsp"), itemp, "utf-8");}

  这里需要用Poi的第三软类库来完成对word文件的"拆分",然后根据自己的需要将获得的拆分元素写回前端显示。

3.制作pdf在线文档

  这里采取了一种折中的办法,先把pdf转化为图片然后在页面读取,这个办法好像不是特别好,所以如果能找到更好的办法请联系本人,

这里同样要引入第三方类库itextpdf-5.3.5.jar java代码如下

  

//生成pdf生成图片public static List<String> reapdf(File file,String upleadpath) throws IOException {List<String> strlist = new ArrayList<String>();//创建随即读取文件留RandomAccessFile raf = new RandomAccessFile(file, "r");FileChannel channel = raf.getChannel();ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());//创建PDF文件对象PDFFile pdffile = new PDFFile(buf);//显示Pdf文件页数    System.out.println("页数: " + pdffile.getNumPages());//根据页数生成图片for (int i = 1; i <= pdffile.getNumPages(); i++) {// 创建pdf 页对象PDFPage page = pdffile.getPage(i);// 获得图片的宽度和长度Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());// 创建文件对象Image img = page.getImage(rect.width*2, rect.height*2, // width &rect, // clip rectnull, // null for the ImageObservertrue, // fill background with whitetrue // block until drawing is done
                    );//创建图片缓存BufferedImage tag = new BufferedImage(rect.width*2, rect.height*2,BufferedImage.TYPE_INT_RGB);tag.getGraphics().drawImage(img, 0, 0, rect.width*2, rect.height*2,null);FileOutputStream out = new FileOutputStream(upleadpath+"\\"+ i + ".jpg"); // 输出到文件流strlist.add(i + ".jpg");JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(tag); // JPEG编码
        out.close();buf.clear();channel.close();raf.close();}return strlist;}

  对Pdf文档的转化同样使用专门的处理类库将pdf分解为单页的图片传到前端显示,代码内容注释给出,在这里不多做废话。下面详细说明下excel转化为在线文档,这个比较复杂,涉及到两种类型:一种是没有图片的,一种是有图片的。这里同样跟word一样使用了poi的第三方类库

4.1Excel 转jsp 用poi 没有图片的

//读起excel文档public static void  readexcel(String filepath,String fwpath) throws Throwable{//定义HSSFWorkbook对象
           HSSFWorkbook workbook;File f = new File(filepath);try{//根据文件路径获得HSSFWorkbook对象workbook = ExcelToHtmlUtils.loadXls( f );}catch ( Exception exc ){return;}//获得excel转化Html对象ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );excelToHtmlConverter.processWorkbook(workbook );//创建写出对象StringWriter stringWriter = new StringWriter();/*** 设置转化的样式*/                Transformer transformer = TransformerFactory.newInstance().newTransformer();transformer.setOutputProperty( OutputKeys.ENCODING, "GBK" );transformer.setOutputProperty( OutputKeys.INDENT, "no" );transformer.setOutputProperty( OutputKeys.METHOD, "html" );transformer.transform(new DOMSource( excelToHtmlConverter.getDocument() ),new StreamResult( stringWriter ) );/*** 以下雷同word转化方法*/String temp = "<%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"utf-8\"%><br> <%@taglib prefix=\"s\"  uri=\"/struts-tags\"%>";temp =temp +stringWriter.toString();temp = temp.replace("<img src=\"","<img src=\""+"${pageContext.request.contextPath}/upload/");String itemp = temp.replace("</style>", ".SelectId{" +"-webkit-user-select:none; /* Webkit */ " +" -moz-user-select:none; /* Firefox */" +" -ms-user-select:none; /* IE10+ */ " +"} </style>");itemp = itemp.replace("<body class=\"b1\">", "<body  class=\"b1\"> \r <div style=\"margin-left:100px;;margin-top:20px;\" class=\"SelectId\">");itemp=itemp.replace("</body>", "</div> </body>");FileUtils.write(new File(fwpath, "abc.jsp"), itemp, "utf-8");}

  以上的方法同word转化在线文档差不多再次不多做解释。

4.2有图片的 用jacob做的 吧excel转成pdf 在pdf 转图片 pdf在转图片上面有就不说了你可以下载jacob-1.15;

  转化思路为excel-pdf-在线文档(html,jsp)等

    //根据时间生成文件名的方法(其实完全可以用uuid生成)public String getDateStr(){Calendar cl = Calendar.getInstance();cl.setTime(new Date());String str = cl.get(Calendar.YEAR) + "" + (cl.get(Calendar.MONTH) + 1) + "" + cl.get(Calendar.DATE) + "" + cl.get(Calendar.HOUR) + "" + cl.get(Calendar.MINUTE) + "" + cl.get(Calendar.SECOND);return str;}

下面为具体转化细节

private String path;public static boolean runFlag = false;public void saveExcelAsPdf(String filePath, String outFile) {ComThread.InitSTA();//根据pid获得ActiveXComponent对象,这个pid对应在你的注册表中,如果没有说明你的电脑上的office//未安装或安装出问题,需要重新安装,否则该程序不能用ActiveXComponent actcom = new ActiveXComponent("Excel.Application");Dispatch excel = null;try {/*** 以下为对excel文档的操作,来自网上的资料笔者亦不懂其中的意思*/System.out.println((new Date()).toString()+ "  start convert from : " + filePath + " to " + outFile);actcom.setProperty("Visible", new Variant(false));Dispatch excels = actcom.getProperty("Workbooks").toDispatch();excel = Dispatch.invoke(excels,"Open",Dispatch.Method,new Object[] { filePath, new Variant(false),new Variant(false) }, new int[9]).toDispatch();Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {outFile, new Variant(57), new Variant(false),new Variant(57), new Variant(57), new Variant(false),new Variant(true), new Variant(57), new Variant(false),new Variant(true), new Variant(false) }, new int[1]);} catch (Exception es) {es.printStackTrace();} finally {Dispatch.call(excel, "Close", new Variant(false));if (actcom != null) {actcom.invoke("Quit", new Variant[] {});actcom = null;}ComThread.Release();}}/*** 该方法批次将excel文档转化为pdf文档,之后pdf文档的显示已经在上面介绍中给出。*/public void listAllFile(){runFlag = true;String fileName = "", appdex = "";File temp = null;try{File[] list = new File(path).listFiles(new FileFilter(){public boolean accept(File pathname){boolean x = false;if (pathname.getName().toLowerCase().endsWith(".xls")){x = true;}return x;}});System.out.println((new Date()).toString() + "  Total Convert File : " + list.length);for (int i = 0; i < list.length; i++){fileName = list[i].getName().substring(0, list[i].getName().indexOf("."));appdex = list[i].getName().substring(list[i].getName().indexOf("."));temp = new File(path + fileName + ".pdf");if (temp.exists()){temp.renameTo(new File(path + fileName + "-" + getDateStr() + ".pdf"));}saveExcelAsPdf(path + fileName + appdex, path + fileName + ".pdf");}} catch (Exception ex){ex.printStackTrace();}runFlag = false;}

  以上为本文的全部内容,虽然山寨的意味很弄,但总归能够实现在线文档的功能,希望以后找到更完美的解决方案再与大家共享。(补充下:这里使用了第三方类库poi 实现excel和word的在线显示,关于对该类库的调用方法还有讲究,下载的dll 文件必须入你的机器类型兼容,也就是要区分好64位和32位的,再有就是你的office一定要装好,并写入到到注册表里,最后就是excel转化pdf的时候需要在本地服务器上安装SaveAsPDFandXPS.exe的插件才能完成相关转换,这个插件可以自行百度下载)。

转载于:https://www.cnblogs.com/wq123/p/3468117.html

在线文档的制作(包含txt,word,pdf,excel的文档类型,一应俱全哦)相关推荐

  1. VSTO 得到Office文档的选中内容(Word、Excel、PPT、Outlook)

    VSTO 得到Office文档的选中内容(Word.Excel.PPT.Outlook) 原文:VSTO 得到Office文档的选中内容(Word.Excel.PPT.Outlook) 目的:得到在W ...

  2. java实现word,pdf,excel,图片添加水印

    gitee项目地址:https://gitee.com/betelnutandwine/meutilswatermark: java实现pdf,word,excel,ppt,图片加水印 jar地址:s ...

  3. html怎么转换到百度,类似百度文库在线预览文档flash版(支持word、excel、ppt、pdf)+在线预览文档html版...

    类似百度文库在线预览文档flash版(支持word.excel.ppt.pdf)+在线预览文档html版 (1).将文档转换为html,只支持支持office文档 (2).将文档转换为flash,实现 ...

  4. 计算机软件制作程序,使用Word和Excel制作模板打印方法_计算机软件和应用程序_IT /计算机_资源...

    使用Word和Excel制作模板A,并打印自我设计证书. 除了一些不固定的信息(例如姓名,等级,科目,奖项,讲师等)之外,其余内容都是固定的. 1.在具有五列的Excel表中创建一个新表,并将标题写在 ...

  5. office@microsoft365@官方在线安装@第三方离线下载并安装(word+ppt+excel)

    文章目录 官方下载@office下载安装 其他(三方)安装途径(离线安装) 版本补充说明 官方下载@office下载安装 Download and install or reinstall Micro ...

  6. json 文档拆分工具_如何把PDF多页文档拆为单页?快看高手私藏实用的技巧

    如何把PDF多页文档拆为单页?有时一份PDF文件页面过多,当我们只想提取部分页面内容时,就需要进行PDF拆分的操作.但很多小伙伴都不知道PDF如何拆分页面,想要拆分PDF文件,首先你得拥有一个PDF拆 ...

  7. Android实现在线预览office文档(Word,Pdf,excel,PPT.txt等格式)

    1.概述 我们都知道,Android原生并没有提供浏览office文档格式的相关Api,在安卓端想要实现在线预览office文档的功能显然很是复杂,我们手机安装QQ浏览器时,在手机打开office文档 ...

  8. java实现在线预览word,excel,ppt文档

    项目中遇到的word文档在线预览需求,查阅很多资料决定利用openoffice转换word文档为pdf进行预览实现. 1.下载openoffice4安装 www.openoffice.org: 2.导 ...

  9. 前端网页预览word,pdf,excel等各类文档

    项目中有需求要在网页上预览word文档,但是使用a标签的话只能预览图片一类的文件,对word只会下载文档不能预览 在网上查了很多资料,有些方法只能支持ie(使用ActiveXObject) 终于发现有 ...

最新文章

  1. 用koa开发一套内容管理系统(CMS),支持javascript和typescript双语言
  2. 10.15 iptables filter表小案例10.16/10.17/10.18 iptables nat表应用
  3. Kafka——性能逆天的存在
  4. 什么样的状态该跳槽了?
  5. mysql必知必会的数据_MySQL必知必会---数据过滤
  6. 旭荣管理软件怎么修改小票内容_水果门店管理系统怎么管理水果门店的
  7. 暨阳社区创始人游牧:为什么我们要转型?
  8. win10下安装php7.2的memcache扩展
  9. 什么是PBR?pbr入门基础干货
  10. KingbaseES V8R6 集群运维系列 -- 命令行部署repmgr管理集群+switchover测试
  11. excel表格计算年龄_在Excel中计算年龄
  12. 如何快速建立一个优秀的账号体系
  13. 多目标跟踪(MOT)数据集资源整理分享
  14. 随心所欲——享受恬淡的心态
  15. 辨别貔貅币的一种代码思路
  16. [转]做个男人,做个成熟的男人,做个有城府的男人
  17. Variational graph auto-encoders (VGAE)
  18. 搭建高性能计算环境(四)、应用软件的安装之VASP
  19. 给初学者的RxJava2.0教程(八)(转载)
  20. matlab仿真与控制应用,控制系统MATLAB仿真与应用

热门文章

  1. F1巴林揭幕阿隆索拔头筹 雷克南一次进站成就季军
  2. 【转】通俗易懂!白话朴素贝叶斯
  3. antv x6基类cell第五讲-文本节点可编辑
  4. C# winFrom中让MessageBox.Show显示到最顶层
  5. 刷酸记录(迪维维A酸乳膏)20190906-0908
  6. iOS后台运行任务的应用
  7. js 日期转换 strToDate
  8. vue-aplayer 音乐播放,实现播放与音乐列表
  9. JAVA:实现二进制转八进制算法(附完整源码)
  10. ffmpeg中av_read_frame 超时设置