队列设计

/**  * @ClassName ConvertQueue* @Description TODO(文件转换PDF的队列)* @author feizhou* @Date 2018年4月18日 下午1:49:13* @version 1.0.0* @param <T>*/
public class ConvertQueue<T>  {private   LinkedList<T> queue=new LinkedList<T>();private   Boolean isHavaRun=true;public   Boolean getIsHavaRun() {return isHavaRun;
}public   void setIsRun(Boolean isHavaRun) {this.isHavaRun = isHavaRun;
}public LinkedList<T> getQueue() {return queue;
}public ConvertQueue() {super();if(StringUtil.isEmpty(queue)){queue=new LinkedList<T>();}
}//返回队列的长度
public int size() {if(StringUtil.isEmpty(queue)){//如果队列是null返回0return 0;}else{return queue.size();}
}//判断队列是否是null
public boolean isEmpty() {return StringUtil.isEmpty(queue);
}//判断是否包含某个对象
public boolean contains(T o) {return queue.contains(o);
}//清空队列的所有元素public void clear() {queue.clear();
}//删除头部元素,并返回
public T removeHead() {if(this.isEmpty()){return null;}else{return queue.removeFirst();}
}//删除指定元素,返回boolean主
public boolean removeObject(T t) {return queue.remove(t);
}
//删除最后元素,并返回
public T removeLast(T t) {return queue.removeLast() ;
}
//添加元素到尾部
public boolean addTail(T e) {return queue.add(e);
}//添加元素到头部
public void addHead(T e) {queue.add(0, e);
}//获取头部元素
public synchronized T getHead() {return queue.removeFirst();
}
//获取尾部元素
public T getTail() {return queue.removeLast();
}//获取添加一个队列
public void addQueue(LinkedList<T> q) {queue.addAll(q);
}}

队列继承设计


/**  * @ClassName UnConvertQueue* @Description TODO(正在执行转换的队列)* @author feizhou* @Date 2018年4月18日 上午11:49:31* @version 1.0.0*/
public class RunConvertQueue extends ConvertQueue<FileToPDF>{@Autowiredprivate ErrorConvertQueue errorConvertQueue;//转换策略:小文件优先转换策略 Apublic RunConvertQueue minFilePrecedenceStrategy(){Collections.sort(this.getQueue(), new Comparator<FileToPDF>() {@Overridepublic int compare(FileToPDF s1, FileToPDF s2) {return    (int) (s1.getSize()-s2.getSize());}});return this;}//转换策略:最早上传转换策略 Bpublic RunConvertQueue FiFoStrategy(){Collections.sort(this.getQueue(), new Comparator<FileToPDF>() {@Overridepublic int compare(FileToPDF s1, FileToPDF s2) {return    s1.getCreateDate().compareTo(s2.getCreateDate());}});return this;}//转换策略:BApublic RunConvertQueue FiFoAndMinFileStrategy(){Collections.sort(this.getQueue(), new Comparator<FileToPDF>() {@Overridepublic int compare(FileToPDF s1, FileToPDF s2) {//按时间排序int num1= s1.getCreateDate().compareTo(s2.getCreateDate());////如果时间相同,按大小排序int num2=num1==0?(int) (s1.getSize()-s2.getSize()):num1;return num2;}});return this;}//转换策略:ABpublic RunConvertQueue MinAndFifoFileStrategy(){Collections.sort(this.getQueue(), new Comparator<FileToPDF>() {@Overridepublic int compare(FileToPDF s1, FileToPDF s2) {//按大小排序int num1= (int) (s1.getSize()-s2.getSize());////如果大小相同,按时间排序int num2=num1==0?(s1.getCreateDate().compareTo(s2.getCreateDate())):num1;return num2;}});return this;}//转换策略:x文件最先转换public RunConvertQueue  appointFilePrecedenceStrategy(FileToPDF fileToPDF){//获取队列头部FileToPDF head = this.getHead();//如果该头部任务正在转换,删除头部,添加新任务//如果该头部还没有转换,添加新任务if(head.getIsRunConvert()){//正在转换FileToPDF removeHead = this.removeHead();removeHead.setIsRunConvert(false);errorConvertQueue.addTail(removeHead);} this.addHead(fileToPDF);return this;}
}
/**  * @ClassName UnConvertQueue* @Description TODO(转换错误或者超时的队列)* @author feizhou* @Date 2018年4月18日 上午11:49:31* @version 1.0.0*/
public class ErrorConvertQueue extends ConvertQueue<FileToPDF> {}

任务调度设计
xml配置

bean配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><bean id="fileToHTML" class="cn.xiniu.common.fileToHtml.FileToHTMLImpl"/><bean id="fileToOnline" class="cn.xiniu.common.fileToHtml.FileToOnlineimpl"  scope="prototype"/><bean id="errorConvertQueue" class="cn.xiniu.common.fileToHtml.queue.ErrorConvertQueue" scope="singleton"/><bean id="runConvertQueue" class="cn.xiniu.common.fileToHtml.queue.RunConvertQueue" scope="singleton"/><bean id="unConvertQueue" class="cn.xiniu.common.fileToHtml.queue.UnConvertQueue" scope="singleton"/>
</beans>

任务调度配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:task="http://www.springframework.org/schema/task"xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-3.2.xsd"><task:annotation-driven/><!-- <context:component-scan base-package="cn.xxxx.xxx.task" /> -->
</beans>

任务调度代码


/**  * @ClassName FileToPDFTask* @Description TODO(这里用一句话描述这个类的作用)* @author feizhou* @Date 2018年4月18日 下午4:52:27* @version 1.0.0*/
@Component
public class FileToPDFTask {@Autowiredprivate RunConvertQueue runConvertQueue;@Autowiredprivate ErrorConvertQueue  errorConvertQueue;@Autowiredprivate FileToPDFDao  fileToPDFDao;@Autowiredprivate FileToOnline fileToOnline;//   @Scheduled(cron="* */3 * * * ?") //每3分钟执行1次   @Scheduled(cron = "0  0/3 * * * ?")//每隔60秒执行一次,给测试用public void FileToPDF(){//生成正在转换队列的数据generateRunConvertQueue();SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(this.hashCode()+"---"+time.format(new Date()));if(errorConvertQueue.isEmpty()&&runConvertQueue.isEmpty()){//关闭任务调度}else{//单线程
//           fileToPDFHandler();//多线程fileToOnline.multiThreadingFileToPDF(Constans.FILETOPDF_DEFALUT_RUNCOUNT);}}//生成正在转换队列的数据public   void generateRunConvertQueue(){Map<String, Object> map=new HashMap<String, Object>();map.put("errorCountLt", Constans.FILETOPDF_DEFALUT_ERRORCOUNT);//获取所有失败次数小于最大失败次数的附件//获取附件临时表数据List<FileToPDF> fileToPdfs=fileToPDFDao.findFileUploadDetailTemp(map);//建附件添加到正在执行的队列中for (FileToPDF fileToPDF : fileToPdfs) {runConvertQueue.addTail(fileToPDF);}}//单线程public void fileToPDFHandler(){while(true){Integer i = fileToOnline.singleThreadingFileToPDFTask(null);if(i==2){break;}}}
}

主要接口

/*** * @ClassName FileToOnline* @Description TODO(文件在线预览)* @author feizhou* @Date 2018年3月21日 上午11:13:44* @version 1.0.0*/
public interface FileToOnline {/*** * @Description (文件转PDF)* @author feizhou* @Date 2018年3月21日上午11:14:12  * @version 1.0.0* @param getoutPutUrl* @return* @throws IOException*/public void fileToPDF(Map<String, String> getoutPutUrl) throws IOException;/*** EXCEL转pdf自动缩放。* @param rootSourceFilePath* @param globalVariable*/public  Boolean  excel2PDF(Map<String, String> getoutPutUrl) ;/*** * @Description (单线程,用于任务调度,文件转PDF)* @author feizhou* @Date 2018年4月20日下午4:38:47  * @version 1.0.0* @return* return 1:重新执行* return 2:关闭任务调度* return 3;文件转换失败* return 4;文件转换成功   */public Integer singleThreadingFileToPDFTask(FileToPDF fileToPDF);/*** * @Description (多线程文件转PDF)* @author feizhou* @Date 2018年4月20日下午5:44:21  * @version 1.0.0* @return */public void multiThreadingFileToPDF(Integer threadCount);
}

接口实现

public class FileToOnlineimpl implements FileToOnline {private final Logger logger = Logger.getLogger(FileToPDFTask.class);  @Autowiredprivate RunConvertQueue runConvertQueue;@Autowiredprivate ErrorConvertQueue  errorConvertQueue;@Autowiredprivate FileToPDFDao  fileToPDFDao;@Autowiredprivate FileToHTML fileToHTML;/*** * @Description (文件转PDf)* @author feizhou* @Date 2018年3月21日上午11:15:29  * @version 1.0.0* @param getoutPutUrl* @return true,false* @throws IOException*/public    void   fileToPDF(Map<String, String> getoutPutUrl) throws IOException {String port=getoutPutUrl.get("port");
//          Boolean isSuccess=true;String pdfUrl=getoutPutUrl.get("pdfUrl");String htmlParentUrl=getoutPutUrl.get("htmlParentUrl");String inputFileUrl=getoutPutUrl.get("fileFullName");String postfix=getoutPutUrl.get("postfix");//文件输入流FileInputStream  fromFileInputStream = new FileInputStream(new File(inputFileUrl));Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");String timesuffix = sdf.format(date);//转换文件名称String docFileName =timesuffix +postfix;//文件输出流File htmlOutputFile = new File(pdfUrl);//转换转扣除File docInputFile = new File(htmlParentUrl + File.separatorChar + docFileName);//创建文件if (htmlOutputFile.exists())htmlOutputFile.delete();htmlOutputFile.createNewFile();if (docInputFile.exists())docInputFile.delete();docInputFile.createNewFile();/*** 由fromFileInputStream构建输入文件*/OutputStream os =null;try {os = new FileOutputStream(docInputFile);int bytesRead = 0;byte[] buffer = new byte[1024 * 8];while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {os.write(buffer, 0, bytesRead);}}
//          catch (IOException e) {//              e.printStackTrace();
//              isSuccess =false;
//          }finally {if(os!=null){os.close();}if(fromFileInputStream!=null){fromFileInputStream.close();}}
//          String command = Constans.OPENOFFICE_HOME + "/soffice --headless --accept=\"socket,host=127.0.0.1,port="+port+";urp;\" --nofirststartwizard";
//          Process pro = Runtime.getRuntime().exec(command);OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", Integer.valueOf(port));try {connection.connect();// convertDocumentConverter converter = new OpenOfficeDocumentConverter(connection);converter.convert(docInputFile, htmlOutputFile);}
//          catch (ConnectException e) {//              e.printStackTrace();
//              isSuccess =false;
//          }finally{if(connection!=null){connection.disconnect();// 关闭OpenOffice服务的进程
//                     pro.destroy();// 转换完之后删除word文件docInputFile.delete();}}
//          return isSuccess;}/*** EXCEL转pdf自动缩放。* @param rootSourceFilePath* @param globalVariable*/public  synchronized  Boolean  excel2PDF(Map<String, String> getoutPutUrl) {String destFile=getoutPutUrl.get("pdfUrl");String sourceFile=getoutPutUrl.get("fileFullName");XComponentLoader xComponentLoader=null;Object doc=null;String  OpenOffice_HOME=Constans.OPENOFFICE_HOME;try {// 调用OpenOffice的BootstrapSocketConnectorXComponentContext xRemoteContext = BootstrapSocketConnector.bootstrap(OpenOffice_HOME);XMultiComponentFactory xRemoteServiceManager = xRemoteContext.getServiceManager();Object desktop = xRemoteServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xRemoteContext);xComponentLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, desktop);PropertyValue[] loadProps = new PropertyValue[1];loadProps[0] = new PropertyValue();loadProps[0].Name = "Hidden";loadProps[0].Value = new Boolean(true);doc = xComponentLoader.loadComponentFromURL("file:///"+sourceFile, "_blank", 0,loadProps);XSpreadsheetDocument xSpreadsheetDocument = (XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class,doc);com.sun.star.style.XStyleFamiliesSupplier xFamiliesSupplier =(com.sun.star.style.XStyleFamiliesSupplier) UnoRuntime.queryInterface(com.sun.star.style.XStyleFamiliesSupplier.class, xSpreadsheetDocument);com.sun.star.container.XNameAccess xFamiliesNA = xFamiliesSupplier.getStyleFamilies();Object aPageStylesObj = xFamiliesNA.getByName("PageStyles");com.sun.star.container.XNameContainer xPageStylesNA = (com.sun.star.container.XNameContainer)UnoRuntime.queryInterface(com.sun.star.container.XNameContainer.class, aPageStylesObj);String []stylename=xPageStylesNA.getElementNames();for(int j=0;j<stylename.length;j++){Object style=xPageStylesNA.getByName(stylename[j]);com.sun.star.style.XStyle xPageStyleNA = (com.sun.star.style.XStyle)UnoRuntime.queryInterface(com.sun.star.style.XStyle.class, style);if(xPageStyleNA.isInUse()){XPropertySet xPropSet = (XPropertySet)UnoRuntime. queryInterface(XPropertySet.class, xPageStyleNA);try{xPropSet.setPropertyValue("ScaleToPages", new Short((short)1));}catch(Exception e1){e1.printStackTrace();}}}//转化// Preparing properties for converting the documentPropertyValue[] propertyValues = new PropertyValue[2];// Setting the flag for overwritingpropertyValues[0] = new PropertyValue();propertyValues[0].Name = "Overwrite";propertyValues[0].Value = new Boolean(true);// Setting the filter namepropertyValues[1] = new PropertyValue();propertyValues[1].Name = "FilterName";propertyValues[1].Value = "writer_pdf_Export";// Composing the URL by replacing all backslashsFile outputFile = new File(destFile);String outputUrl = "file:///" + outputFile.getAbsolutePath().replace('\\', '/');// Getting an object that will offer a simple way to store// a document to a URL.XStorable storable = (XStorable) UnoRuntime.queryInterface(XStorable.class, doc);// Storing and converting the documentstorable.storeToURL(outputUrl, propertyValues);return true;} catch (Exception e) {e.printStackTrace();return false;}finally {if(doc!=null){XComponent component = (XComponent) UnoRuntime.queryInterface(XComponent.class, doc);component.dispose();}}}//多线程文件转PDFpublic void multiThreadingFileToPDF(Integer threadCount){//创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。ExecutorService es= Executors.newFixedThreadPool(threadCount);//提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。 ThreadPoolExecutor pool = (ThreadPoolExecutor)es;while (true) {//获取队列的头部//队列非空,且没有正在执行if(!runConvertQueue.isEmpty()&&!runConvertQueue.getIsHavaRun()){//获取活动的线程数量int activeCount = pool.getActiveCount();if(activeCount<Constans.FILETOPDF_DEFALUT_RUNCOUNT){//线程池有空闲    FileToPDF head = runConvertQueue.getHead();es.submit(new FileToPDFThread(head));} }else{System.out.println("任务结束,关闭多线程");//设置队列没有正在运行的任务runConvertQueue.setIsRun(false);//启动一次顺序关闭,执行以前提交的任务,但不接受新任务。 es.shutdown();break;}}}//单线程文件转PDFpublic Integer singleThreadingFileToPDFTask(FileToPDF fileToPDF){
//           return 1:重新执行
//           return 2:关闭任务调度
//           return 3;文件转换失败
//           return 4;文件转换成功//拿出队列头部元素String inputFileUrl=null;if(fileToPDF==null){fileToPDF = runConvertQueue.getHead();}if(StringUtil.isEmpty(fileToPDF)){//正在执行的队列为空//把错误队列的数据给正在执行队列if( !errorConvertQueue.isEmpty()){runConvertQueue.addQueue(errorConvertQueue.getQueue());return 1;}else{//错误队列和正在执行的队列都没有数据,结束任务调度return 2;}}else{//正在执行的队列非空inputFileUrl=fileToPDF.getSavePath();}//生成文件的绝对路径String fileFullName=fileToHTML.generateInputFileAbsolutePath(inputFileUrl);//生成输出文件的信息Map<String, String> outPutInfo = fileToHTML.getOutPutInfo(fileFullName);File file = new File(outPutInfo.get("pdfUrl"));//判断文件是否生成if(!file.exists()){try {//生成端口号String port = fileToHTML.togeneratePortForOpenOffice();outPutInfo.put("port", port);fileToHTML.togeneratePDFByPostfix(outPutInfo);//没有报错误,删除附件临时表的数据fileToPDFDao.deleteFileUploadDetailTemp(fileToPDF);} catch (Exception e) {//转换失败处理logger.error(e.getMessage());//添加到错误队列errorConvertQueue.addTail(fileToPDF);//更新错误次数Integer errorCount=fileToPDF.getErrorCount();fileToPDF.setErrorCount(errorCount+1);//更新附件临时表错误次数fileToPDFDao.updateFileUploadDetailTemp(fileToPDF);//删除在硬盘的文件String path=outPutInfo.get("htmlParentUrl");FileOperationTool.delDirectoryIncludeDirectory(path);//向上抛异常return 3;}}else{//文件已经生成//删除附件临时表的数据fileToPDFDao.deleteFileUploadDetailTemp(fileToPDF);}return 4;
}}

线程设计


/**  * @ClassName FileToPDFThread* @Description TODO(这里用一句话描述这个类的作用)* @author feizhou* @Date 2018年4月20日 下午4:53:09* @version 1.0.0*/
public class FileToPDFThread implements Runnable {private FileToPDF fileToPDF;public FileToPDFThread(FileToPDF fileToPDF) {super();this.fileToPDF = fileToPDF;}@Overridepublic void run() {//实力话新的fileToOnlineWebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();FileToOnline fileToOnline = (FileToOnline)context.getBean("fileToOnline");Integer i=0;try {System.out.println("当前的线程是:"+Thread.currentThread().getName()+"--当前bean:"+fileToOnline);i = fileToOnline.singleThreadingFileToPDFTask(fileToPDF);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}System.out.println("当前的线程是:"+Thread.currentThread().getName()+"--断电测试:"+i);}}

在线预览底层转换接口

/*** * @ClassName FileToHTML* @Description TODO(在线预览底层转换)* @author feizhou* @Date 2018年4月23日 上午10:13:40* @version 1.0.0*/
public interface FileToHTML  {/*** * @Description (文件转PDF)* @author feizhou* @Date 2018年3月21日上午11:21:24  * @version 1.0.0* @param getoutPutUrl* @throws TransformerException* @throws IOException* @throws ParserConfigurationException*/public  void fileToPDF(Map<String, String> getoutPutUrl) throws IOException;/*** * @Description (输出PDf)* @author feizhou* @Date 2018年3月21日上午11:38:58  * @version 1.0.0* @param fileFullName* @return* @throws Exception*/public   Map<String, String> generatePDF(String fileFullName) throws Exception;/*** * @Description (excel文件转PDF)* @author feizhou* @Date 2018年3月21日上午11:21:24  * @version 1.0.0* @param getoutPutUrl* @throws TransformerException* @throws IOException* @throws ParserConfigurationException*/public  void excelToPDF(Map<String, String> getoutPutUrl) throws IOException;/*** * @Description (通过源文件目录,生成目标文件信息)* @author feizhou* @Date 2018年4月19日下午4:14:25  * @version 1.0.0* @param inputFileUrl* @return*/public Map<String, String> getOutPutInfo(String inputFileUrl) ;/*** * @Description (生成文件在服务器中的绝对路径)* @author feizhou* @Date 2018年4月19日下午4:27:04  * @version 1.0.0* @param inputFileUrl 文件的url* @return*/public String generateInputFileAbsolutePath(String inputFileUrl);/*** * @Description (通过后缀名,适配不同的文件转换)* @author feizhou* @Date 2018年2月7日 上午9:17:20* @version 1.0.0* @param postfix* @param getoutPutUrl* @throws Exception*/public void togeneratePDFByPostfix(Map<String, String> getoutPutUrl) throws Exception;/*** * @Description (生成openOfffice的端口)* @author feizhou* @Date 2018年4月19日下午5:59:52  * @version 1.0.0* @param getoutPutUrl* @return* @throws Exception*/public String togeneratePortForOpenOffice() throws Exception;}

在线预览底层转换实现


/*** * @ClassName FileToHTMLImpl* @Description TODO(文件转换PDF)* @author feizhou* @Date 2018年4月18日 上午11:28:36* @version 1.0.0*/public class FileToHTMLImpl implements FileToHTML{private  static List<Integer> ports=new ArrayList<Integer>();//静态属性,对象共享@Autowiredprivate FileToOnline fileToOnline;@Autowiredprivate DataDictionaryService dataDictionaryService;@Overridepublic Map<String, String> generatePDF(String inputFileUrl) throws Exception {// TODO Auto-generated method stubString  fileFullName=generateInputFileAbsolutePath(inputFileUrl);Map<String, String> outPutInfo = this.getOutPutInfo(fileFullName);//生成端口号String port = this.togeneratePortForOpenOffice();outPutInfo.put("port", port);String pdfUrl = outPutInfo.get("pdfUrl");// 1判断文件是否存在,如果不存在,创建对应的html文件File file = new File(pdfUrl);if (!file.exists()) {togeneratePDFByPostfix(outPutInfo);}// 2返回对应html的地址。return outPutInfo;}
/*** * @Description (生成文件在服务器中的绝对路径)* @author feizhou* @Date 2018年4月19日下午4:27:04  * @version 1.0.0* @param inputFileUrl 文件的url* @return*/public String generateInputFileAbsolutePath(String inputFileUrl){Map paramap = dataDictionaryService.findSystemParam();int beginIndex = inputFileUrl.indexOf(Constans.UPLOADFILES);inputFileUrl = inputFileUrl.substring(beginIndex+13);inputFileUrl = paramap.get("uploadSavePath").toString() + inputFileUrl;
//      fileFullName = getPath(fileFullName,request);inputFileUrl = inputFileUrl.replaceAll("\\\\", "/");return inputFileUrl;}/*** * @Description (通过输入的文件全称,获取输出html的保存地址),例如E:\test\1t.docx*              htmlUrl:E:\test\1t\1t.html fileName:1t*              htmlParentUrl:E:\test\1t* @author feizhou* @Date 2018年2月5日 下午2:42:28* @version 1.0.0* @param inputFileUrl  文件的绝对路径*            :输入的文件名全称* @return*/public Map<String, String> getOutPutInfo(String inputFileUrl) {//  ..*/uploadFiles/20180206114633293508.docx// 生成一个包含文件名的文件夹int lastIndexOf = inputFileUrl.lastIndexOf(".");int length = inputFileUrl.length();String htmlParentUrl = inputFileUrl.substring(0, lastIndexOf) + "_html/";// 保存html文件的文件夹// /uploadFiles/20180205171125318612_html/String postfix = inputFileUrl.substring(lastIndexOf, length);// 后缀名// 看看文件夹是否存在,不存在就创建File newFolder = new File(htmlParentUrl);if (!newFolder.exists()) {// 创建/html/product/文件夹,mkdirs多级创建newFolder.mkdirs();}String fileName = inputFileUrl.substring(inputFileUrl.lastIndexOf("/") + 1, lastIndexOf);// 文件名String pdfUrl = htmlParentUrl + fileName + ".pdf";// 生成的绝对pdf文件全称// ...../uploadFiles/20180205171125318612_html/20180205171125318612.pdfint lastIndexOf2 = pdfUrl.lastIndexOf("uploadFiles");int lastlength=pdfUrl.length();String serverPath=getServerPath2();String redirectPDFUrl =serverPath+"/"+pdfUrl.substring(lastIndexOf2,lastlength);//重定向的PDFMap<String, String> map = new HashMap<String, String>();map.put("htmlParentUrl", htmlParentUrl);//map.put("fileFullName", inputFileUrl);//map.put("postfix", postfix);map.put("fileName", fileName);map.put("pdfUrl", pdfUrl);//pdf的绝对路径map.put("redirectPDFUrl", redirectPDFUrl);//return map;}/*** * @Description (通过后缀名,适配不同的转换代码)* @author feizhou* @Date 2018年2月7日 上午9:17:20* @version 1.0.0* @param postfix* @param getoutPutUrl* @throws Exception*/public void togeneratePDFByPostfix(Map<String, String> getoutPutUrl) throws Exception {String postfix = getoutPutUrl.get("postfix");if (postfix.equals(".txt")) {} else if (postfix.equalsIgnoreCase(".pdf")) {} else if (postfix.equalsIgnoreCase(".doc")) {fileToPDF(getoutPutUrl);} else if (postfix.equalsIgnoreCase(".docx")) {fileToPDF(getoutPutUrl);} else if (postfix.equalsIgnoreCase(".xlsx")) {excelToPDF(getoutPutUrl);} else if (postfix.equalsIgnoreCase(".xls")) {excelToPDF(getoutPutUrl);} else if (postfix.equalsIgnoreCase(".pptx")) {fileToPDF(getoutPutUrl);} else if (postfix.equalsIgnoreCase(".ppt")) {fileToPDF(getoutPutUrl);} else {}}//没有用注释掉
//  // 获取名称对应的路径
//  public String getPath(String name) {//      return servletContext.getRealPath(name);
//
//  }
//
//  public void setServletContext(ServletContext servletContext) {//      // set注入
//      this.servletContext = servletContext;
//  }//没有用注释掉
//private String getServerPath(){//  String RUL_PATH = Thread.currentThread().getContextClassLoader().getResource("").getPath()
//          .replace("%20", " ")
//          + "properties/fileClass.properties";
//      Properties prop = new Properties();
//          FileInputStream fis = null;
//          try {//              fis = new FileInputStream(RUL_PATH);
//              prop.load(fis);// 将属性文件流装载到Properties对象中
//          } catch (Exception e) {//              e.printStackTrace();
//          }finally {//              if(fis!=null){//                  try {//                      fis.close();
//                  } catch (IOException e) {//                      // TODO Auto-generated catch block
//                      e.printStackTrace();
//                  }// 关闭流
//              }
//          }
//          String filePath = prop.getProperty("filePath");
//          return filePath;
//}
private String getServerPath2(){DataDictionary d = new DataDictionary();String path = null;//系统参数从数据字典中获取d.setGroupID("34");d.setItemID("324");List<DataDictionary> list = dataDictionaryService.find(d);Map map = new HashMap();if(list != null && list.size() > 0){String a = list.get(0).getParam();if(StringUtil.isNotEmpty(a)){String[] array = a.split(";");for(int i = 0; i < array.length; i++){String  b = array[i];String[] array2 = b.split("=");map.put(array2[0],array2[1]);}}path = map.get("fileUrl").toString();}return path;
}
/*** @Description (文件转换PDF)* @author feizhou* @Date 2018年3月21日上午11:22:13* @version 1.0.0* @param getoutPutUrl* @throws TransformerException* @throws IOException* @throws ParserConfigurationException*/@Override
public void fileToPDF(Map<String, String> getoutPutUrl) throws  IOException{fileToOnline.fileToPDF(getoutPutUrl);}
@Override
public void excelToPDF(Map<String, String> getoutPutUrl) throws IOException {Boolean issuccess=fileToOnline.excel2PDF(getoutPutUrl);if(!issuccess){throw new MyException("文件转PDF失败");}
}
@Override
public String togeneratePortForOpenOffice(){return "8100";
}

转载于:https://www.cnblogs.com/feiZhou/p/9344022.html

在线预览任务调度的实现相关推荐

  1. uniapp移动端H5在线预览PDF等文件实现源码及注解

    uniapp移动端H5预览文件实现分为两个场景处理: (这里以预览PDF文件为示例,在线预览就是查看网络文件) 1. IOS客户端预览PDF文件 IOS客户端预览PDF文件可以通过跳转文件地址实现预览 ...

  2. 上班第一天公司要你用Spring Boot 实现万能文件在线预览

    欢迎关注方志朋的博客,回复"666"获面试宝典 推荐一个用 Spring Boot 搭建的文档在线预览解决方案:kkFileView,一款成熟且开源的文件文档在线预览项目解决方案, ...

  3. Spring Boot 实现万能文件在线预览

    推荐一个用 Spring Boot 搭建的文档在线预览解决方案:kkFileView,一款成熟且开源的文件文档在线预览项目解决方案,对标业内付费产品有永中office.office365.idocv等 ...

  4. SpringBoot实现万能文件在线预览,已开源,真香!!!

    欢迎关注方志朋的博客,回复"666"获面试宝典 推荐一个用Spring Boot搭建的文档在线预览解决方案: kkFileView,一款成熟且开源的文件文档在线预览项目解决方案,对 ...

  5. window下实现在线预览功能

    window下实现在线预览功能 最近用到文档在线预览功能,之前没接触过,一切从零开始,整了一段时间终于实现,现在把方法分享给大家! 一.主要思路 先将其他格式的文档(office文档.txt.图片等等 ...

  6. 实现word在线预览 有php的写法 也有插件似

    1 <?php2 //header("Content-type:text/html;charset=utf-8");3 //word转html 展示4 $lj=$_GET[' ...

  7. [Asp.net]使用flexpaper+swftools大文件分页转换实现在线预览

    引言 之前总结了在线预览几种常见解决方案,可以戳这里: http://www.cnblogs.com/wolf-sun/p/3569960.html http://www.cnblogs.com/wo ...

  8. WEB文档在线预览解决方案

    WEB文档在线预览解决方案 参考文章: (1)WEB文档在线预览解决方案 (2)https://www.cnblogs.com/lizhao123/p/11581971.html (3)https:/ ...

  9. OSS上传图片无法在线预览的解决方案

    OSS上传图片无法在线预览的解决方案 参考文章: (1)OSS上传图片无法在线预览的解决方案 (2)https://www.cnblogs.com/tian874540961/p/12058544.h ...

最新文章

  1. Qt-4.6.3移植与Qt creator开发环境建立
  2. 如何衡量RFID技术在仓库中的价值?
  3. Telephone Number
  4. 快速打造属于你的接口自动化测试框架
  5. 获取win7时区所有信息
  6. linux-权限设置--facl基本
  7. CloudIDE:为开发者写代码开启“加速”模式
  8. 如何联机调试和发布程序
  9. python如何获取网页内容_python如何获取网页内容
  10. Windows 之 IP地址
  11. Python编写中国象棋棋盘(可视化页面)
  12. 执行python generate_tfrecord.py 出现 utf-8‘ codec can‘t decode
  13. 313day(服务器的一些问题)
  14. 数字图像相关(Digital Image Correlation, DIC)中的非线性优化方法IC-GN的数值解计算
  15. 获得32位UUID字符串和指定数目的UUID
  16. java 字体变形_怎样用java绘制弧形文字
  17. 阿里云推出“通达云OA”办公系统 基于钉钉的移动OA应用...
  18. 【数据库】什么是 PostgreSQL?开源数据库系统
  19. 三维人脸重建 (一)
  20. Jenkins+GitHub报错hudson.plugins.git.GitException: Failed to fetch from GitHub 443

热门文章

  1. Linux下tomcat内存溢出分析及优化
  2. 程序猿,如果下次有人让你帮忙开发App,你就这样回答他
  3. 利用tftp和nfs下载文件到开发板
  4. Linux下SSH命令使用方法详解
  5. 梦心日记本V2.0完工
  6. 用JEP 343打包工具,构建自包含、可安装的Java应用程序
  7. 用 go 写 WebAssembly入门
  8. 从MyEclipse到IntelliJ IDEA ——让你摆脱鼠标,全键盘操作
  9. 高性能服务器架构(一):缓冲策略
  10. 二分搜索 2015百度之星初赛1 HDOJ 5248 序列变换