首页 > 系统相关 >centos7下安装libreoffice供word和ppt转pdf预览使用

centos7下安装libreoffice供word和ppt转pdf预览使用

时间:2023-08-29 09:45:45浏览次数:34  
标签:word String url centos7 -- file ppt import pdf

一、卸载系统当前的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

相关文章

  • centos7.9+php+apache 配置阿里云ssl
     1、前往阿里云官网申请免费证书选择 2、证书存放在/etc/cert 3、httpd.cof配置ssl<VirtualHost_default_:443> ServerName域名 DocumentRoot网站根目录 SSLEngineon SSLProtocolall-SSLv2-SSLv3 SSLCipherSuiteHIGH:!RC4:!MD5:!aNULL:!eNULL:!NULL:......
  • Centos7 安装 seata1.7.0
    seata官网: https://seata.io/zh-cn/index.htmlseata下载地址:   https://github.com/seata/seata 1、下载seata包wgethttps://github.com/seata/seata/releases/download/v1.7.0/seata-server-1.7.0.tar.gz2、解压tarzxvfseata-server-1.7.0.tar.gz-C/......
  • .NET Core使用NPOI导出复杂Word详解
    前言:最近使用NPOI做了个导出Word文档的功能,关于使用.NETCore导出Word文档的方式有很多。最终我为什么选择了NPOI来实现了这个功能,首先是NPOI是一个开源,免费且容易上手的第三方框架(并且现在已支持.NETCore,GitHub源码地址:https://github.com/tonyqus/npoi)。因为之前使用NP......
  • python使用docx向word文档中表格插入图片并固定缩放
    使用python的docx模块对word文档进行编辑时,有时候需要向表格中插入图片,但是插入的图片一般是按照原图片的大小插入的,即使你的word文档一开始就设置好了固定宽高,似乎也是不起作用,这个时候就需要在插入后,用python去调整图片的宽高。示例代码:fromdocximportDocumentfromdocxi......
  • centos7 python3安装注意点
    1.安装,参考网上教程,不再重复赘述https://www.cnblogs.com/mindtechnist/p/17243882.html2.注意点:网上多数文章中为了方便,会直接在/usr/bin目录下重建python的软链接,指向python3,由于centos默认的python版本为2.7,2和3无法兼容,故会导致很多基础组件出现调用异常,如yum、firewall-cm......
  • 10在centos7安装RabbitMQ Server
    一.erlang环境安装erlang语言环境和RabbitMQ版本的对应关系如下:https://www.rabbitmq.com/which-erlang.html  本次安装RabbitMQ 3.11.20 和erlang25.3.2.5进入erlang官网下载https://www.erlang.org/patches/otp-25.3.2.5 安装编译环境yuminstallmakeg......
  • Centos7防火墙关闭和启用iptables操作
    Centos7防火墙关闭和启用iptables操作_小戴BOTAOY演示博客(yii666.com) 前序还是docker惹得最近做的系统都是上的centos7的系统带来的一系列的新环境的适应补记下:在使用oraclevmbox虚拟centos7的时候选用桥接网络的时候一定要记得插网线,无线不好使(浪费了一上午的时间的教......
  • Docker方式安装wordpress
    准备拉取wordpress,mysql镜像dockerpullwordpressdockerpullmysql启动wordpress,mysql容器启动wordpress容器,将容器80端口映射到主机端口8080dockerrun-d-p8080:80--namewordpress01wordpress启动mysql容器,映射数据库端口到主机的3306,设置root密......
  • office-js操作word
    office-js是一个用于操作Word文档的JavaScript库,它允许你在Word文档中创建、读取、编辑和删除内容。以下是一些常用的方法及其详细参数说明: 1.**Word.run**:运行一个Word宏。你需要提供一个包含宏代码的字符串。   ```javascript  constword=require('......
  • centos7.6 anaconda安装python
    在CentOS7.6上安装Anaconda并配置Python3.8.17环境可以按照以下步骤进行操作:下载Anaconda:首先,前往Anaconda官网下载适用于Linux的Anaconda安装包。选择适合你操作系统位数的版本(通常是64位)。下载链接:https://www.anaconda.com/products/distribution安装......