队列设计
/**
* @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返回0
return 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>{
@Autowired
private ErrorConvertQueue errorConvertQueue;
//转换策略:小文件优先转换策略 A
public RunConvertQueue minFilePrecedenceStrategy(){
Collections.sort(this.getQueue(), new Comparator<FileToPDF>() {
@Override
public int compare(FileToPDF s1, FileToPDF s2) {
return (int) (s1.getSize()-s2.getSize());
}
});
return this;
}
//转换策略:最早上传转换策略 B
public RunConvertQueue FiFoStrategy(){
Collections.sort(this.getQueue(), new Comparator<FileToPDF>() {
@Override
public int compare(FileToPDF s1, FileToPDF s2) {
return s1.getCreateDate().compareTo(s2.getCreateDate());
}
});
return this;
}
//转换策略:BA
public RunConvertQueue FiFoAndMinFileStrategy(){
Collections.sort(this.getQueue(), new Comparator<FileToPDF>() {
@Override
public 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;
}
//转换策略:AB
public RunConvertQueue MinAndFifoFileStrategy(){
Collections.sort(this.getQueue(), new Comparator<FileToPDF>() {
@Override
public 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.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://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/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://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 {
@Autowired
private RunConvertQueue runConvertQueue;
@Autowired
private ErrorConvertQueue errorConvertQueue;
@Autowired
private FileToPDFDao fileToPDFDao;
@Autowired
private 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);
@Autowired
private RunConvertQueue runConvertQueue;
@Autowired
private ErrorConvertQueue errorConvertQueue;
@Autowired
private FileToPDFDao fileToPDFDao;
@Autowired
private 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();
// convert
DocumentConverter 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的BootstrapSocketConnector
XComponentContext 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 document
PropertyValue[] propertyValues = new PropertyValue[2];
// Setting the flag for overwriting
propertyValues[0] = new PropertyValue();
propertyValues[0].Name = "Overwrite";
propertyValues[0].Value = new Boolean(true);
// Setting the filter name
propertyValues[1] = new PropertyValue();
propertyValues[1].Name = "FilterName";
propertyValues[1].Value = "writer_pdf_Export";
// Composing the URL by replacing all backslashs
File 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 document
storable.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();
}
}
}
//多线程文件转PDF
public 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;
}
}
}
//单线程文件转PDF
public 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;
}
@Override
public void run() {
//实力话新的fileToOnline
WebApplicationContext 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 exception
e.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>();//静态属性,对象共享
@Autowired
private FileToOnline fileToOnline;
@Autowired
private DataDictionaryService dataDictionaryService;
@Override
public Map<String, String> generatePDF(String inputFileUrl) throws Exception {
// TODO Auto-generated method stub
String 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.pdf
int lastIndexOf2 = pdfUrl.lastIndexOf("uploadFiles");
int lastlength=pdfUrl.length();
String serverPath=getServerPath2();
String redirectPDFUrl =serverPath+"/"+pdfUrl.substring(lastIndexOf2,lastlength);//重定向的PDF
Map<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";
}