1/** 2 * 文档预览 3 * 4 * @param request 5 * @param response 6 * @throws IOException 7 */ 8public void view(HttpServletRequest request, HttpServletResponse response) throws IOException { 9 try { 10 // 你的文档地址 11 String file = "http://view.xdocin.com/doc/preview.docx"; 12 // XDOC文档预览服务地址 13 String xurl = "http://view.xdocin.com/xdoc"; 14 15 // 预览参数 16 Map<String, Object> params = new HashMap<String, Object>(); 17 // 获取预览结果url 18 params.put("_func", "url"); 19 // 结果格式XML 20 params.put("_rformat", "xml"); 21 // 文档地址 22 params.put("_xdoc", file); 23 24 // word文档是否以pdf方式显示,默认false 25 // params.put("_pdf", true); 26 27 // 水印文本,显示水印 28 // params.put("_watermark", "XDOC文档预览"); 29 30 // 是否允许保存PDF,默认true 31 // params.put("_saveable", false); 32 33 // 是否允许打印PDF,默认true 34 // params.put("_printable", false); 35 36 // 是否允许选择复制内容,默认true 37 // params.put("_copyable", false); 38 39 // 是否显示底部工具条,默认true 40 // params.put("_toolbar", false); 41 42 // 自定义标题 43 // params.put("_title", "文档预览"); 44 45 // 预览链接有效期,单位分钟,默认永久有效 46 // params.put("_expire", 30); 47 48 // 组合调用URL 49 StringBuffer sb = new StringBuffer(); 50 sb.append(xurl); 51 Iterator<String> it = params.keySet().iterator(); 52 String key; 53 boolean first = true; 54 while (it.hasNext()) { 55 key = it.next(); 56 sb.append(first ? '?' : '&'); 57 sb.append(java.net.URLEncoder.encode(key, "UTF-8")); 58 sb.append('='); 59 sb.append(java.net.URLEncoder.encode(params.get(key).toString(), "UTF-8")); 60 first = false; 61 } 62 63 // 获取预览结果URL,跳转 64 URL url = new URL(sb.toString()); 65 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 66 factory.setValidating(false); 67 DocumentBuilder builder = factory.newDocumentBuilder(); 68 Document document = builder.parse(url.openStream()); 69 document.getDocumentElement().normalize(); 70 Element root = document.getDocumentElement(); 71 if (root.getAttribute("success").equals("true")) { 72 // 预览结果URL 73 String viewUrl = root.getElementsByTagName("result").item(0).getTextContent(); 74 // 跳转 75 response.sendRedirect(viewUrl); 76 } else { 77 throw new RuntimeException(root.getElementsByTagName("error").item(0).getTextContent()); 78 } 79 } catch (Exception e) { 80 e.printStackTrace(); 81 } 82}
Java在线预览文档最佳实践
Wesley13
2021-10-11
1299 0 0
点赞
收藏
评论区
加载中...