2020-10-22

it2025-08-06  6

com.documents4j documents4j-local 1.1.1 com.documents4j documents4j-transformer-msoffice-word 1.1.1 import com.documents4j.api.DocumentType;import com.documents4j.api.IConverter;import com.documents4j.job.LocalConverter;/** * 文档文件预览 */ @RequestMapping(path = "/previewFile") public void preview(HttpServletResponse response, @RequestParam(required = true)String path, @RequestParam(required = true)String fileName, @RequestParam(required = true)String suffix) throws Exception { // 读取pdf文件的路径 String pdfPath=""; // 将对应的后缀转换成小写 String lastSuffix=suffix.toLowerCase(); //读取文件内容,获取文件存储的路径 String orgPath = filePath + path; // 生成pdf文件的路径 String toPath = filePath + "pdf/"; // 判断对应的pdf是否存在,不存在则创建 File folder = new File(toPath); if (!folder.exists()) { folder.mkdirs(); } // doc类型 if (lastSuffix.equals("pdf")) { // pdf 文件不需要转换,直接从上传文件路径读取即可 pdfPath=orgPath; } else { // 转换之后的pdf文件 String newName=fileName.replace(lastSuffix,"pdf");; File newFile = new File( toPath+"/"+newName); // 如果转换之后的文件夹中有转换后的pdf文件,则直接从里面读取即可 if (newFile.exists()) { pdfPath =toPath+"/"+newName; }else { pdfPath = wordToPdf(fileName,orgPath, toPath,lastSuffix); } } // 读取文件流上 FileInputStream fis = new FileInputStream(pdfPath); //设置返回的类型 response.setContentType("application/pdf"); //得到输出流,其实就是发送给客户端的数据。 OutputStream os = response.getOutputStream(); try { int count = 0; //fis.available()返回文件的总字节数 byte[] buffer = new byte[fis.available()]; //read(byte[] b)方法一次性读取文件全部数据。 while ((count = fis.read(buffer)) != -1) os.write(buffer, 0, count); os.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (os != null) os.close(); if (fis != null) fis.close(); } }

/** * 将之前对应的word文件转换成pdf,然后预览pdf文件 */ public String wordToPdf(String orgFile,String orgPath, String toPath, String suffix ){ // 转换之后的pdf文件 String targetFile=orgFile.replace(suffix,“pdf”); File inputWord = new File(orgPath); File outputFile = new File(toPath+targetFile); try { InputStream docxInputStream = new FileInputStream(inputWord); OutputStream outputStream = new FileOutputStream(outputFile); IConverter converter = LocalConverter.builder().build(); if(suffix.equals(“doc”)){ converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute(); } else if(suffix.equals(“docx”)){ converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute(); } else if(suffix.equals(“txt”)){ converter.convert(docxInputStream).as(DocumentType.TEXT).to(outputStream).as(DocumentType.PDF).execute(); } outputStream.close(); } catch (Exception e) { e.printStackTrace(); } return toPath+targetFile; }

最新回复(0)