在线预览文档简单例子

我就是我 2022-06-02 23:58 552阅读 0赞

以下是一个Java实现简单浏览器预览服务端文档的例子,文档包括pdf,excel,word,ppt,思路是将excel,word转化为html;将ppt转为图片,再转为html;将pdf以pdf流的形式返回给浏览器,一般的浏览器都支持预览pdf。

maven依赖

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>ooxml-schemas</artifactId>
  4. <version>1.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi</artifactId>
  9. <version>3.15</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.poi</groupId>
  13. <artifactId>poi-ooxml</artifactId>
  14. <version>3.15</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.apache.poi</groupId>
  18. <artifactId>poi-scratchpad</artifactId>
  19. <version>3.15</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>fr.opensagres.xdocreport</groupId>
  23. <artifactId>org.apache.poi.xwpf.converter.core</artifactId>
  24. <version>1.0.4</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>fr.opensagres.xdocreport</groupId>
  28. <artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
  29. <version>1.0.4</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.apache.xmlbeans</groupId>
  33. <artifactId>xmlbeans</artifactId>
  34. <version>2.5.0</version>
  35. </dependency>

预览pdf

  1. byte[] datas = readFile(f);
  2. response.setContentType("application/pdf");
  3. response.setContentLength(datas.length);
  4. OutputStream os = res.getOutputStream();
  5. os.write(datas, 0, datas.length);
  6. os.flush();
  7. os.close();

预览页面

将转为html或者图片的文档,嵌入此html中返回给浏览器展示。

  1. private static final StringBuilder ORIGIN_HTML = new StringBuilder("<!DOCTYPE html>\n" +
  2. "<html lang=\"en\">\n" +
  3. "<head>\n" +
  4. " <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />\n" +
  5. " <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
  6. " <title>预览</title>\n" +
  7. " <link rel=\"stylesheet\" href=\"/resource/css/simple.slide.css\">\n" +
  8. " <link rel=\"stylesheet\" href=\"/resource/css/preview.css\">\n" +
  9. " <script type=\"text/javascript\" src=\"../../resource/jquery-1.9.0.min.js\"></script>\n" +
  10. " <script type=\"text/javascript\" src=\"/resource/simple.slide.js\"></script>\n" +
  11. " <script type=\"text/javascript\">\n" +
  12. " $(function(){\n" +
  13. " $(\".pptimage\").simpleSlide();\n" +
  14. " });\n" +
  15. " </script>\n" +
  16. "</head>\n" +
  17. "<body>\n" +
  18. " ####\n" +
  19. "</body>\n" +
  20. "</html>");

word07转为html

  1. public static void doc07ToHtml(String from, OutputStream out, String imagePath){
  2. try{
  3. Map<String, String> map = new HashMap<String, String>();
  4. //1.如果图片文件夹存在,删除重新创建之
  5. File imagePathFile = new File(imagePath);
  6. if(imagePathFile.exists()) {
  7. FileUtils.deleteDirectory(imagePathFile);
  8. }
  9. imagePathFile.mkdirs();
  10. FileInputStream fis = new FileInputStream(from);
  11. XWPFDocument doc = new XWPFDocument(fis);
  12. XHTMLOptions options = XHTMLOptions.create();
  13. options.setExtractor(new IImageExtractor() {
  14. @Override
  15. public void extract(String imagePath1, byte[] imageData) throws IOException {
  16. //2.处理文件后缀
  17. String suf = "";
  18. if(imagePath1.lastIndexOf(".") > 0) {
  19. suf = imagePath1.substring(imagePath1.lastIndexOf("."), imagePath1.length());
  20. }
  21. //3.写文件,并将文件对应关系存入map
  22. String tempFile = imagePath+File.separator+UuidUtil.getUUID()+suf;
  23. File f = new File(tempFile);
  24. FileUtils.writeByteArrayToFile(f, imageData);
  25. map.put(imagePath1, tempFile);
  26. }});
  27. options.setIgnoreStylesIfUnused(false);
  28. options.setFragment(true);
  29. options.URIResolver(new IURIResolver() {
  30. @Override
  31. public String resolve(String arg0) {
  32. if(map.containsKey(arg0)) {
  33. String u = map.get(arg0);
  34. if(!XaUtil.isEmpty(u)){
  35. try {
  36. u = URLEncoder.encode(u,"ISO-8859-1");
  37. } catch (UnsupportedEncodingException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. return "/sys/filemanage/getViewImage.do?id="+u;
  42. }
  43. return arg0;
  44. }
  45. });
  46. ByteArrayOutputStream os = new ByteArrayOutputStream();
  47. XHTMLConverter.getInstance().convert(doc, os, options);
  48. byte[] datas = os.toByteArray();
  49. os.close();
  50. //处理表格没有边框
  51. String content = new String(datas,"utf-8");
  52. content = ORIGIN_HTML.toString().replaceAll("####",content);
  53. datas = content.getBytes("utf-8");
  54. out.write(datas, 0, datas.length);
  55. out.flush();
  56. out.close();
  57. }catch(Exception e){
  58. log.error("",e);
  59. }
  60. }

word03转为html

  1. public static void doc03ToHtml(String from, OutputStream out, String imagePath)throws Exception{
  2. try{
  3. //1.如果图片文件夹存在,删除重新创建之
  4. File imagePathFile = new File(imagePath);
  5. if(imagePathFile.exists()) {
  6. FileUtils.deleteDirectory(imagePathFile);
  7. }
  8. imagePathFile.mkdirs();
  9. FileInputStream fis = new FileInputStream(from);
  10. HWPFDocument doc = new HWPFDocument(fis);
  11. WordToHtmlConverter converter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
  12. converter.setPicturesManager(new PicturesManager() {
  13. @Override
  14. public String savePicture(byte[] arg0, PictureType arg1, String arg2, float arg3, float arg4) {
  15. //2.处理文件后缀
  16. String suf = "";
  17. if(arg2.lastIndexOf(".") > 0) {
  18. suf = arg2.substring(arg2.lastIndexOf("."), arg2.length());
  19. }
  20. //3.写文件,并将文件对应关系存入map
  21. String tempFile = imagePath+File.separator+UuidUtil.getUUID()+suf;
  22. File f = new File(tempFile);
  23. try {
  24. FileUtils.writeByteArrayToFile(f, arg0);
  25. } catch (IOException e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. }
  29. if(!XaUtil.isEmpty(tempFile)){
  30. try {
  31. tempFile = URLEncoder.encode(tempFile,"ISO-8859-1");
  32. } catch (UnsupportedEncodingException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. return "/sys/filemanage/getViewImage.do?id="+tempFile;
  37. }
  38. });
  39. converter.processDocument(doc);
  40. Document htmlDocument = converter.getDocument();
  41. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  42. DOMSource domSource = new DOMSource(htmlDocument);
  43. StreamResult streamResult = new StreamResult(outStream);
  44. TransformerFactory tf = TransformerFactory.newInstance();
  45. Transformer serializer = tf.newTransformer();
  46. serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
  47. serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  48. serializer.setOutputProperty(OutputKeys.METHOD, "html");
  49. serializer.transform(domSource, streamResult);
  50. outStream.close();
  51. byte[] datas = outStream.toByteArray();
  52. //处理表格没有边框
  53. String content = new String(datas,"utf-8");
  54. content = ORIGIN_HTML.toString().replaceAll("####",content);
  55. datas = content.getBytes("utf-8");
  56. out.write(datas, 0, datas.length);
  57. out.flush();
  58. out.close();
  59. }catch(Exception e){
  60. log.error("",e);
  61. }
  62. }

Excel转为html

  1. public static void exceToHtml(String from, OutputStream out){
  2. InputStream in = null;
  3. XSSFWorkbook xwb = null;
  4. HSSFWorkbook hwb= null;
  5. try{
  6. in = new FileInputStream(from);
  7. Workbook wb = WorkbookFactory.create(in);
  8. if(wb instanceof XSSFWorkbook) {
  9. xwb = (XSSFWorkbook) wb;
  10. hwb = new HSSFWorkbook();
  11. ConvertXSSF2HSSF c = new ConvertXSSF2HSSF();
  12. c.transformXSSF(xwb, hwb);
  13. }else{
  14. hwb = (HSSFWorkbook) wb;
  15. }
  16. ExcelToHtmlConverter converter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
  17. converter.processWorkbook(hwb);
  18. wb.close();
  19. Document htmlDocument = converter.getDocument();
  20. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  21. DOMSource domSource = new DOMSource (htmlDocument);
  22. StreamResult streamResult = new StreamResult (outStream);
  23. TransformerFactory tf = TransformerFactory.newInstance();
  24. Transformer serializer = tf.newTransformer();
  25. serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8");
  26. serializer.setOutputProperty (OutputKeys.INDENT, "yes");
  27. serializer.setOutputProperty (OutputKeys.METHOD, "html");
  28. serializer.transform (domSource, streamResult);
  29. outStream.close();
  30. String content = new String (outStream.toByteArray(),"utf-8" );
  31. content = ORIGIN_HTML.toString().replaceAll("####",content);
  32. byte[] datas = content.getBytes("utf-8");
  33. out.write(datas,0,datas.length);
  34. out.flush();
  35. out.close();
  36. }catch (Exception e){
  37. log.error("",e);
  38. }finally {
  39. try {
  40. if(null != in){
  41. in.close();
  42. }
  43. if(null != xwb){
  44. xwb.close();
  45. }
  46. if(null != hwb){
  47. hwb.close();
  48. }
  49. } catch (IOException e) {
  50. log.error("",e);
  51. }
  52. }
  53. }

ppt07转为图片

  1. public static String ppt07ToImage(String from, String images) {
  2. StringBuilder sb = new StringBuilder();
  3. FileInputStream fis = null;
  4. XMLSlideShow ppt = null;
  5. FileOutputStream fos = null;
  6. try {
  7. // 1.如果图片文件夹存在,删除重新创建之
  8. File imagePathFile = new File(images);
  9. if (imagePathFile.exists()) {
  10. FileUtils.deleteDirectory(imagePathFile);
  11. }
  12. imagePathFile.mkdirs();
  13. fis = new FileInputStream(from);
  14. ppt = new XMLSlideShow(fis);
  15. Dimension pageSize = ppt.getPageSize();
  16. List<XSLFSlide> slides = ppt.getSlides();
  17. String xmlFontFormat = "<xml-fragment xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\">"
  18. + "<a:rPr lang=\"zh-CN\" altLang=\"en-US\" dirty=\"0\" smtClean=\"0\"> "
  19. + "<a:latin typeface=\"+mj-ea\"/> " + "</a:rPr>" + "</xml-fragment>";
  20. int index = 0;
  21. for (XSLFSlide slide : slides) {
  22. CTSlide cts = slide.getXmlObject();
  23. CTGroupShape groupShape = cts.getCSld().getSpTree();
  24. List<CTShape> shapeList = groupShape.getSpList();
  25. for (CTShape ctShape : shapeList) {
  26. CTTextBody oneCTTextBody = ctShape.getTxBody();
  27. if (null == oneCTTextBody) {
  28. continue;
  29. }
  30. CTTextParagraph[] oneCTTextParagraph = oneCTTextBody.getPArray();
  31. CTTextFont oneCTTextFont = null;
  32. oneCTTextFont = CTTextFont.Factory.parse(xmlFontFormat);
  33. for (CTTextParagraph ctTextParagraph : oneCTTextParagraph) {
  34. CTRegularTextRun[] onrCTRegularTextRunArray = ctTextParagraph.getRArray();
  35. for (CTRegularTextRun ctRegularTextRun : onrCTRegularTextRunArray) {
  36. CTTextCharacterProperties oneCTTextCharacterProperties = ctRegularTextRun.getRPr();
  37. oneCTTextCharacterProperties.setLatin(oneCTTextFont);
  38. }
  39. }
  40. }
  41. // 创建BufferedImage 对象,图像尺寸为原来的PPT的每页尺寸
  42. BufferedImage oneBufferedImage = new BufferedImage(pageSize.width, pageSize.height,
  43. BufferedImage.TYPE_INT_RGB);
  44. Graphics2D oneGraphics2D = oneBufferedImage.createGraphics();
  45. // 将PPT文件中的每个页面中的相关内容画到转换后的图片中
  46. slides.get(index).draw(oneGraphics2D);
  47. /**
  48. * 设置图片的存放路径和图片格式,注意生成的文件路径为绝对路径,最终获得各个图像文件所对应的输出流的对象
  49. */
  50. String imgName = images + File.separator + UuidUtil.getUUID() + ".jpg";
  51. sb.append(imgName + ",");
  52. fos = new FileOutputStream(imgName);
  53. ImageIO.write(oneBufferedImage, "jpg", fos);
  54. index++;
  55. }
  56. } catch (Exception e) {
  57. e.printStackTrace();
  58. }finally {
  59. try {
  60. if(null != fis) {
  61. fis.close();
  62. }
  63. if(null != ppt) {
  64. ppt.close();
  65. }
  66. if(null != fos){
  67. fos.close();
  68. }
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. }
  73. return sb.toString();
  74. }

ppt03转为图片

  1. public static String ppt03ToImage(String from, String images) {
  2. StringBuilder sb = new StringBuilder();
  3. FileInputStream fis = null;
  4. FileOutputStream fos = null;
  5. HSLFSlideShow ppt = null;
  6. try {
  7. // 1.如果图片文件夹存在,删除重新创建之
  8. File imagePathFile = new File(images);
  9. if (imagePathFile.exists()) {
  10. FileUtils.deleteDirectory(imagePathFile);
  11. }
  12. imagePathFile.mkdirs();
  13. fis = new FileInputStream(from);
  14. ppt = new HSLFSlideShow(fis);
  15. // 获取PPT每页的大小(宽和高度)
  16. Dimension onePPTPageSize = ppt.getPageSize();
  17. // 获得PPT文件中的所有的PPT页面(获得每一张幻灯片),并转为一张张的播放片
  18. List<HSLFSlide> pptPageSlideList = ppt.getSlides();
  19. // 下面循环的主要功能是实现对PPT文件中的每一张幻灯片进行转换和操作
  20. for (int i = 0; i < pptPageSlideList.size(); i++) {
  21. // 这几个循环只要是设置字体为宋体,防止中文乱码,
  22. List<List<HSLFTextParagraph>> oneTextParagraphs = pptPageSlideList.get(i).getTextParagraphs();
  23. for (List<HSLFTextParagraph> list : oneTextParagraphs) {
  24. for (HSLFTextParagraph hslfTextParagraph : list) {
  25. List<HSLFTextRun> HSLFTextRunList = hslfTextParagraph.getTextRuns();
  26. for (int j = 0; j < HSLFTextRunList.size(); j++) {
  27. /*
  28. * 如果PPT在WPS中保存过,则 HSLFTextRunList.get(j).getFontSize();的值为0或者26040,
  29. * 因此首先识别当前文本框内的字体尺寸是否为0或者大于26040,则设置默认的字体尺寸。
  30. *
  31. */
  32. // 设置字体大小
  33. Double size = HSLFTextRunList.get(j).getFontSize();
  34. if ((size <= 0) || (size >= 26040)) {
  35. HSLFTextRunList.get(j).setFontSize(20.0);
  36. }
  37. // 设置字体样式为宋体
  38. // String family=HSLFTextRunList.get(j).getFontFamily();
  39. // HSLFTextRunList.get(j).setFontFamily("宋体");
  40. int index = HSLFTextRunList.get(j).getFontIndex();
  41. String name = HSLFTextRunList.get(j).getFontFamily();
  42. HSLFTextRunList.get(j).setFontIndex(1);
  43. HSLFTextRunList.get(j).setFontFamily("宋体");
  44. log.info("ppt info:"+HSLFTextRunList.get(j).getRawText());
  45. }
  46. }
  47. }
  48. /**
  49. * 创建BufferedImage对象,图像的尺寸为原来的每页的尺寸
  50. */
  51. BufferedImage oneBufferedImage = new BufferedImage(onePPTPageSize.width, onePPTPageSize.height,
  52. BufferedImage.TYPE_INT_RGB);
  53. Graphics2D oneGraphics2D = oneBufferedImage.createGraphics();
  54. /**
  55. * 设置转换后的图片背景色为白色
  56. *
  57. */
  58. oneGraphics2D.setPaint(Color.white);
  59. oneGraphics2D.fill(new Rectangle2D.Float(0, 0, onePPTPageSize.width, onePPTPageSize.height));
  60. pptPageSlideList.get(i).draw(oneGraphics2D);
  61. /**
  62. * 设置图片的存放路径和图片格式
  63. */
  64. String imgName = images + File.separator + UuidUtil.getUUID() + ".jpg";
  65. sb.append(imgName);
  66. sb.append(",");
  67. fos = new FileOutputStream(imgName);
  68. /**
  69. * 图片文件保存的指定的目录中
  70. */
  71. ImageIO.write(oneBufferedImage, "jpg", fos);
  72. }
  73. } catch (Exception e) {
  74. e.printStackTrace();
  75. } finally {
  76. try {
  77. if(null != fis) {
  78. fis.close();
  79. }
  80. if(null != ppt) {
  81. ppt.close();
  82. }
  83. if(null != fos){
  84. fos.close();
  85. }
  86. } catch (IOException e) {
  87. e.printStackTrace();
  88. }
  89. }
  90. return sb.toString();
  91. }

(完)

发表评论

表情:
评论列表 (有 0 条评论,552人围观)

还没有评论,来说两句吧...

相关阅读

    相关 文件在线

    浏览器并不能支持word、excel文件的在线预览,所以都是将word、excel转换为浏览器能直接看的文件格式(html、pdf、txt、png、svg、flash),因此在