mongodb 下載word 二進位制流檔案 轉出html檔案
@RequestMapping(value="/getyjpllook",produces="application/json;charset=UTF-8")
public void getyjpllook(String plid)throws Throwable {
String filepath = "C:/html";
File file1=new File(filepath);
if(!file1.exists()){
file1.mkdir();
}
String picturesPath = filepath+"/image/";
File picturesDir = new File(picturesPath);
if(!picturesDir.exists()){
picturesDir.mkdir();
}
String content = null;
//InputStream in =new FileInputStream(new File(docFile));
TbfileSelect tbfileSelect = new TbfileSelect();
tbfileSelect.setPlanid(plid);
List<Tbfile> filelist = tbfileservice.getTbfileListByplanid(tbfileSelect);
ByteAndInfo bi = gsMongoClient.getByteAndInfo(InDomainCommConst.PLAN_NAME,filelist.get(0).getId());
ByteArrayInputStream input = new ByteArrayInputStream(bi.getByteFile());
String[] strArray = bi.getName().split("\\.");
if(strArray[strArray.length -1].equals("docx")){
XWPFDocument document = new XWPFDocument(input);
XHTMLOptions options = XHTMLOptions.create();
options.setExtractor(new FileImageExtractor(picturesDir));
options.URIResolver(new BasicURIResolver(picturesPath));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XHTMLConverter.getInstance().convert(document, baos, options);
baos.close();
content = baos.toString();
}else{
HWPFDocument wordDocument =new HWPFDocument(input);
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
wordToHtmlConverter.setPicturesManager(new PicturesManager(){
@Override
public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches,
float heightInches) {
File file = new File(picturesPath + suggestedName);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(file);
fos.write(content);
fos.close();
}catch(Exception e){
e.printStackTrace();
}
return picturesPath + suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);
org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
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);
out.close();
content = new String(out.toByteArray());
}
File fileyl = new File("C:/html");
if(fileyl.exists()) {//刪除原來的舊檔案
fileyl.delete();
}
FileUtils.writeStringToFile(new File("C:/html", "預覽.html"), content, "utf-8");
// File file = new File("預覽.html");
//Runtime ce=Runtime.getRuntime();
// ce.exec("cmd /c start "+fileyl.getAbsolutePath()+"/預覽.html");//