SpringBoot实现本地上传Word文档并在线预览

所需依赖

    	<dependency>
            <groupId>com.itextpdfgroupId>
            <artifactId>itextpdfartifactId>
            <version>5.5.9version>
        dependency>
          
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poiartifactId>
            <version>3.15version>
        dependency>
         <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
            <version>3.15version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxml-schemasartifactId>
            <version>3.15version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>ooxml-schemasartifactId>
            <version>1.3version>
        dependency>
        
        <dependency>
            <groupId>fr.opensagres.xdocreportgroupId>
            <artifactId>xdocreportartifactId>
            <version>1.0.6version>
        dependency>
         <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.11.0version>
        dependency>

       <dependency>
            <groupId>com.lowagiegroupId>
            <artifactId>itextartifactId>
            <version>2.1.7version>
        dependency>
        <dependency>
            <groupId>com.lowagiegroupId>
            <artifactId>itext-rtfartifactId>
            <version>2.1.7version>
        dependency>

2、上传文件到本地文件夹中

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Object> uploadFileToLocal(@RequestParam("multipartFile") MultipartFile multipartFile) {
        if (multipartFile == null) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        File file = null;
        try {
            File dir = new File(basePath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            file = new File(basePath + File.separator + multipartFile.getOriginalFilename());
            if (!file.exists()) {
                multipartFile.transferTo(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(FileVo.builder().size(multipartFile.getSize()).path(file.getAbsolutePath()).build());

    }

basePath为定义的常量: private static final String basePath = “C:\tempFile”;

3、在线预览Word文档

	@GetMapping("/showWord")
    public void showWord(@RequestParam("path")String path, HttpServletResponse response) throws IOException {
        FileInputStream in = new FileInputStream(path);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        byte[] fileByte = out.toByteArray();
        XWPFDocument doc = new XWPFDocument(new ByteArrayInputStream(fileByte));
        PdfOptions options = PdfOptions.create();
        // 中文字体处理
        options.fontProvider((familyName, encoding, len, style, color) -> {
            try {
                BaseFont bfChinese = createFont();
                Font fontChinese = new Font(bfChinese, len, style, color);
                if (familyName != null) {
                    fontChinese.setFamily(familyName);
                }
                return fontChinese;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        });
        PdfConverter.getInstance().convert(doc, out, options);
        outputStream.write(out.toByteArray());
        outputStream.flush();    
    }

    private BaseFont createFont() {
        //仿宋体
        String font_cn = getChineseFont();
        BaseFont chinese = null;
        try {
            chinese = BaseFont.createFont(font_cn, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (com.lowagie.text.DocumentException e) {
            e.printStackTrace();
        }
        return chinese;
    }

    private String getChineseFont() {
        URL resource = this.getClass().getClassLoader().getResource("font/msyh.ttc");
        String urlString = resource.toString();
        String font = urlString.substring(urlString.indexOf("file:") + "file:".length() + 1);
        return font + ",0";
    }

“font/msyh.ttc” 是放在resources目录font文件夹下面的一个字体文件,字体文件可在网上下载或者直接copy电脑中自带的字体文件。

Word文件转换为Pdf预览时,主要是对字体格式进行处理,默认的字体格式有可能再预览时无法显示字体,所以直接做了统一处理。

注意:当压缩包运行项目到服务器上的时候,预览会报错,无法查找到字体文件,我们需要再此时进行特定处理,可以先将字体文件上传至服务器,服务器运行时直接读取服务器绝对地址路径下的字体文件即可。

4、预览效果

SpringBoot实现本地上传Word文档并在线预览_第1张图片

你可能感兴趣的:(Springboot,spring,boot,java)