Browse Source

init

master
燕鹏 3 years ago
parent
commit
d2f0b916a7
  1. 7
      pom.xml
  2. 90
      src/main/java/com/aiprose/word2pdf/PdfUtils.java
  3. BIN
      src/main/resources/tst.docx

7
pom.xml

@ -32,6 +32,13 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.9.1</version>
</dependency>
</dependencies>
<build>

90
src/main/java/com/aiprose/word2pdf/PdfUtils.java

@ -0,0 +1,90 @@
package com.aiprose.word2pdf;
/**
* @author yanpeng
* @version 1.0
* @desc TODO
* @company 北京中经网软件有限公司
* @date 2022/3/8 11:47
*/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
/**
* 依赖libreoffice实现PDF转化
* @author Dawn
*/
public class PdfUtils {
public static void main(String[] args) {
PdfUtils pdfUtils = new PdfUtils();
String filepath = "F:/word2pdf/tst.docx";
String targetFolder = "F:/word2pdf/";
pdfUtils.toPdf(filepath,targetFolder);
}
/**
*
* @param filePath 原文件路径 本地路径
* @param targetFolder 目标文件夹
*/
@Async
public void toPdf(String filePath,String targetFolder){
long start=System.currentTimeMillis();
String srcPath = filePath, desPath = targetFolder;
System.out.println("源文件:"+filePath);
System.out.println("目标文件夹:"+targetFolder);
String command = "";
String osName = System.getProperty("os.name");
System.out.println("系统名称:"+osName);
if (osName.contains("Windows")) {
command = "soffice --headless --convert-to pdf " + srcPath + " --outdir " + desPath;
windowExec(command);
}else {
command = "libreoffice7.0 --convert-to pdf:writer_pdf_Export " + srcPath + " --outdir "+ desPath;
LinuxExec(command);
}
long end=System.currentTimeMillis();
System.out.println("转换文件耗时:"+(end-start)+"毫秒");
}
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) {
e.printStackTrace();
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){
System.out.println(cmd);
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}

BIN
src/main/resources/tst.docx

Binary file not shown.
Loading…
Cancel
Save