libreoffice下载地址

https://zh-cn.libreoffice.org/get-help/install-howto/linux/

安装

解压

tar -xvf xxxx.tar.gz

进入解压执行命令

yum install ./LibreOffice_4.x.x_Linux_x86_rpm/RPMS/*.rpm

然后在/opt 下会有文件夹/opt/liberofficex.x

(第一种) java调用

++++++++++++第一种方法,不太推荐++++++++++++++++
依赖

<dependency>
     <groupId>com.github.livesense</groupId>
     <artifactId>jodconverter-core</artifactId>
     <version>1.0.5</version>
 </dependency>
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

import java.io.File;

public class LibreOfficeWordToPDFUtil {
    //需要解决线程安全问题,防止端口重新启动报错被占用加上synchronized 
    public  static synchronized void libreOfficeToPDF(File inputfile, File outputfile) {
          // libreOffice的安装目录
        String LibreOffice_HOME = "/opt/libreoffice7.1";
        DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
        configuration.setOfficeHome(new File(LibreOffice_HOME));
        // 端口号
        configuration.setPortNumber(8100);
        configuration.setTaskExecutionTimeout(1000 * 60 * 20L);
//         设置任务执行超时为20分钟
        configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
//         设置任务队列超时为24小时
        OfficeManager officeManager = configuration.buildOfficeManager();
        officeManager.start();
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        converter.getFormatRegistry();
        try {
            converter.convert(inputfile, outputfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            officeManager.stop();
        }
    }
}

(第二种 推荐) java调用Linux命令转pdf

不需要专门依赖,经测试直接调用Linux命令不需要synchronized同步,反应更快
参数参考(文件名必须要去掉中间的空格字符)
source=“/home/pdfs/first.docx”
targetDir=“/home/to”
结果->目录下生成pdf文件 /home/to/first.pdf
方法的status正常输出为0

public static String doc2pdf(String source,String targetDir){
        String cmd="libreoffice7.1 --convert-to pdf:writer_pdf_Export "+source+" --outdir "+targetDir;
        Integer status=null;
        Process process=null;
        try {
            process=Runtime.getRuntime().exec(cmd);
            status = process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            process.destroy();
        }
        return "ok  NOT synchronized"+status;
    }

java远程连接Linux执行命令(少数情况)

依赖

<dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
</dependency>

小案例:测试Linux里 jpg 和 png 的文件数量
参数说明 like可自行设置,这里没用上这个参数

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public void connectLinux(String like,String hostname, String username,String password){
		Connection con=null;
        try {
            con = new Connection(hostname);
            con.connect();
            //登录
            boolean islog = con.authenticateWithPassword(username, password);
            // 是否登录成功
            if (islog== false) {
                throw new IOException("登录失败");
            }
            if (con != null) {
                Session session = con.openSession();
                //一个session只能执行一条命令,多条可拼接"\n"
                //如果要分开多次命令,可再一次openSession
                //Session s2=con.openSession();
                //s2.execCommand("ps -ef|grep java*");
                session.execCommand("cd /home/ftp\n ls -lR ./|grep '.jpg'  |wc -l\n  ls -lR ./|grep '.png'  |wc -l");
                InputStream stdout = new StreamGobbler(session.getStdout());
                BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
                while (true) {
                    String line = br.readLine();
                    if (line == null) {
                        break;
                    }
                    System.out.println(line+"个======文件");
                }
                System.out.println("ExitCode:" + session.getExitStatus());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            // 关闭连接
            session.close();
            con.close();
		}
    }

linux安装windows中文字体解决pdf乱码

复制C:\windows\Fonts里的字体到linux下的/usr/share/fonts/chinese
直接把文件夹复制过去然后把Fonts改名chinese
linux下若没有目录就创建目录

进入chinese
执行

sudo fc-cache -fv

如果 fc-cache 未找到命令

yum install lsb

生效

source /etc/profile

查看是否有了中文字体

fc-list  |wc -l
fc-list :lang=zh-cn | sort

pdf加水印

依赖

<dependency>
       <groupId>com.itextpdf.tool</groupId>
       <artifactId>xmlworker</artifactId>
       <version>5.5.10</version>
</dependency>
<dependency>
       <groupId>com.itextpdf</groupId>
       <artifactId>itextpdf</artifactId>
       <version>5.5.10</version>
</dependency>
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;

import java.io.FileOutputStream;

public class PDFWaterUtil {
    public static void addPDFWater(String pdfFilePath, String outputFilePath) {
        try {
            // 原PDF文件
            PdfReader reader = new PdfReader(pdfFilePath);
            // 输出的PDF文件内容
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFilePath));
            BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
//            BaseFont baseFont = BaseFont.createFont("/usr/share/fonts/chinese/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
            //BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            // 设置透明度
            gs.setFillOpacity(0.3f);
            gs.setStrokeOpacity(0.4f);
            //页数
            int totalPage = reader.getNumberOfPages() + 1;
            for (int i = 1; i < totalPage; i++) {
                // 内容上层
//			PdfContentByte content = stamper.getOverContent(i);
                // 内容下层
                PdfContentByte content = stamper.getUnderContent(i);
                content.beginText();
                // 字体添加透明度
                content.setGState(gs);
                // 添加字体大小等
                content.setFontAndSize(baseFont, 50);
                // 添加范围
                content.setTextMatrix(70, 200);
                // 具体位置 内容 旋转多少度 共360度
                 content.showTextAligned(Element.ALIGN_CENTER, "logotext", 100, 0, 300);
                 content.showTextAligned(Element.ALIGN_CENTER, "logotext", 200, 80, 300);
                 content.showTextAligned(Element.ALIGN_CENTER, "logotext", 300, 180, 300);
                 content.showTextAligned(Element.ALIGN_CENTER, "logotext", 400, 280, 300);
                 content.endText();
            }
            // 关闭
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Logo

更多推荐