上傳的Word 轉 pdf ,實現在線預覽功能


上傳Word 文件,轉PDF格式,實現在線預覽功能;

 

下載一個 OpenOffice 4.1.6 ,解壓運行,安裝到電腦上,就是通過openOffice 的api進行轉換的;

//這個是一個controller

@Controller
@RequestMapping(value = "${adminPath}/enterprise/ecsSysPolicyAnnex")
public class EcsSysPolicyAnnexController extends BaseController {

  //這個是一個form 保存功能,其中就有一個文件上傳功能

  @RequiresPermissions("enterprise:ecsSysPolicyAnnex:edit")
  @RequestMapping(value = "save")
  public String save(MultipartFile multipartFile, EcsSysPolicyAnnex ecsSysPolicyAnnex, Model model,
  HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
  if (!beanValidator(model, ecsSysPolicyAnnex)) {
  return form(ecsSysPolicyAnnex, model);
  }
  // 上傳文件功能的實現,返回保存路徑
  String path = ecsSysPolicyAnnexService.uploadFile(multipartFile, request);
  if (!StringUtils.isBlank(path)) {
  ecsSysPolicyAnnex.setFileurl(path);
  }
  ecsSysPolicyAnnexService.save(ecsSysPolicyAnnex);
  addMessage(redirectAttributes, "保存政策附件表成功");
  return "redirect:" + Global.getAdminPath() + "/enterprise/ecsSysPolicyAnnex/?repage";
  }

}

//這個是service 層方法 

  /**
  * 上傳文件
  */
  public String uploadFile(MultipartFile multipartFile, HttpServletRequest request) throws Exception {
  // 解決文件重名問題
  String finalFileName = UUID.randomUUID().toString()
  + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
  // 判斷后綴名是否是(.doc.docx.pdf)
  String[] allowTypes = new String[] { "docx", "doc", "pdf" };
  int splitIndex = finalFileName.lastIndexOf(".");
  String fileType = finalFileName.substring(splitIndex + 1);// doc、docx、pdf
  String path = "";
  // 包含在docx,doc,pdf時,將path保存,否則,不保存(因為是非必填項);
  if (isHasSuffix(fileType, allowTypes)) {
  // 獲取上傳文件的路徑
  path = request.getSession().getServletContext().getRealPath("static") + File.separator + finalFileName;
  if (!new File(path).exists()) {
  new File(path).mkdirs();
  }
  multipartFile.transferTo(new File(path));
  // 將Word轉成PDF(docx,doc-->pdf)
  path = word2pdf(path);
  }
  return path;
  }

/**
* 判斷類型是否包含這些
*
* @param fileType
* @return
*/
private static boolean isHasSuffix(String fileType, String... allowTypes) {
Boolean CanUploaded = isValid(fileType, allowTypes);
if (CanUploaded) {
// System.out.println("允許上傳!");
return true;
} else {
// System.out.println("禁止上傳!");
return false;
}
}

/**
* 判斷是否為空;
*
* @param contentType
* @param allowTypes
* @return
*/
public static boolean isValid(String contentType, String... allowTypes) {
if (null == contentType || "".equals(contentType)) {
return false;
}
for (String type : allowTypes) {
if (contentType.indexOf(type) > -1) {
return true;
}
}
return false;
}

/**
* 將上傳的文件轉換為pdf格式,方便在線預覽
*
* @param path:Word所在文件路徑
* @return :返回PDF格式文件路徑
* @throws Exception
*/
private String word2pdf(String path) throws Exception {
// 要轉換的文件及地址
File pdf = new File(path);

// openoffice.paht 是 properties 配置文件中配置的openoffice 的安裝地址; 比如我的 : openoffice.paht = C:\\Program Files (x86)\\OpenOffice 4\\program

String configPath = Global.getConfig("openoffice.paht");
// 轉換工具所在的安裝目錄(配置文件中);
Word2PdfConvertor wp = new Word2PdfConvertor(configPath);
// 轉換為PDF文件
File convert = wp.convert(pdf);
// 獲取 PDF文件路徑
String courseFile = convert.getCanonicalPath();
// 獲取PDF文件名稱及路徑
return courseFile;
}

// 這個是工具類,可以 pdf 轉圖片,可以文本轉圖片,文本轉 PDF ,Word 轉圖片,Word 轉 pdf ,看你需要什么,就調用什么;

 

// 工具類,也給貼出來了;

package com.thinkgem.jeesite.modules.utils;

import java.io.File;
import java.io.IOException;
import java.net.ConnectException;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;


/**
* 將Word文檔轉換成pdf文件
* <p>此功能依賴於OpenOffice提供的文件轉換服務</p>
* @author hkrj
*
*/
public class Word2PdfConvertor implements IConvertor {
private String sofficePath;
private OpenOfficeConnection connection = null;
private int port =8100;

/**
* 創建word轉換pdf轉換器,此工具需要OpenOffice軟件支持
* @param sofficePath soffice命令所在的目錄
* @throws Exception
*/
public Word2PdfConvertor(String sofficePath) throws Exception{
this.sofficePath=sofficePath;
this.connection = new SocketOpenOfficeConnection(8100);
//啟動OpenOffice轉換服務
if(!this.checkOpenOfficeConnection(this.connection)){
this.startOpenOfficeConverterService();
}
}

/**
* 創建word轉換pdf轉換器,此工具需要OpenOffice軟件支持
* @param sofficePath soffice命令所在的目錄
* @param port soffice服務運行的端口號,默認端口號為8100
* @throws Exception
*/
public Word2PdfConvertor(String sofficePath,int port) throws Exception{
this(sofficePath);
this.port=port;
}

@Override
public File convert(File srcFile) throws Exception {
OpenOfficeConnection connection = new SocketOpenOfficeConnection(this.port);
File outputFile = null;
try {
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
String filename = srcFile.getAbsolutePath();
filename=filename.substring(0,filename.lastIndexOf("."))+".pdf";
outputFile=new File(filename);
converter.convert(srcFile, outputFile);
} catch (ConnectException e) {
throw new Exception(e);
}finally {
if(connection!=null){
connection.disconnect();
}
}
return outputFile;
}


/**
* 啟動OpenOffice轉換服務
*
* @return
* @throws IOException
*/
public synchronized void startOpenOfficeConverterService() throws IOException {
String commandStr = this.prepareCommand();
Runtime.getRuntime().exec(commandStr, null,new File(this.sofficePath));
}

/**
* 根據當前系統類型准備啟動OpenOffice轉換服務的命令
* @return 返回命令字符串,如果獲取不到系統類型則返回null
*/
public String prepareCommand() {
String osname = this.getOSType();
if (osname == null) {
throw new RuntimeException("獲取不到當前系統類型");
}
if ("windows".equals(osname)) {
return "cmd /c soffice.exe -headless -accept=\"socket,host=127.0.0.1,port="+this.port+";urp;\" -nofirststartwizard";
}
if ("linux".equals(osname) || "mac".equals(osname) || "unix".equals(osname)) {
return "soffice --headless -accept=\"socket,host=127.0.0.1,port="+this.port+";urp;\" --nofirststartwizard";
}
return null;
}

/**
* 獲取當前系統類型
*
* @return 如果獲取不到系統類型則返回null,否則根據實際情況返回[windows/linux/mac/unix]
*/
public String getOSType() {

String osName = System.getProperty("os.name");
osName = osName.toLowerCase();
if (osName.contains("windows")) {
return "windows";
}
if (osName.contains("linux")) {
return "linux";
}
if (osName.contains("mac")) {
return "mac";
}
if (osName.contains("unix")) {
return "unix";
}

return null;

}

/**
* 檢測OpenOffice轉換服務是否已經啟動
*
* @param connection
* OpenOffice轉換服務連接,如果connection為null則方法直接返回false
* @return 如果轉換服務已經啟動並能聯通則返回true否則返回false
*/
public boolean checkOpenOfficeConnection(OpenOfficeConnection connection) {
if (connection == null) {
return false;
}
boolean isConnection = true;
try {
connection.connect();
connection.disconnect();
} catch (ConnectException e) {
isConnection = false;
}
return isConnection;
}

}

 

//用到了兩個jar 包

 

 

自此,Word上傳轉pdf 預覽功能 完成;

這個得思考着寫,大概的思路就是這樣;

記錄一下;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM