一、卸载系统当前的libreoffice并安装新的,执行如下命令:
yum remove libreoffice-*
在命令行执行libreoffice --version,检查是否已经安装LibreOffice。
1、在centos7下安装LibreOffice,可直接使用yum安装即可,在命令行输入以下命令:
yum install libreoffice
yum install libreoffice-headless
安装完成后,生成的二进制文件所在位置为:
/usr/bin/libreoffice
2、通过libreoffice转换pdf文档,执行以下命令即可转换文档(可转换ppt、pptx和doc、docx):
libreoffice --headless --convert-to pdf {文档路径} --outdir {导出目录路径}
执行命令一直报错:
soffice --headless --convert-to pdf /data/minio/data/files/专家_1660100454352.docx --outdir /data/minio/data/files
最后执行成功
解决办法:
1、保证有文件读写权限,用root账号 chmod 777 *为佳
2、安装原因是少装了LibreOffice的writer,直接执行:
yum install libreoffice-writer
3、安装汉化包保证转换的汉字不乱码
4、具体相关代码(返回文件流给前端vue)
二、代码相关:
控制层:
package com.sxlinks.modules.system.controller;
import com.sxlinks.modules.system.service.textbook.impl.TextbookFileServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import com.sxlinks.common.api.vo.Result;
import com.sxlinks.common.util.CommonUtils;
import com.sxlinks.common.util.MinioUtil;
import com.sxlinks.common.util.oConvertUtils;
import com.sxlinks.modules.oss.entity.OSSFile;
import com.sxlinks.modules.oss.service.IOSSFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* minio文件上传示例
*/
@Api(tags="pc-文件服务")
@Slf4j
@RestController
@RequestMapping("/sys/upload")
public class SysUploadController {
@Autowired
private IOSSFileService ossFileService;
@Resource
private TextbookFileServiceImpl textbookFileServiceImpl;
/**
* 上传
*
* @param request
*/
@ApiOperation(value = "上传")
@PostMapping(value = "/uploadMinio")
public Result uploadMinio(HttpServletRequest request) {
String bizPath = request.getParameter("biz");
if (oConvertUtils.isEmpty(bizPath)) {
bizPath = "";
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
String orgName = file.getOriginalFilename();// 获取文件名
orgName = CommonUtils.getFileName(orgName);
String file_url = MinioUtil.upload(file, bizPath);
if (oConvertUtils.isEmpty(file_url)) {
return Result.error("上传失败,请检查配置信息是否正确!");
}
//保存文件信息
OSSFile minioFile = new OSSFile();
minioFile.setFileName(orgName);
minioFile.setUrl(file_url);
ossFileService.save(minioFile);
minioFile.setFileUrl(file_url);
minioFile.setType(orgName.substring(orgName.lastIndexOf(".") + 1));
minioFile.setFileSize(file.getSize());
return Result.OK("操作成功", minioFile);
}
/**
* 上传
*
* @param
*/
@ApiOperation(value = "上传2")
@PostMapping(value = "/uploadMulti")
public Result uploadMulti(@RequestPart MultipartFile file,HttpServletResponse response) throws Exception {
String orgName = file.getOriginalFilename();// 获取文件名
orgName = CommonUtils.getFileName(orgName);
String file_url = MinioUtil.upload(file, "");
if (oConvertUtils.isEmpty(file_url)) {
return Result.error("上传失败,请检查配置信息是否正确!");
}
//mp4处理传前端相对地址
if (file_url.contains(".mp4")) {
file_url = file_url.substring(file_url.indexOf("/files"));
System.out.println(file_url);
}
if (file_url.contains(".ppt") || file_url.contains(".pptx") || file_url.contains(".pdf") || file_url.contains(".docx") || file_url.contains(".doc")) {
file_url = file_url.substring(file_url.indexOf("/files"));
System.out.println(file_url);
String newFileName = file_url.substring(7);
//上传时就转换为pdf
findInfoPdf(newFileName);
}
//保存文件信息
OSSFile minioFile = new OSSFile();
minioFile.setFileName(orgName);
minioFile.setUrl(file_url);
ossFileService.save(minioFile);
minioFile.setFileUrl(file_url);
minioFile.setType(orgName.substring(orgName.lastIndexOf(".") + 1));
minioFile.setFileSize(file.getSize());
return Result.OK("操作成功", minioFile);
}
/**
* pdf文件预览自己写的测试方法
*
* @param request
* @param response
* @return
* @throws
*/
@GetMapping(value = "/preview")
@ApiOperation(value = "PDF文件预览")
public void reviewPriceData(@RequestParam(name = "pdfPath", defaultValue = "") String pdfPath, HttpServletRequest request, HttpServletResponse response) throws Exception {
// 获取pdf文件路径(包括文件名)
String tpdfPath = "D:\\test.pdf";
FileInputStream in = new FileInputStream(tpdfPath);
// 设置输出的格式
response.setContentType("application/pdf");
OutputStream outputStream = response.getOutputStream();
int count = 0;
byte[] buffer = new byte[1024 * 1024];
while ((count = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, count);
}
outputStream.flush();
}
/**
* ppt或doc转pdf,并返还minio文件路径给前端,直接进行预览pdf
*/
public void findInfoPdf(@RequestParam(name = "fileName",required=true) String fileName) throws Exception {
try {
ossFileService.findInfoPdf(fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Service层:
实现层:
package com.sxlinks.modules.oss.service.impl;
import ch.qos.logback.core.util.CloseUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxlinks.common.util.CommonUtils;
import com.sxlinks.common.util.oss.OssBootUtil;
import com.sxlinks.modules.oss.entity.OSSFile;
import com.sxlinks.modules.oss.mapper.OSSFileMapper;
import com.sxlinks.modules.oss.service.IOSSFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Slf4j
@Service("ossFileService")
public class OSSFileServiceImpl extends ServiceImpl<OSSFileMapper, OSSFile> implements IOSSFileService {
@Value(value = "${jeecg.path.upload}")
private String uploadPath;
// private long pdf_timeout = 5 * 60 * 1000;
@Override
public void upload(MultipartFile multipartFile) throws IOException {
String fileName = multipartFile.getOriginalFilename();
fileName = CommonUtils.getFileName(fileName);
OSSFile ossFile = new OSSFile();
ossFile.setFileName(fileName);
String url = OssBootUtil.upload(multipartFile,"upload/test");
//update-begin--Author:gaoliang Date:20201227 for:JT-361【文件预览】阿里云原生域名可以文件预览,自己映射域名kkfileview提示文件下载失败-------------------
// 返回阿里云原生域名前缀URL
ossFile.setUrl(OssBootUtil.getOriginalUrl(url));
//update-end--Author:gaoliang Date:20201227 for:JT-361【文件预览】阿里云原生域名可以文件预览,自己映射域名kkfileview提示文件下载失败-------------------
this.save(ossFile);
}
@Override
public boolean delete(OSSFile ossFile) {
try {
this.removeById(ossFile.getId());
OssBootUtil.deleteUrl(ossFile.getUrl());
}
catch (Exception ex) {
return false;
}
return true;
}
@Override
public void findInfoPdf(String fileName) throws Exception {
log.info("begin to transfer!!!");
//默认文件为linux下的/data/minio/data/files目录下
String filesPath = uploadPath;
String file2PdfPath =filesPath+File.separator+fileName;
FileInputStream is = new FileInputStream(file2PdfPath);
//取文件的类型
String fileType = file2PdfPath.substring(file2PdfPath.lastIndexOf(".") + 1);
log.info("file2PdfPath:"+file2PdfPath+" and file2PdfPath:"+fileType);
// response.setHeader("Content-Disposition", "inline;filename*=utf-8''" + fileName);
// response.setContentType("application/pdf");
//利用libreoffice将word转pdf,保持样式内容100%还原
//需要改的原文件名字,不含文件后缀
String originalName = fileName.substring(0, fileName.lastIndexOf("."));;
//转化为PDF后的文件名
String pdfName = originalName + ".pdf";
Path path = Paths.get(pdfName);
log.info("开始将{}转换成{}", originalName, pdfName);
if (Files.exists(path)) {
log.info("转换后的pdf文件已存在,不进行转换直接展示");
return;
}
String osName = System.getProperty("os.name");
String command = "";
if (osName.contains("Windows")) {
// ./表示输出到当前目录
command = "soffice --headless --convert-to pdf " + originalName + " --outdir ./";
windowExec(command);
} else {
command = command +"sudo libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + file2PdfPath + " --outdir /data/minio/data/files";
LinuxExec(command);
log.info("成功执行command");
}
//调一下系统命令的执行是异步的,在这里监听下文件是否生成
//
// long startTime = System.currentTimeMillis();
// while (!Files.exists(path) && (System.currentTimeMillis() - startTime) < pdf_timeout) {
// }
// if (!Files.exists(path)) {
// log.info("{}删除{}", originalName, FileUtils.deleteQuietly(new File(originalName)) ? "成功" : "失败");
// }
// //转换为文件流给前端vue
// FileCopyUtils.copy(new FileInputStream(pdfName), response.getOutputStream());
// //删除文件
// log.info("{}删除{}", originalName, FileUtils.deleteQuietly(new File(originalName)) ? "成功" : "失败");
// log.info("{}删除{}", pdfName, FileUtils.deleteQuietly(new File(pdfName)) ? "成功" : "失败");
// CloseUtil.closeQuietly(is);
}
private boolean windowExec(String command) {
Process process;// Process可以控制该子进程的执行或获取该子进程的信息
try {
process = Runtime.getRuntime().exec(command);// exec()方法指示Java虚拟机创建一个子进程执行指定的可执行程序,并返回与该子进程对应的Process对象实例。
// 下面两个可以获取输入输出流
InputStream errorStream = process.getErrorStream();
InputStream inputStream = process.getInputStream();
} catch (IOException e) {
return false;
}
int exitStatus = 0;
try {
exitStatus = process.waitFor();// 等待子进程完成再往下执行,返回值是子线程执行完毕的返回值,返回0表示正常结束
// 第二种接受返回值的方法
int i = process.exitValue(); // 接收执行完毕的返回值
} catch (InterruptedException e) {
return false;
}
process.destroy(); // 销毁子进程
process = null;
return true;
}
private void LinuxExec(String cmd) throws IOException {
log.info("命令:{}", cmd);
Runtime.getRuntime().exec(cmd);
}
}
上面不知道怎么回事,格式被打乱,见谅。主要写大概思路,具体的util类,网上也特别全,就省略了,以上至此。
标签:word,String,url,centos7,--,file,ppt,import,pdf From: https://www.cnblogs.com/CarlJohnson9527/p/17663933.html