package org.bigdata.framework.docmg.util;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.rtf.RTFEditorKit;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.tools.ant.Main;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.bigdata.framework.docmg.util.DXFDrawings.ExportSpecificDXFLayoutToPDF;
import org.springframework.beans.factory.annotation.Value;
import org.w3c.dom.Document;
import com.aspose.cad.Image;
import com.aspose.cad.imageoptions.CadRasterizationOptions;
import com.aspose.cad.imageoptions.PdfOptions;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
* 文件适配器
* @author rhy
* @time 2018年11月12日 下午4:16:15
*
*/
public class FileAdapter {
private final static String tempPath = "http://localhost:8081/file_server/conver/image";
private final static String path = "D:\\logs\\conver\\";
// private final static String path = "/usr/local/preview/628/";
//存图片的地方
//private final static String tempPath = "modular/browser/files"; //存图片的地方
private static Logger logger = Logger.getLogger(FileAdapter.class);
public static void fileAdapter(String src,String desc){
String extName = src.substring(src.lastIndexOf(".")+1).toLowerCase();
switch (extName) {
case "txt":
txtAdapter(src,desc);
break;
case "rtf":
// wordAdapter2(src,desc);
windowsToPdf(src,desc);
break;
case "html":
htmlAdapter(src,desc);
break;
case "doc":
// wordAdapter2(src,desc);
windowsToPdf(src,desc);
break;
case "docx":
// wordAdapter2(src,desc);
windowsToPdf(src,desc);
break;
case "wps":
// wpsAdapter2(src,desc);
windowsToPdf(src,desc);
break;
case "pdf":
pdfAdapter2(src,desc);
break;
case "zip":
zipAdapter(src,desc);
break;
case "bmp":
imgToHtml(src,desc);
break;
case "gif":
imgToHtml(src,desc);
break;
case "jpg":
imgToHtml(src,desc);
break;
case "pic":
imgToHtml(src,desc);
break;
case "png":
imgToHtml(src,desc);
break;
case "tif":
// tifToHtml(src,desc);
windowsToPdf(src, desc);
break;
case "wav":
audioToHtml(src,desc);
break;
case "flac":
audioToHtml(src,desc);
break;
case "mp3":
audioToHtml(src,desc);
break;
case "aif":
audioToHtml(src,desc);
break;
case "au":
audioToHtml(src,desc);
break;
case "ram":
videoToHtml(src,desc);
break;
case "wma":
audioToHtml(src,desc);
break;
case "amr":
audioToHtml(src,desc);
break;
case "aac":
audioToHtml(src,desc);
break;
case "mmf":
audioToHtml(src,desc);
break;
case "avi":
imgToHtml(src,desc);
break;
case "mpg":
videoToHtml(src,desc);
break;
case "mov":
videoToHtml(src,desc);
break;
case "swf":
videoToHtml(src,desc);
break;
case "sys":
imgToHtml(src,desc);
break;
case "c":
txtAdapter(src,desc);
break;
case "msg":
mapAdapter(src,desc);
break;
case "map":
mapAdapter(src,desc);
break;
case "bat":
txtAdapter(src,desc);
break;
case "ogg":
videoToHtml(src,desc);
break;
case "mp4":
videoToHtml(src,desc);
break;
case "webm":
videoToHtml(src,desc);
break;
case "xls":
// xlsToPDF(src,desc);
windowsToPdf(src,desc);
break;
case "xlsx":
// xlsToPDF(src,desc);
windowsToPdf(src,desc);
break;
case "dwg":
ExportSpecificDXFLayoutToPDF.dwgExport(src, desc);
break;
case "dxf":
ExportSpecificDXFLayoutToPDF.dxfExport(src, desc);
break;
case "pptx":
// pptToPDF(src,desc);
windowsToPdf(src,desc);
break;
default:
break;
}
}
//dxf类型
private static void dxfToPDF(String src, String desc) {
try {
String dataDir = getDataDir(FileAdapter.class) + "static\\cad\\";
String srcFile = dataDir + "53b22a155a703.dwg";
Image image = Image.load(srcFile);
CadRasterizationOptions rasterizationOptions = new CadRasterizationOptions();
rasterizationOptions.setPageWidth(1600);
rasterizationOptions.setPageHeight(1600);
rasterizationOptions.getLayers().add("0");
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setVectorRasterizationOptions(rasterizationOptions);
image.save(dataDir + "dxf.pdf", pdfOptions);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//dwg类型
private static void dwgToPDF(String src, String desc) {
File dir = new File(System.getProperty("user.dir"));
dir = new File(dir, "src");
dir = new File(dir, "main");
dir = new File(dir, "resources");
String dataDir = dir.toString() + "\\static\\cad\\";
//ExStart:ExportSpecificLayerOfDXFDrawingToPDF
String srcFile = dataDir + "1.dwg";
Image image = Image.load(srcFile);
CadRasterizationOptions rasterizationOptions = new CadRasterizationOptions();
rasterizationOptions.setPageWidth(1600);
rasterizationOptions.setPageHeight(1600);
rasterizationOptions.getLayers().add("0");
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setVectorRasterizationOptions(rasterizationOptions);
image.save(dataDir + "dwg.pdf", pdfOptions);
}
//ppt类型
private static void pptToPDF(String src, String desc) {
try {
// File file = new File(desc);
// file.delete();
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent(
"PowerPoint.Application");
app.setProperty("Visible", false);
Dispatch ppts = app.getProperty("Presentations").toDispatch();
Dispatch ppt = Dispatch.call(ppts, "Open", src, true,// ReadOnly
true,// Untitled指定文件是否有标题
false// WithWindow指定文件是否可见
).toDispatch();
Dispatch.call(ppt, "SaveAs", desc, 32);
Dispatch.call(ppt, "Close");
app.invoke("Quit");
} catch (Exception e) {
}finally {
ComThread.Release();
}
}
//excel类型
public static boolean xlsToPDF(String src, String desc) {
try {
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("Excel.Application");
app.setProperty("Visible", false);
Dispatch excels = app.getProperty("Workbooks").toDispatch();
Dispatch excel = Dispatch.call(excels, "Open", src, false,
true).toDispatch();
Dispatch.call(excel, "SaveAs","ExportAsFixedFormat", 0, desc);
Dispatch.call(excel, "Close", false);
app.invoke("Quit");
return true;
} catch (Exception e) {
return false;
}finally {
ComThread.Release();
}
/*ActiveXComponent ax = null;
Dispatch excel = null;
try {
ComThread.InitSTA();
ax = new ActiveXComponent("Excel.Application");
ax.setProperty("Visible", false);
ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
Dispatch excels = ax.getProperty("Workbooks").toDispatch();
Object[] obj = new Object[]{
src,
new Variant(false),
new Variant(false)
};
excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();
// 转换格式
Object[] obj2 = new Object[]{
new Variant(0), // PDF格式=0
desc,
new Variant(0) //0=标准 (生成的PDF图片不会变模糊) ; 1=最小文件
};
Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method,obj2, new int[1]);
return true;
} catch (Exception es) {
es.printStackTrace();
throw es;
} finally {
if (excel != null) {
Dispatch.call(excel, "Close", new Variant(false));
}
if (ax != null) {
ax.invoke("Quit", new Variant[] {});
ax = null;
}
ComThread.Release();
}*/
}
private static void mapAdapter2(String src, String desc) {
BufferedReader r = null;
BufferedWriter w = null;
try {
r = new BufferedReader(new InputStreamReader(new FileInputStream(src)));
w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(desc)));
// if(!new File(desc).exists()){
new File(desc).createNewFile();
// }
String line = "";
w.write("
");");
while((line = r.readLine()) != null){
w.write(line);
w.write("
");
}
w.write("
w.write("");
}catch(Exception e){
logger.info(e);
e.printStackTrace();
}finally{
if(r!=null){
try {
r.close();
} catch (IOException e) {
logger.info(e);
e.printStackTrace();
}
}
if(w!=null){
try {
w.close();
} catch (IOException e) {
logger.info(e);
e.printStackTrace();
}
}
}
}
private static void mapAdapter(String src, String desc) {
BufferedReader r = null;
BufferedWriter w = null;
try {
r = new BufferedReader(new InputStreamReader(new FileInputStream(src)));
w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(desc)));
// if(!new File(desc).exists()){
new File(desc).createNewFile();
// }
String line = "";
while((line = r.readLine()) != null){
w.write(line);
w.write("\n");
}
}catch(Exception e){
logger.info(e);
e.printStackTrace();
}finally{
if(r!=null){
try {
r.close();
} catch (IOException e) {
logger.info(e);
e.printStackTrace();
}
}
if(w!=null){
try {
w.close();
} catch (IOException e) {
logger.info(e);
e.printStackTrace();
}
}
}
}
//音频类型
private static void audioToHtml(String src, String desc) {
try {
InputStream inputStream = new FileInputStream(new File(src));
String file_path = getFilePath("file_path");
file_path += desc.substring(desc.lastIndexOf("/")+1,desc.lastIndexOf("."));
String local_path = "";
local_path = desc.substring(0,desc.indexOf("."))+src.substring(src.lastIndexOf("."));
file_path += src.substring(src.lastIndexOf("."));
OutputStream outputStream = new FileOutputStream(new File(local_path));
byte[] b = new byte[1024];
int length = 0;
while((length = inputStream.read(b))!=-1){
outputStream.write(b,0,length);
}
Writer writer = new FileWriter(new File(desc));
writer.write("
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
//视频类型
private static void videoToHtml(String src, String desc) {
try {
InputStream inputStream = new FileInputStream(new File(src));
String file_path = getFilePath("file_path");
file_path += desc.substring(desc.lastIndexOf("/")+1,desc.lastIndexOf("."));
String local_path = "";
local_path = desc.substring(0,desc.indexOf("."))+src.substring(src.lastIndexOf("."));
file_path += src.substring(src.lastIndexOf("."));
OutputStream outputStream = new FileOutputStream(new File(local_path));
byte[] b = new byte[1024];
int length = 0;
while((length = inputStream.read(b))!=-1){
outputStream.write(b,0,length);
}
Writer writer = new FileWriter(new File(desc));
writer.write("
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static String getFilePath(String filePath){
String file_path = "";
try{
Properties properties = new Properties();
properties.load(FileAdapter.class.getResourceAsStream("/beetl.properties"));
file_path = properties.getProperty(filePath);
}catch(Exception e){
e.printStackTrace();
}
return file_path;
}
//图片展示
@SuppressWarnings("resource")
public static void tifToHtml(String src,String desc){
String file_path = getFilePath("file_path");
file_path += desc.substring(desc.lastIndexOf("/")+1,desc.lastIndexOf("."));
String local_path = "";
local_path = desc.substring(0,desc.indexOf("."))+".jpg";
file_path += ".jpg";
ImageInputStream input;
try {
input = ImageIO.createImageInputStream(new File(src));//以图片输入流形式读取到tif
ImageReader reader = ImageIO.getImageReaders(input).next();//获得image阅读器,阅读对象为tif文件转换的流
String path,tiffName;
path = src.substring(0, src.lastIndexOf("."));
tiffName = src.substring(src.lastIndexOf("\\"),src.lastIndexOf("."));
try {
reader.setInput(input);
int count = reader.getNumImages(true);//tif文件页数
for(int i = 0; i < count; i++){
BufferedImage image = reader.read(i, null);//取得第i页
File f = new File(local_path);
try {
if(!f.exists()){
f.getParentFile().mkdirs();
f.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
ImageIO.write(image, "JPEG", f);//保存图片
}
}catch(Exception e){
e.printStackTrace();
}
finally {
reader.dispose();
input.close();
}
Writer writer = new FileWriter(new File(desc));
writer.write("
writer.close();
}catch (IOException e) {
e.printStackTrace();
}
}
//图片展示
@SuppressWarnings("resource")
public static void imgToHtml(String src,String desc){
try {
InputStream inputStream = new FileInputStream(new File(src));
String file_path = getFilePath("file_path");
file_path += desc.substring(desc.lastIndexOf("/")+1,desc.lastIndexOf("."));
String local_path = "";
if(src.endsWith("tif")){
local_path = desc.substring(0,desc.indexOf("."))+".png";
file_path += ".png";
}else{
local_path = desc.substring(0,desc.indexOf("."))+src.substring(src.lastIndexOf("."));
file_path += src.substring(src.lastIndexOf("."));
}
OutputStream outputStream = new FileOutputStream(new File(local_path));
byte[] b = new byte[1024];
int length = 0;
while((length = inputStream.read(b))!=-1){
outputStream.write(b,0,length);
}
Writer writer = new FileWriter(new File(desc));
writer.write("
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
private static void zipAdapter(String src, String desc) {
try{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(desc)));
desc = src.substring(0,src.lastIndexOf(".zip"));
unzip(src, desc);
String fileDirData = getZipJson(src,desc);
writer.write("
//zip类型
public static String getZipJson(String src,String desc) {
StringBuilder buf=new StringBuilder();
if(src == null){
return null;
}
buf.append("var zNodes =");
File f = new File(desc);
if (f.isDirectory())
{
scan(new File(desc),buf);
buf.delete(buf.length() - 2, buf.length());
}
else if(f.getName() != null && f.getName().indexOf(".")!=-1){
buf.append("{").append("\"name\":\"").append(f.getName()).append("\"");
}
return buf.append("}").toString();
}
private static void scan(File f,StringBuilder buf) {
if (f.isDirectory())
{
buf.append("{").append("\"name\":\"").append(f.getName()).append("\",").append("\"filePath\":\"\",").append("\"children\":[");
// Arrays.asList(f.listFiles()).forEach(this::scan);
File[] files = f.listFiles();
for(int i=0;i
}
if(buf.toString().endsWith("\"children\":["))
buf.append("{\"name\":\"暂无文件\",\"path\":\"\",");
buf.delete(buf.length() - 2, buf.length());
buf.append("}").append("]").append("},");
}
else if(f.getName() != null && f.getName().indexOf(".")!=-1) {
//
String filePath = getFilePath("file_path");
filePath +=f.getName().substring(0,f.getName().lastIndexOf("."))+".html";
String newPath = getFilePath("new_path")+f.getName().substring(0,f.getName().lastIndexOf("."))+".html";
fileAdapter(f.getAbsolutePath(),newPath);
//buf.append("{").append("\"name\":\"").append(f.getName()).append("\"").append(",\"filePath\":\"").append(f.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\")).append("\"},");
buf.append("{").append("\"name\":\"").append(f.getName()).append("\"").append(",\"filePath\":\"").append(filePath.replaceAll("\\\\", "\\\\\\\\")).append("\"},");
}
}
//zip类型
private static void unzip(String sourceZip,String destDir) throws Exception{
try{
Project p = new Project();
Expand e = new Expand();
e.setProject(p);
e.setSrc(new File(sourceZip));
e.setOverwrite(false);
e.setDest(new File(destDir));
/*
ant下的zip工具默认压缩编码为UTF-8编码,
而winRAR软件压缩是用的windows默认的GBK或者GB2312编码
所以解压缩时要制定编码格式
*/
e.setEncoding("gbk");
e.execute();
}catch(Exception e){
throw e;
}
}
// wps类型文件
public static void wpsAdapter(String inputFile, String pdfFile) {
try {
File file = new File(pdfFile);
file.delete();
// file.createNewFile();
ActiveXComponent app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs, "Open", inputFile, false, true)
.toDispatch();
// Dispatch.call(doc, "SaveAs","ExportAsFixedFormat", pdfFile, 17);
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { pdfFile, new Variant(8) }, new int[1]);
Dispatch.call(doc, "Close", false);
app.invoke("Quit", 0);
} catch (Exception e) {
}
}
//word类型文件
public static void wordAdapter(String src,String desc){
try {
/*final String path = "D:\\poi-test\\wordToHtml\\";
final String file = "人员选择系分.doc";*/
InputStream input = new FileInputStream(src);
HWPFDocument wordDocument = new HWPFDocument(input);
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument());
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
public String savePicture(byte[] content, PictureType pictureType,
String suggestedName, float widthInches, float heightInches) {
return suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);
List pics = wordDocument.getPicturesTable().getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
pic.writeImageContent(new FileOutputStream(desc
+ pic.suggestFullFileName()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(outStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
outStream.close();
String content = new String(outStream.toByteArray());
FileUtils.writeStringToFile(new File(desc), content, "utf-8");
}catch(Exception e){
try {
XWPFDocument document = new XWPFDocument(new FileInputStream(src));
XHTMLOptions options = XHTMLOptions.create().indent(4);
// 导出图片
String file_path = getFilePath("file_path");
// File imageFolder = new File("d:\\logs\\conver\\image");
File imageFolder = new File(file_path);
if(!imageFolder.getParentFile().exists()){
imageFolder.getParentFile().mkdirs();
}
options.setExtractor(new FileImageExtractor(imageFolder));
// URI resolver
/*options.URIResolver(new IURIResolver() {
@Override
public String resolve(String uri) {
return uri;
}
});*/
//options.URIResolver(new FileURIResolver(imageFolder));
options.URIResolver(new BasicURIResolver(tempPath));
File outFile = new File(desc);
if(!outFile.exists()){
outFile.createNewFile();
}
outFile.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(outFile);
XHTMLConverter.getInstance().convert(document, out, options);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
//word转pdf
public static void wordAdapter2(String src,String desc){
try {
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs, "Open", src, false, true)
.toDispatch();
Dispatch.call(doc, "ExportAsFixedFormat", desc, 17);// word保存为pdf格式宏,值为17
Dispatch.call(doc, "Close", false);
app.invoke("Quit", 0);
}catch(Exception e){
}finally {
ComThread.Release();
}
}
//rtf类型
public static void rtfAdapter(String src,String desc){
try {
RTFEditorKit rtf=new RTFEditorKit();
DefaultStyledDocument dsd=new DefaultStyledDocument();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(desc)));
try {
rtf.read(new FileInputStream(new File(src)), dsd, 0);
String text = new String(dsd.getText(0, dsd.getLength()));
writer.write("
");");
writer.write(text.replaceAll("[ ]"," "));
writer.write("
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//html类型
public static void htmlAdapter(String src,String desc) {
BufferedReader r = null;
BufferedWriter w = null;
try {
r = new BufferedReader(new InputStreamReader(new FileInputStream(src)));
w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(desc)));
if(!new File(desc).exists()){
new File(desc).createNewFile();
}
String line = "";
w.write("
}catch(Exception e){
logger.info(e);
e.printStackTrace();
}finally{
if(r!=null){
try {
r.close();
} catch (IOException e) {
logger.info(e);
e.printStackTrace();
}
}
if(w!=null){
try {
w.close();
} catch (IOException e) {
logger.info(e);
e.printStackTrace();
}
}
}
}
//txt类型文件
public static void txtAdapter(String src,String desc) {
BufferedReader r = null;
BufferedWriter w = null;
try {
r = new BufferedReader(new InputStreamReader(new FileInputStream(src)));
w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(desc)));
// if(!new File(desc).exists()){
new File(desc).createNewFile();
// }
String line = "";
w.write("
");");
while((line = r.readLine()) != null){
//String result = new String(line.getBytes("gbk"),"utf-8");
w.write(line.replaceAll("[ ]"," "));
w.write("
");
}
w.write("
}catch(Exception e){
logger.info(e);
e.printStackTrace();
}finally{
if(r!=null){
try {
r.close();
} catch (IOException e) {
logger.info(e);
e.printStackTrace();
}
}
if(w!=null){
try {
w.close();
} catch (IOException e) {
logger.info(e);
e.printStackTrace();
}
}
}
}
//pdf类型
public static void pdfAdapter(String src,String desc){
try {
PDDocument document = PDDocument.load(new File(src));
document.getClass();
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(desc)));
if(!document.isEncrypted()) {
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
PDFTextStripper tStripper = new PDFTextStripper();
String pdfFileInText = tStripper.getText(document);
String[] lines = pdfFileInText.split("\\r?\\n");
writer.write("
writer.write(line);
writer.write("
");
}
writer.write("
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//复制的方式
public static void pdfAdapter2(String src,String desc){
InputStream is = null;
OutputStream os = null;
try{
is = new FileInputStream(new File(src));
os = new FileOutputStream(new File(desc));
int length = 0;
byte[] b = new byte[1024];
while((length = is.read(b)) != -1){
os.write(b, 0, length);
}
}catch(Exception e){
e.printStackTrace();
}finally {
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void wpsAdapter2(String src, String desc){
try {
InputStream input = new FileInputStream(src);
HWPFDocument wordDocument = new HWPFDocument(input);
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument());
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
public String savePicture(byte[] content, PictureType pictureType,
String suggestedName, float widthInches, float heightInches) {
return suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);
List pics = wordDocument.getPicturesTable().getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
pic.writeImageContent(new FileOutputStream(path
+ pic.suggestFullFileName()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(outStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
outStream.close();
String content = new String(outStream.toByteArray());
FileUtils.writeStringToFile(new File(desc), content, "utf-8");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getDataDir(Class c) {
File dir = new File(System.getProperty("user.dir"));
dir = new File(dir, "src");
dir = new File(dir, "main");
dir = new File(dir, "resources");
return dir.toString() + File.separator;
}
//windows 产品转换为 pdf
public static void windowsToPdf(String src,String desc){
File file = new File(src);
String path = file.getParent();
// src = src.replaceAll("\\\\", "\\\\\\\\");
// path = path.replaceAll("\\\\","\\\\\\\\");
try {
String osName = System.getProperty("os.name");
String command = "";
if (osName.contains("Windows")) {
// command = "soffice --convert-to pdf -outdir " + path + " " + src;
command = "soffice.exe --headless --invisible --convert-to pdf "+src+" --outdir "+path;
} else {
// command = "doc2pdf --output=" + path + File.separator + file.getName().replaceAll(".(?i)docx", ".pdf") + " " + src;
command = "libreoffice6.1 --headless --invisible --convert-to pdf "+src+" --outdir "+path;
}
executeCommand(command);
File temPdf = new File(src.substring(0,src.lastIndexOf("."))+".pdf");
temPdf.renameTo(new File(desc));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
inputStreamReader = new InputStreamReader(p.getInputStream(), "UTF-8");
reader = new BufferedReader(inputStreamReader);
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(inputStreamReader != null){
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(p != null){
p.destroy();
}
}
return output.toString();
}
pom文件如下: