需求:

每天都执行,把一个文件夹中的(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, // ReadOnlytrue, // Untitled指定文件是否有标题false// WithWindow指定文件是否可见).toDispatch();Dispatch.call(ppt, "SaveAs", pdfFilePath, 32); // ppSaveAsPDF为特定值32System.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 TransparencyPdfGState gs = new PdfGState();// 设置透明度为0.2gs.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>

图:

windows操作系统运用jacob转换文件,并添加水印相关推荐

  1. 将windows下编辑好的文件(GBK)转换成Linux下的格式(UTF8)

    背景:一般我们在windows上编辑好的文件默认编码是GBK,而且换行符是^M,为了将这些文件用在linux上,我们一般会将它们转换成Linux下的文件格式,即去掉^M,且将文件格式转换成UTF8. ...

  2. 使用 windows命令和iconv.exe批量转换文件编码

    使用 windows命令和iconv.exe批量转换文件编码    iconv是知名的开源跨平台编码转换库,iconv.exe是iconv库在windows下的命令行工具,iconv.exe的一般用法 ...

  3. 使用windows命令和iconv.exe批量转换文件编码

    使用windows命令和iconv.exe批量转换文件编码 iconv是知名的开源跨平台编码转换库,iconv.exe是iconv库在windows下的命令行工具,iconv.exe的一般用法:ico ...

  4. 如何通过备份 Windows 7 “ 两个激活文件”实现重装操作系统后的自行激活?

    用 "MAK密钥"联网激活Windows 7企业版或专业版,是时过境迁的历史机遇(至少目前如此):用"神Key"联网激活Windows 7旗舰版,靠的是&quo ...

  5. 在计算机窗口中什么中的文件不能被删除,在Windows操作系统中,“回收站”可以恢复(1)上使用键删除的文件或文件夹。在“我的电脑”窗口中,...

    55题库为您解答: 正确答案:B 解析:本题考查Windows操作系统应用的基本知识.在Windows操作系统中,"回收站"可以恢复硬盘上使用Del>键删除的文件或文件夹.& ...

  6. Windows操作系统 分页文件 | 九七的Windows开发

    Windows操作系统 分页文件 环境 Windows7 64位 一.定义介绍   分页一词由Paging翻译而来.数据分成固定大小的区块叫做"页".分页的第一个意思指的是磁盘和内 ...

  7. 操作系统ppt_Python处理PPT文件的实用姿势

    好看的皮囊千篇一律,有趣的灵魂两百多斤. 和Word.Excel承载数据的能力相比,PPT的应用重点在于表演. 比如一场发布会.一场演说.一次产品展示.一次客户沟通-- 正常情况下,用PowerPoi ...

  8. jacob jar包_java 文档在线预览 Windows版本(jacob)

    文档在线预览有两种实现方式: 1. windows server下用 jacob2. linux server下 用openoffice 1 2 话不多说,看吧.这里是使用jacob实现的 准备一下j ...

  9. 如何在Windows和Mac上将PNG文件转换为PDF?

    文章来源:https://www.reneelab.com.cn/convert-png-to-pdf.html 目录 一.什么是PNG与PDF 二.如何在Windows上将PNG转换为PDF 1.都 ...

最新文章

  1. java一维数组初始化_Java一维数组,初始化一维数组详解
  2. python语言入门自学-如何系统地自学 Python?
  3. 子查询in和表连接效率
  4. tpp letter
  5. 外部中断0——51程序
  6. matlab 误差椭圆,求3倍标准差误差椭圆分析的程序
  7. 计算机相关专业的自我评价,计算机相关专业的学生自我评价
  8. 如何用vbs编写一个游戏_如何编写一个 SkyWalking 插件
  9. ipad文件管理怎么添加服务器,ipad怎样建文件夹
  10. 日志服务器文档,日志服务器的搭建.docx
  11. 武汉科技大学计算机学院研究生复试,2019年武汉科技大学硕士研究生复试及录取工作方案...
  12. Day-26 多线程和多进程
  13. props传值强校验validator
  14. IDEA设置按键提示 Ctrl+p
  15. 【7集iCore3基础视频】7-5 iTool2驱动安装
  16. 《优柔有情人》读后感6000字
  17. zblog php建站教程_Z-BlogPHP主题制作教程
  18. po、bo、do、dto、vo相关图形
  19. Nginx如何跳转到非443端口的https
  20. Scrapy简明教程(一)

热门文章

  1. kafka(1) 初识
  2. WebStorm/IDEA 激活证书服务器
  3. DDL(数据定义语言)讲解
  4. AES 轮密钥(子密钥如何生成).md
  5. 唤醒手腕 - 爆肝 3 天整理出来关于 Opencv 计算机图像处理详细教程(更新中)
  6. c语言数码管中断器,数码管动态显示 定时器中断 数码管动态显示不正常
  7. vue input file 上传图片
  8. 一些基于新闻表示和用户表示的新闻推荐模型总结:NPA/ NAML/ LSTUR/ NRMS
  9. manjaro docker安装使用
  10. 【详细七层】OSI 网络模型,七层网络模型