需求:
每天都执行,把一个文件夹中的(ppt.doc.docx.csv.txt.xlsx.....)文件转换为pdf,并添加水印功能
JacobController类
package com.jacob.JacobDemo.Controller;
import com.jacob.JacobDemo.util.ToPdf;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@PropertySource("classpath:file.properties")
@RestController
@RequestMapping("/hello")
public class JacobController {
private static final int wdFormatPDF = 17; // PDF 格式
private static final int xlTypePDF = 0; // xls格式
@Value("${filesrc}")
private String filesrc;
@Value("${filepdfsrc}")
private String filepdfsrc;
@Value("${filepdfchangesrc}")
private String filepdfchangesrc;
@Value("${filebackupsrc}")
private String filebackupsrc;
@RequestMapping("")
public String hello() {
return "hello jacob";
}
@Scheduled(cron = "0 8 11 * * ?")
public void Jacob() {
System.out.println("定时调度开启-------------------------------------");
SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
String fould = s.format(new Date());
try {
File baseFile = new File(filesrc);
File[] files = baseFile.listFiles();
for (File file : files) {
String src1 = filesrc + File.separator + file.getName();//待转换路径
String src2 = filepdfsrc + File.separator + fould +File.separator + file.getName().split("\\.")[0]+".pdf";//生成pdf路径
String src3 = filepdfchangesrc + File.separator + fould +File.separator +file.getName().split("\\.")[0]+".pdf";//生成pdf+水印路径
String src4 = filebackupsrc + File.separator + fould +File.separator + file.getName();;//转换成功备份路径
File file1 = new File(filesrc);
File file2 = new File(filepdfsrc + File.separator + fould);
File file3 = new File(filepdfchangesrc + File.separator + fould);
File file4 = new File(filebackupsrc + File.separator + fould);
if (!file1.exists()) {
file1.mkdirs();// 创建文件根目录
}
if (!file2.exists()) {
file2.mkdirs();// 创建文件根目录
}
if (!file3.exists()) {
file3.mkdirs();// 创建文件根目录
}
if (!file4.exists()) {
file4.mkdirs();// 创建文件根目录
}
try {
Boolean b = ToPdf.toPDF(src1, src2);
if(b) {
Boolean c = ToPdf.waterMark(src2, src3, "仅限际恒锐智使用,其他无效,仅限际恒锐智使用,其他无效");
if(c) {
//转换成功文件移动
File oldName=new File(src1);
File newName = new File(src4);
oldName.renameTo(newName);
}
}
}catch(Exception e) {
System.out.println("转换失败文件名为:"+file.getName());
e.printStackTrace();
}
}
}catch(Exception e) {
e.printStackTrace();
System.out.println("定时调度异常-------------------------------------");
}
System.out.println("定时调度结束-------------------------------------");
}
}
ToPdf类
package com.jacob.JacobDemo.util;
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import java.io.FileOutputStream;
public class ToPdf {
private static final int wdFormatPDF = 17; // PDF 格式
private static final int xlTypePDF = 0; // xls格式
public static boolean toPDF(String sfileName, String toFileName) {
System.out.println("------开始转换------");
String suffix = getFileSufix(sfileName);
File file = new File(sfileName);
if (!file.exists()) {
System.out.println("文件不存在!");
return false;
}
if (suffix.equals("pdf")) {
System.out.println("PDF not need to convert!");
return false;
}
if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt") || suffix.equals("csv")) {
return word2PDF(sfileName, toFileName);
} else if (suffix.equals("ppt") || suffix.equals("pptx")) {
return ppt2PDF(sfileName, toFileName);
} else if (suffix.equals("xls") || suffix.equals("xlsx")) {
return excel2PDF(sfileName, toFileName);
} else {
System.out.println("文件格式不支持转换!");
return false;
}
}
// 转换word文档
public static boolean word2PDF(String sfileName, String toFileName) {
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null;
boolean result = true;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
doc = Dispatch.call(docs, "Open", sfileName).toDispatch();
System.out.println("打开文档..." + sfileName);
System.out.println("转换文档到 PDF..." + toFileName);
File tofile = new File(toFileName);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc, "SaveAs", toFileName, wdFormatPDF);
long end = System.currentTimeMillis();
System.out.println("转换完成..用时:" + (end - start) + "ms.");
result = true;
} catch (Exception e) {
System.out.println("========Error:文档转换失败:" + e.getMessage());
result = false;
} finally {
Dispatch.call(doc, "Close", false);
System.out.println("关闭文档");
if (app != null) {
app.invoke("Quit", new Variant[] {});
}
}
ComThread.Release();
return result;
}
// 转换excel文档
public static boolean excel2PDF(String inputFile, String pdfFile) {
ActiveXComponent app = null;
Dispatch excel = null;
boolean result = true;
try {
app = new ActiveXComponent("Excel.Application");
app.setProperty("Visible", false);
Dispatch excels = app.getProperty("Workbooks").toDispatch();
excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch();
Dispatch.call(excel, "ExportAsFixedFormat", xlTypePDF, pdfFile);
System.out.println("打开文档..." + inputFile);
System.out.println("转换文档到 PDF..." + pdfFile);
result = true;
} catch (Exception e) {
result = false;
} finally {
if (excel != null) {
Dispatch.call(excel, "Close");
}
if (app != null) {
app.invoke("Quit");
}
}
return result;
}
// 转换ppt文档
public static boolean ppt2PDF(String srcFilePath, String pdfFilePath) {
ActiveXComponent app = null;
Dispatch ppt = null;
boolean result = true;
try {
ComThread.InitSTA();
app = new ActiveXComponent("PowerPoint.Application");
Dispatch ppts = app.getProperty("Presentations").toDispatch();
// 因POWER.EXE的发布规则为同步,所以设置为同步发布
ppt = Dispatch.call(ppts, "Open", srcFilePath, true, // ReadOnly
true, // Untitled指定文件是否有标题
false// WithWindow指定文件是否可见
).toDispatch();
Dispatch.call(ppt, "SaveAs", pdfFilePath, 32); // ppSaveAsPDF为特定值32
System.out.println("转换文档到 PDF..." + pdfFilePath);
result = true; // set flag true;
} catch (ComFailException e) {
result = false;
} catch (Exception e) {
result = false;
} finally {
if (ppt != null) {
Dispatch.call(ppt, "Close");
}
if (app != null) {
app.invoke("Quit");
}
ComThread.Release();
}
return result;
}
// 截取文件后缀方法
public static String getFileSufix(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(splitIndex + 1);
}
/**
* @param inputFile 你的PDF文件地址
* @param outputFile 添加水印后生成PDF存放的地址
* @param waterMarkName 你的水印
* @return
*/
public static boolean waterMark(String inputFile, String outputFile, String waterMarkName) {
try {
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
// 这里的字体设置比较关键,这个设置是支持中文的写法
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
int total = reader.getNumberOfPages() + 1;
PdfContentByte under;
Rectangle pageRect = null;
for (int i = 1; i < total; i++) {
pageRect = stamper.getReader().getPageSizeWithRotation(i);
// 计算水印X,Y坐标
float x = pageRect.getWidth() / 10;
float y = pageRect.getHeight() / 10 - 10;
// 获得PDF最顶层
under = stamper.getOverContent(i);
under.saveState();
// set Transparency
PdfGState gs = new PdfGState();
// 设置透明度为0.2
gs.setFillOpacity(1.f);
under.setGState(gs);
under.restoreState();
under.beginText();
under.setFontAndSize(base, 60);
under.setColorFill(BaseColor.ORANGE);
// 水印文字成45度角倾斜
under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x, y, 55);
// 添加水印文字
under.endText();
under.setLineWidth(1f);
under.stroke();
}
stamper.close();
reader.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
配置文件
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jacob</groupId>
<artifactId>JacobDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>JacobDemo</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- SpringBoot 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- SpringBoot 拦截器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- SpringBoot Cache缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- SpringBoot 监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- SpringBoot Web容器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- pdf -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.19</version>
<scope>system</scope>
<systemPath>C:/Users/Administrator/.m2/jacob-1.20/jacob.jar</systemPath>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
图: