jquery.media.js实现前端页面预览

邵繁
2023-12-01

前端代码

<body>  
<section layout:fragment="content">  
    <div class="form-group">  
        <div class="col-md-6">  
            <button type="button" class="btn btn-default" onclick="toView('D:\\2.doc')">预览doc</button>  
            <button type="button" class="btn btn-default" onclick="toView('D:\\3.docx')">预览docx</button>  
            <button type="button" class="btn btn-default" onclick="toPdfView('D:\\4.pdf')">预览pdf</button>  
            <button type="button" class="btn btn-default" onclick="toPdfView('D:\\5.pdf')">预览pdf</button>  
        </div>  
    </div>  
    <div class="modal fade" aria-labelledby="预览" aria-hidden="true" id="previewModal">  
        <div class="modal-dialog" style="width:1000px;height:800px;">  
            <div class="modal-content">  
                <div class="modal-header">  
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>  
                </div>  
                <div class="modal-body"></div>  
            </div>  
        </div>  
    </div>  
    <script type="text/javascript" src="js/jquery.media.js" th:src="@{/js/jquery.media.js}"></script>  
    <script th:inline="javascript">  
    function toView(filePath){  
        var url = [[@{/converter/preview}]]+'?filePath='+filePath;  
        $(".modal-body").empty();  
        $(".modal-body").load(url);  
        $("#previewModal").modal();  
    }  
      
    function toPdfView(filePath){  
        var url = [[@{/converter/viewPdf}]]+'?filePath='+filePath;  
        $(".modal-body").empty();  
        $(".modal-body").append('<a class="media">预览pdf</a>');  
        $("a.media").attr("href",[[@{/converter/viewPdf}]]+'?filePath='+filePath);  
        $("#previewModal").modal();  
        $("a.media").attr("href",url)  
        $("a.media").media({width:960,height:800});  
    }  
      
    $("#previewModal").on("hide.bs.modal",function(){  
        $(this).removeData("bs.modal");  
    });  
    </script>  
</section>  
</body> 

java代码

    import java.awt.Image;  
    import java.awt.image.BufferedImage;  
    import java.io.BufferedOutputStream;  
    import java.io.ByteArrayInputStream;  
    import java.io.ByteArrayOutputStream;  
    import java.io.File;  
    import java.io.FileInputStream;  
    import java.io.IOException;  
    import java.io.InputStream;  
      
    import javax.imageio.ImageIO;  
    import javax.servlet.http.HttpServletResponse;  
      
    import org.slf4j.Logger;  
    import org.slf4j.LoggerFactory;  
    import org.springframework.beans.factory.annotation.Value;  
    import org.springframework.stereotype.Controller;  
    import org.springframework.web.bind.annotation.RequestMapping;  
    import org.springframework.web.bind.annotation.RequestParam;  
      
    import com.bjdjjs.utils.converter.WordToHtml;  
      
    @Controller  
    @RequestMapping(value = "/converter")  
    public class OfficeConterverController {  
          
        protected final Logger logger = LoggerFactory.getLogger(OfficeConterverController.class);  
          
        @Value("${image.temp.folder}")  
        private String ImageTempFolder;  
          
        @Value("${server.context-path}")  
        private String contextPath;  
          
        @RequestMapping(value = "/preview")  
        public String preview(HttpServletResponse response,  
                @RequestParam(value = "filePath", required=true) String filePath){  
            logger.info("预览文件:"+filePath);  
            WordToHtml wh = new WordToHtml(ImageTempFolder,contextPath);  
            ByteArrayOutputStream htmlOutputStream = wh.change(filePath);  
            try{  
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());  
                bos.write(htmlOutputStream.toByteArray());  
                bos.close();  
                htmlOutputStream.flush();  
            }catch (Exception e) {  
                e.printStackTrace();  
            } finally{  
                if(htmlOutputStream != null){  
                    try {  
                        htmlOutputStream.close();  
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
            return null;  
        }  
          
        @RequestMapping(value = "/viewPdf")  
        public String viewPdf(HttpServletResponse response,  
                @RequestParam(value = "filePath", required=true) String filePath){  
            logger.info("预览文件:"+filePath);  
            response.setContentType("application/pdf");  
            try{  
                InputStream pdfInputStream = new FileInputStream(filePath);  
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());  
                int pdfByte;  
                while((pdfByte = pdfInputStream.read()) != -1){  
                    bos.write(pdfByte);  
                }  
                pdfInputStream.close();  
                bos.close();  
                  
            }catch (Exception e) {  
                e.printStackTrace();  
                return null;  
            }   
            return null;  
        }  
          
        @RequestMapping(value = "/fetchImage")  
        public String fetchImage(HttpServletResponse response,  
                @RequestParam(value = "n", required=true) String fileName){  
            logger.info("获取图片:"+fileName);  
            try {  
                BufferedImage image = ImageIO.read(new File(ImageTempFolder+fileName));  
                ImageIO.write(image, "png", response.getOutputStream());  
                response.setContentType("image/png");  
                ImageIO.write(image, "png", response.getOutputStream());  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            return null;  
        }  
          
        @RequestMapping(value = "/test")  
        public String test(){  
            logger.info("测试页面");  
            return "test/preview";  
        }  
          
    }  

工具类

    package com.bjdjjs.utils.converter;  
      
    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.InputStream;  
    import java.util.List;  
      
    import javax.imageio.ImageIO;  
    import javax.xml.parsers.DocumentBuilderFactory;  
    import javax.xml.parsers.ParserConfigurationException;  
    import javax.xml.transform.OutputKeys;  
    import javax.xml.transform.Transformer;  
    import javax.xml.transform.TransformerException;  
    import javax.xml.transform.TransformerFactory;  
    import javax.xml.transform.dom.DOMSource;  
    import javax.xml.transform.stream.StreamResult;  
      
    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.core.FileURIResolver;  
    import org.apache.poi.xwpf.converter.core.IURIResolver;  
    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.poi.xwpf.usermodel.XWPFPictureData;  
    import org.slf4j.Logger;  
    import org.slf4j.LoggerFactory;  
    import org.w3c.dom.Document;  
      
      
    public class WordToHtml {  
          
        protected final Logger logger = LoggerFactory.getLogger(WordToHtml.class);  
          
        private String ImageTempFolder;  
          
        private String contextPath;  
          
        //返回图片请求地址  
        private static String ImageRequestMap = "/converter/fetchImage?n=";  
          
        private static String WORD2003 = "doc";  
          
        private static String WORD2007 = "docx";  
          
        public WordToHtml(String imageTempFolder,String contextPath){  
            this.ImageTempFolder = imageTempFolder;  
            this.contextPath = contextPath;  
        }  
          
        public  ByteArrayOutputStream change(String filePath) {  
             int index = filePath.lastIndexOf(".");  
             String fileType = filePath.substring(index+1, filePath.length());  
             try {  
                 if(WORD2003.equalsIgnoreCase(fileType))  
                    return convert2Html(filePath);    
                 else if(WORD2007.equalsIgnoreCase(fileType))  
                     return xconvert2Html(filePath);  
                } catch (Exception e) {    
                    e.printStackTrace();  
                }  
             return null;  
        }  
          
        public  ByteArrayOutputStream convert2Html(String filePath)    
                throws TransformerException, IOException,    
                ParserConfigurationException {    
            HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(filePath));//创建一个文档    
            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 contextPath+ImageRequestMap+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);    
                    System.out.println();    
                    try {    
                        pic.writeImageContent(new FileOutputStream(ImageTempFolder    
                                + pic.suggestFullFileName()));    
                    } catch (FileNotFoundException e) {    
                        e.printStackTrace();    
                    }      
                }    
            }    
            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();    
            return out;  
        }   
          
        public ByteArrayOutputStream xconvert2Html(String filePath)    
                throws TransformerException, IOException,    
                ParserConfigurationException {    
            InputStream inputStream = new FileInputStream(new File(filePath));  
            XWPFDocument document = new XWPFDocument(inputStream);  
            XHTMLOptions options = XHTMLOptions.create().indent(1);  
            File imageFolderFile =new File(ImageTempFolder);  
            FileImageExtractor extractor = new FileImageExtractor(imageFolderFile);  
            options.setExtractor(extractor);  
            options.setIgnoreStylesIfUnused(false);  
            options.setFragment(true);  
            options.URIResolver(new BasicURIResolver(contextPath+ImageRequestMap));  
            ByteArrayOutputStream out = new ByteArrayOutputStream();   
            XHTMLConverter.getInstance().convert(document, out, options);  
            out.close();  
            return out;  
        }   
    }  

 

 类似资料: