在线预览doc,docx⽂档在线预览doc,docx⽂档
前⾔:上传成功以后的每个⽂档都能获取到所传⽂件的路径;
我这⾥是⼀个maven项⽬,需要在pom⽂件引⼊
<!--⽂件预览-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>xdocreport</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
点击在线预览的时候,前端需要给后台传⼊这条数据的id
需要在你项⽬的static/img下边新建⼀个doc⽂件夹,存放所需要的⽂档;⾥⾯的图⽚ 如图:
先将所需要的东西封装好
l;
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.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
l.parsers.DocumentBuilderFactory;
l.parsers.ParserConfigurationException; l.transform.OutputKeys;
l.transform.Transformer;
l.transform.TransformerException;
l.transform.TransformerFactory;
l.transform.dom.DOMSource;
l.transform.stream.StreamResult;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.verter.PicturesManager; import org.apache.verter.WordToHtmlConverter; import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.BasicURIResolver; import org.apache.FileImageExtractor; import org.apache.verter.xhtml.
XHTMLConverter; import org.apache.verter.xhtml.XHTMLOptions; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.w3c.dom.Document;
public class Doc2Html {
/**
* doc转换为html
*
*
*
* @param
*
*    fileName
*
*            docx⽂件路径(如果你的是存到⽂件服务器的,直接⽤路径,如果是直接将⽂件流存到数据库的,转为InputStream )  *
* @param
*
*    outPutFile
*
*            html输出⽂件路径
*
* @throws TransformerException
* @throws IOException
* @throws ParserConfigurationException
*/
public static void doc2Html(String fileName, String outPutFile, String imgPath)
throws TransformerException, IOException, ParserConfigurationException {
long startTime = System.currentTimeMillis();
// HWPFDocument wordDocument = new HWPFDocument(fileName);
HWPFDocument wordDocument =new HWPFDocument(new FileInputStream(fileName));
WordToHtmlConverter wordToHtmlConverter =new WordToHtmlConverter(
wordToHtmlConverter.setPicturesManager(new PicturesManager(){
public String savePicture(byte[] content, PictureType pictureType, String suggestedName,float widthInches,
float heightInches){
return"/img/doc/"+ suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);
// 保存图⽚
List<Picture> pics = PicturesTable().getAllPictures();
if(pics != null){
for(int i =0; i < pics.size(); i++){
Picture pic =(Picture) (i);
String suggestFullFileName = pic.suggestFullFileName();
System.out.println(suggestFullFileName);
try{
pic.writeImageContent(new FileOutputStream(
imgPath +"/src/main/resources/static/img/doc/"+ pic.suggestFullFileName()));
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
Document htmlDocument = Document();
ByteArrayOutputStream out =new ByteArrayOutputStream();
DOMSource domSource =new DOMSource(htmlDocument);
StreamResult streamResult =new StreamResult(out);
TransformerFactory tf = wInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING,"utf-8");
serializer.setOutputProperty(OutputKeys.INDENT,"yes");
serializer.setOutputProperty(OutputKeys.METHOD,"html");
out.close();
writeFile(new ByteArray()), outPutFile);
System.out.println("Generate "+ outPutFile +" with "+(System.currentTimeMillis()- startTime)+" ms.");
}
/**
* 写⽂件
*
* @param content
* @param content
* @param path
*/
public static void writeFile(String content, String path){
FileOutputStream fos = null;
BufferedWriter bw = null;
try{
File file =new File(path);
fos =new FileOutputStream(file);
bw =new BufferedWriter(new OutputStreamWriter(fos,"utf-8"));
bw.write(content);
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
try{
if(bw != null)
bw.close();
if(fos != null)
fos.close();
}catch(IOException ie){
}
}
}
/**
* docx格式word转换为html
*
* @param fileName
*            docx⽂件路径(如果你的是存到⽂件服务器的,直接⽤路径,如果是直接将⽂件流存到数据库的,转为InputStream )  * @param outPutFile
*            html输出⽂件路径
* @throws TransformerException
* @throws IOException
* @throws ParserConfigurationException
*/
public static void docx2Html(String fileName, String outPutFile, String imgPath)
throws TransformerException, IOException, ParserConfigurationException {
String fileOutName = outPutFile;
long startTime = System.currentTimeMillis();
XWPFDocument document =new XWPFDocument(new FileInputStream(fileName));
// XWPFDocument document = new XWPFDocument(fileName);
XHTMLOptions options = ate().indent(4);
// 导出图⽚
File imageFolder =new File(imgPath +"/src/main/resources/static/img/");
options.setExtractor(new FileImageExtractor(imageFolder));
// URI resolver
// options.URIResolver(new FileURIResolver(imageFolder));
options.URIResolver(new BasicURIResolver("/img/"));
File outFile =new File(fileOutName);
OutputStream out =new FileOutputStream(outFile);
System.out.println("Generate "+ fileOutName +" with "+(System.currentTimeMillis()- startTime)+" ms.");
}
public static void main(String[] args)throws Exception {
// Doc2Html.docx2Html("D:\\测试⽂档.docx","D:\\cs.html");
}
}
调⽤封装好的接⼝
public void devDoc(HttpServletResponse response,int kid)throws Exception { //获取项⽬的路径
String realPath = Property("user.dir");
Long kId =(long) kid;
InputStream input = null;
OutputStream out = null;
CrKnowledge crKnowledge = crKnowledgeService.selectCrKnowledgeById(kId);  CrKnowledgeAttach crKnowledgeAttach =new CrKnowledgeAttach();
crKnowledgeAttach.setKUid(kId);
crKnowledgeAttach.KName());
List<CrKnowledgeAttach> crKnowledgeAttachs = crKnowledgeAttachService
.selectCrKnowledgeAttachList(crKnowledgeAttach);
for(CrKnowledgeAttach crKnowledgeAttach2 : crKnowledgeAttachs){
crKnowledgeAttach.FjUrl());
// 在线预览
//获取⽂件路径
String filePath = UploadPath();
String string = FjUrl().substring(15);
filePath+=string;
//截取⽂件名称(查看获取到的⽂件名是否需要截取,这⾥需要全路径,需要截取)
String filename = FjName();
String caselsh = filename.substring(0,filename.lastIndexOf("."));
FjTag1().equals("docx")){
Doc2Html.docx2Html(filePath,"D:\\"+caselsh+".html",realPath);
input =new FileInputStream("D:\\"+caselsh+".html");
response.setContentType("text/html;charset=UTF-8");// 解决页⾯显⽰乱码
out = OutputStream();
}else FjTag1().equals("doc")){
param nameDoc2Html.doc2Html(filePath,"D:\\"+caselsh+".html",realPath);
input =new FileInputStream("D:\\"+caselsh+".html");
response.setContentType("text/html;charset=UTF-8");// 解决页⾯显⽰乱码
out = OutputStream();
}
FileInputStream fis =new FileInputStream("D:\\"+caselsh+".html");
byte[] b =new byte[fis.available()];
if(out != null){
if(input != null){
out.write(b);
}else{
System.out.println("InputStream为空。。。");
}
}else{
System.out.println("OutputStream为空。。。");
}
out.flush();
input.close();
out.close();
}
}
前端需要传⼀个id直接展⽰就成:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。