使用OpenOffice外掛實現RTF/WORD轉PDF轉多張圖片或者一張圖片
阿新 • • 發佈:2018-11-13
這裡我們使用的是OpenOffice外掛,需要安裝,還有相關的jar包 網盤地址:
https://pan.baidu.com/s/1c6HymABx3wre-d19eB1c-w 密碼: n1cd
安裝OpenOffice完成後
Windows 命令進入安裝目錄 + 啟動服務
cd C:\Program Files\OpenOffice.org 3\program
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
轉化包 Maven Pom配置
<!-- 手動注入包FileToImgUtil轉化包 -->
<dependency>
<groupId>org.icepdf</groupId>
<artifactId>icepdf-core</artifactId>
</dependency>
1.RTF或者Word生成PDF文件的方法
我註釋掉的部分是啟動每次都訪問都自動啟動關閉OpenOffice,需要可以解開註釋。
/** * @Description: rtf/word 生成pdf文件 * @Param: inputFile 要讀取的檔案 outputFile 輸出的pdf檔案 * @return: String pdf檔名稱 * @Author: 王飛焱 * @Date: 2018/11/8 */ public String docToPdf(File inputFile, File outputFile) { // 啟動服務 /* * String OpenOffice_HOME = "C:/Program Files (x86)/OpenOffice 4";// 這裡是OpenOffice的安裝目錄 * if(OpenOffice_HOME.charAt(OpenOffice_HOME.length()-1)!='/'){ OpenOffice_HOME+="/"; } */ Process pro = null; OpenOfficeConnection connection = null; // 啟動OpenOffice的服務 /* * String command = OpenOffice_HOME + * "program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\""; */ // connect to an OpenOffice.org instance running on port 8100 try { /* pro = Runtime.getRuntime().exec(command); */ connection = new SocketOpenOfficeConnection(8100); connection.connect(); // convert DocumentConverter converter = new OpenOfficeDocumentConverter(connection); System.out.println(inputFile + "=" + outputFile); converter.convert(inputFile, outputFile); } catch (Exception ex) { ex.printStackTrace(); logger.info("\n 程式出錯了:", ex); } finally { if (connection != null) { connection.disconnect(); connection = null; } /* pro.destroy(); */ } logger.info("生成檔案:" + outputFile.getName()); return outputFile.getName(); }
2.將pdf轉換成多張圖片(JPG)
/** * 將pdf轉換成圖片 * * @param pdfPath * @param imgDirPath * @return 返回轉換後圖片的名字 * @throws Exception */ private List<String> pdf2Imgs(String pdfPath, String imgDirPath, String fileName) throws Exception { Document document = new Document(); document.setFile(pdfPath); float scale = 2f;// 放大倍數 float rotation = 0f;// 旋轉角度 List<String> imgNames = new ArrayList<String>(); int pageNum = document.getNumberOfPages(); File imgDir = new File(imgDirPath); if (!imgDir.exists()) { imgDir.mkdirs(); } for (int i = 0; i < pageNum; i++) { BufferedImage image = (BufferedImage)document .getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale); RenderedImage rendImage = image; try { String filePath = imgDirPath + File.separator + fileName + i + ".jpg"; File file = new File(filePath); ImageIO.write(rendImage, "jpg", file); imgNames.add(FilenameUtils.getName(filePath)); } catch (IOException e) { e.printStackTrace(); return null; } image.flush(); } document.dispose(); return imgNames; }
3.PDF多頁轉換成一張圖片
/**
* @Description: PDF多頁轉換成一張圖片
* @Param: pdfFile PDF絕對路徑,outpath 輸出的圖片路徑
* @Author: 王飛焱
* @Date: 2018/11/13
*/
public void pdf2multiImage(String pdfFile, String outpath) throws IOException, PDFException, PDFSecurityException {
InputStream is = new FileInputStream(pdfFile);
List<BufferedImage> piclist = new ArrayList<BufferedImage>();
Document document = new Document();
document.setFile(pdfFile);
float scale = 2.5f; // 縮放比例
float rotation = 0f; // 旋轉角度
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage)document
.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
piclist.add(image);
}
document.dispose();
yPic(piclist, outpath);
is.close();
}
/* 縱向處理圖片 */
public void yPic(List<BufferedImage> piclist, String outPath) throws IOException {
if (piclist == null || piclist.size() <= 0) {
System.out.println("圖片陣列為空!");
return;
}
int height = 0, // 總高度
width = 0, // 總寬度
_height = 0, // 臨時的高度 , 或儲存偏移高度
__height = 0, // 臨時的高度,主要儲存每個高度
picNum = piclist.size();// 圖片的數量
File fileImg = null; // 儲存讀取出的圖片
int[] heightArray = new int[picNum]; // 儲存每個檔案的高度
BufferedImage buffer = null; // 儲存圖片流
List<int[]> imgRGB = new ArrayList<int[]>(); // 儲存所有的圖片的RGB
int[] _imgRGB; // 儲存一張圖片中的RGB資料
for (int i = 0; i < picNum; i++) {
buffer = piclist.get(i);
heightArray[i] = _height = buffer.getHeight();// 圖片高度
if (i == 0) {
width = buffer.getWidth();// 圖片寬度
}
height += _height; // 獲取總高度
_imgRGB = new int[width * _height];// 從圖片中讀取RGB
_imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
imgRGB.add(_imgRGB);
}
_height = 0; // 設定偏移高度為0
// 生成新圖片
BufferedImage imageResult = new BufferedImage(width/2, height/2, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < picNum; i++) {
__height = heightArray[i];
if (i != 0)
_height += __height; // 計算偏移高度
imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 寫入流中
}
File outFile = new File(outPath);
ImageIO.write(imageResult, "jpg", outFile);// 寫圖片
}
我把整個類貼出來
package com.ys.gassys.utils;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
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;
import org.apache.commons.io.FilenameUtils;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import javax.imageio.ImageIO;
/**
* Created with IntelliJ IDEA. Description:openOffice 生成pdf
*
* @author wangfeiyan Date: 14:04 Time: 2018/118/8
*/
public class OfficeToPDF {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* @Description: rtf/word 生成pdf文件
* @Param: inputFile 要讀取的檔案 outputFile 輸出的pdf檔案
* @return: String pdf檔名稱
* @Author: 王飛焱
* @Date: 2018/11/8
*/
public String docToPdf(File inputFile, File outputFile) {
// 啟動服務
/*
* String OpenOffice_HOME = "C:/Program Files (x86)/OpenOffice 4";// 這裡是OpenOffice的安裝目錄
* if(OpenOffice_HOME.charAt(OpenOffice_HOME.length()-1)!='/'){ OpenOffice_HOME+="/"; }
*/
Process pro = null;
OpenOfficeConnection connection = null;
// 啟動OpenOffice的服務
/*
* String command = OpenOffice_HOME +
* "program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
*/
// connect to an OpenOffice.org instance running on port 8100
try {
/* pro = Runtime.getRuntime().exec(command); */
connection = new SocketOpenOfficeConnection(8100);
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
System.out.println(inputFile + "=" + outputFile);
converter.convert(inputFile, outputFile);
}
catch (Exception ex) {
ex.printStackTrace();
logger.info("\n 程式出錯了:", ex);
}
finally {
if (connection != null) {
connection.disconnect();
connection = null;
}
/* pro.destroy(); */
}
logger.info("生成檔案:" + outputFile.getName());
return outputFile.getName();
}
// 生產pdf執行緒
static class TestThread extends Thread {
private File inputFile;
private File outputFile;
public void run() {
OfficeToPDF t = new OfficeToPDF();
t.docToPdf(inputFile, outputFile);
System.out.println(outputFile.getName() + "檔案已生成");
}
public void setInputFile(File inputFile) {
this.inputFile = inputFile;
}
public void setOutputFile(File outputFile) {
this.outputFile = outputFile;
}
}
/**
* 將pdf轉換成圖片
*
* @param pdfPath
* @param imgDirPath
* @return 返回轉換後圖片的名字
* @throws Exception
*/
private List<String> pdf2Imgs(String pdfPath, String imgDirPath, String fileName)
throws Exception {
Document document = new Document();
document.setFile(pdfPath);
float scale = 2f;// 放大倍數
float rotation = 0f;// 旋轉角度
List<String> imgNames = new ArrayList<String>();
int pageNum = document.getNumberOfPages();
File imgDir = new File(imgDirPath);
if (!imgDir.exists()) {
imgDir.mkdirs();
}
for (int i = 0; i < pageNum; i++) {
BufferedImage image = (BufferedImage)document
.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
try {
String filePath = imgDirPath + File.separator + fileName + i + ".jpg";
File file = new File(filePath);
ImageIO.write(rendImage, "jpg", file);
imgNames.add(FilenameUtils.getName(filePath));
}
catch (IOException e) {
e.printStackTrace();
return null;
}
image.flush();
}
document.dispose();
return imgNames;
}
public static void main(String[] args) {
// // String docPath = "d:/94_storage安裝.doc";
// String docPath = "d:/公司通訊錄.xlsx";
// String pdfPath = "d:/pdf/";
// doc2Imags(docPath, pdfPath, "公司通訊錄");
OfficeToPDF officeToPDF = new OfficeToPDF();
officeToPDF.docToPdf(new File("D:\\blob.rtf"), new File("D:\\test\\test1.pdf"));
// officeToPDF.pdf2multiImage("D:\\test\\test1.pdf","D:\\test\\test1.jpg");
// try {
// officeToPDF.pdf2Imgs("D:\\test\\test1.pdf", "D:\\test\\", "test");
// }
// catch (Exception e) {
// e.printStackTrace();
// }
}
/**
* @Description: PDF多頁轉換成一張圖片
* @Param: pdfFile PDF絕對路徑,outpath 輸出的圖片路徑
* @Author: 王飛焱
* @Date: 2018/11/13
*/
public void pdf2multiImage(String pdfFile, String outpath) throws IOException, PDFException, PDFSecurityException {
InputStream is = new FileInputStream(pdfFile);
List<BufferedImage> piclist = new ArrayList<BufferedImage>();
Document document = new Document();
document.setFile(pdfFile);
float scale = 2.5f; // 縮放比例
float rotation = 0f; // 旋轉角度
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage)document
.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
piclist.add(image);
}
document.dispose();
yPic(piclist, outpath);
is.close();
}
/* 縱向處理圖片 */
public void yPic(List<BufferedImage> piclist, String outPath) throws IOException {
if (piclist == null || piclist.size() <= 0) {
System.out.println("圖片陣列為空!");
return;
}
int height = 0, // 總高度
width = 0, // 總寬度
_height = 0, // 臨時的高度 , 或儲存偏移高度
__height = 0, // 臨時的高度,主要儲存每個高度
picNum = piclist.size();// 圖片的數量
File fileImg = null; // 儲存讀取出的圖片
int[] heightArray = new int[picNum]; // 儲存每個檔案的高度
BufferedImage buffer = null; // 儲存圖片流
List<int[]> imgRGB = new ArrayList<int[]>(); // 儲存所有的圖片的RGB
int[] _imgRGB; // 儲存一張圖片中的RGB資料
for (int i = 0; i < picNum; i++) {
buffer = piclist.get(i);
heightArray[i] = _height = buffer.getHeight();// 圖片高度
if (i == 0) {
width = buffer.getWidth();// 圖片寬度
}
height += _height; // 獲取總高度
_imgRGB = new int[width * _height];// 從圖片中讀取RGB
_imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
imgRGB.add(_imgRGB);
}
_height = 0; // 設定偏移高度為0
// 生成新圖片
BufferedImage imageResult = new BufferedImage(width/2, height/2, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < picNum; i++) {
__height = heightArray[i];
if (i != 0)
_height += __height; // 計算偏移高度
imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 寫入流中
}
File outFile = new File(outPath);
ImageIO.write(imageResult, "jpg", outFile);// 寫圖片
}
}