Java实现Excel和word转pdf加水印,复制及可用
Java实现Excel和word转pdf加水印,复制及可用
- 时隔大半年,之前朋友,今天突然找我说,他们有个需求要做这东西。想起来之前自己照着官方文档写,也走了不少坑。今天就索性写个,也为了方便以后使用。
jar包网盘链接地址:链接:https://pan.baidu.com/s/1YeOpA5IMrrw-3p_aMzCIcQ
提取码:7lsw
以下代码可直接粘贴使用,本地已实测。
import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.words.FontSettings;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.swing.*;
import java.awt.*;
import java.io.*;public class Hello {Logger logger = LoggerFactory.getLogger(Hello. class);//1:读取文件public void getFileStream(){try {//xls,xls类型File file = new File("G:\\TestFileStorageLocation\\xls\\suffixXlsTest.xls");//doc,docx类型//File file = new File("G:\\TestFileStorageLocation\\doc\\suffixDocTest.doc");InputStream inputStream = new FileInputStream(file);//根据文件后缀进行转换pdfString suffixName = file.getName().substring(file.getName().lastIndexOf(".")+1,file.getName().length());//下载水印及源文件selectPdf(suffixName,inputStream);} catch (Exception e) {e.printStackTrace();logger.error(">>>>>>>>异常原因:[{}]", e);}}/*** 2:根据后缀名,生成pdf* @param suffixFileName 文件后缀名*/public void selectPdf(String suffixFileName , InputStream inputStream) throws Exception {switch (suffixFileName) {case "xls":case "xlsx":excelPdf(inputStream);break;case "doc":case "docx":docPdf(inputStream);break;default:break;}}/*** (转pdf之前验证)获取aspose密匙(破解)* @return*/private boolean getLicense() {boolean result = false;try {String s = "<License>\n" +" <Data>\n" +" <Products>\n" +" <Product>Aspose.Total for Java</Product>\n" +" <Product>Aspose.Words for Java</Product>\n" +" </Products>\n" +" <EditionType>Enterprise</EditionType>\n" +" <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +" <LicenseExpiry>20991231</LicenseExpiry>\n" +" <SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\n" +" </Data>\n" +" <Signature>2sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +"</License>\n";ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());//InputStream is = getClass().getClassLoader().getResourceAsStream("license.xml");// license.xml应放在..\WebRoot\WEB-INF\classes路径下//InputStream is = new FileInputStream("D:\\xml\\license.xml");License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** @param inputStream doc流*/public void docPdf(InputStream inputStream) throws Exception {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {//pdf存放路径String pdfSavePath = "G:\\TestFileStorageLocation\\doc\\test.pdf";//添加水印之后的pdf存放路径FileOutputStream outputStream = new FileOutputStream(new File("G:\\waterMark\\doc\\test.pdf"));FileOutputStream os = new FileOutputStream(pdfSavePath);com.aspose.words.Document doc = null;//指定文件转码FontSettings.setDefaultFontName("方正楷体");doc = new com.aspose.words.Document(inputStream);doc.getRange().replace("Evaluation Only.Created with Aspose.Words.Copyright 2003-2014 Aspose Pty Ltd.", "", false, false);//Address是将要被转化的word文档doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换//给pdf加水印pdfAddWatermark(pdfSavePath,outputStream);long now = System.currentTimeMillis();os.close();os = null;doc = null;} catch (Exception e) {throw new Exception(">>>>>>>>>>生成pdf异常! 失败原因:[{}]", e);}}/*** @param inputStream excel流*/public void excelPdf(InputStream inputStream) throws Exception {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {//pdf存放路径String pdfSavePath = "G:\\TestFileStorageLocation\\xls\\test.pdf";//添加水印之后的pdf存放路径String waterMarkPdfPath="G:\\waterMark\\xls\\xlsSuffix.pdf";FileOutputStream outputStream = new FileOutputStream(new File(waterMarkPdfPath));com.aspose.cells.Workbook wb = null;wb = new com.aspose.cells.Workbook(inputStream);//生成pdf存放路径FileOutputStream fileOS = new FileOutputStream(new File(pdfSavePath));PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();//避免出现折行pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);wb.save(fileOS, pdfSaveOptions);fileOS.close();fileOS = null;logger.info(">>>>>>>>>>文件生成pdf成功!pdf存放路径:[{}]", pdfSavePath);//给pdf加水印pdfAddWatermark(pdfSavePath,outputStream);wb = null;} catch (Exception e) {throw new Exception(">>>>>>>>>>生成pdf异常! 失败原因:[{}]", e);}}/*** 给pdf加水印--最后一步加水印*/private void pdfAddWatermark(String filePath,OutputStream outputStream) throws Exception {//待加水印的文件PdfReader pdfReader = new PdfReader(filePath);PdfStamper pdfStamper = null;//存放加水印之后的路径pdfStamper = new PdfStamper(pdfReader, outputStream);int total = pdfReader.getNumberOfPages() + 1;PdfContentByte contentByte = null;int i = 1;PdfGState gs = new PdfGState();//设置水印不透明度gs.setFillOpacity(0.5f);com.itextpdf.text.Rectangle pageSize = null;int interval = 40;try {//动态添加水印文字String text = "北斗七星高||哥舒夜带刀||横批";String[] waterText = text.split("\\|\\|");logger.info(">>>>>>>>生成水印内容:[{}]",waterText);//获取字体高度int textH = 0;JLabel label = new JLabel();//label.setText(waterText[0]);FontMetrics metrics = label.getFontMetrics(label.getFont());textH = metrics.getHeight();//逐页添加水印while (i < total) {//水印置于最上层(无论多少分层)contentByte = pdfStamper.getOverContent(i);pageSize = pdfReader.getPageSizeWithRotation(i);float pageHight = pageSize.getHeight();float pageWidth = pageSize.getWidth();contentByte.beginText();//设置字体及字号contentByte.setFontAndSize(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED), 20);contentByte.setGState(gs);//添加多行水印for (int i1 = 0; i1 < waterText.length; i1++) {interval = i1 * textH;//调整水印文字的水平位置及角度contentByte.showTextAligned(Element.ALIGN_CENTER, waterText[i1], pageWidth / 2 - interval, pageHight / 2 + interval, 42);}contentByte.setColorFill(BaseColor.GRAY);contentByte.endText();i++;}contentByte.stroke();logger.info(">>>>>>>>>> pdf文件添加水印成功!");} catch (Exception e) {throw new Exception(">>>>>>>>>>pdf文件添加水印失败 失败原因:[{}]", e);} finally {contentByte = null;gs = null;pdfStamper.close();pdfStamper = null;}pdfReader.close();}public static void main(String[] args) {Hello hello = new Hello();hello.getFileStream();
}
}
这里说明以下Excel是破解版的可直接使用。word未找到破解版,转出的pdf首行会有水印,具体看下图。
- Excel效果:
2,Word效果图:
*特别注意:在linux环境下-----
tomcat里面的catalina文件要添加以下内容(该文件具体哪个问题,百度下–时间久远忘了)
所有-Djava.io.tmpdir=“$CATALINA_TMPDIR” \下面增加 -Djava.awt.headless=true*
我做的时候不加是报错的。
如果帮助到你了,给个赞。谢谢。有问题留言或私信。
Java实现Excel和word转pdf加水印,复制及可用相关推荐
- java操作Excel、word和pdf
2019独角兽企业重金招聘Python工程师标准>>> 有些时候我们需要读写excel和word,或者将文字转为pdf那我们应该怎么做呢? 如果需要读写excel需要添加包: < ...
- 给现有的word和pdf加水印
iTextSharp简单生成pdf和操作pdf添加水印 给word加水印,利用的是aspose.words
- (Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出
目录 1.引入jar包 2.pdf处理工具类 3.poi模板导出工具类 4.测试类 5.模板 6.最终效果 1.引入jar包 2.pdf处理工具类 import com.aspose.cells.Pd ...
- java使用2种方法操作liberoffice把word转pdf,pdf加水印,java远程调用Linux执行命令
文章目录 libreoffice下载地址 安装 (第一种) java调用 (第二种 推荐) java调用Linux命令转pdf java远程连接Linux执行命令(少数情况) linux安装windo ...
- Springboot使用itext及documents4j操作pdf(word转pdf、pdf加水印(文字或图片,可指定位置)、pdf加密(打开密码,编辑密码))
pom.xml引入 <!-- pdf文档生成 --><dependency><groupId>com.documents4j</groupId>< ...
- java pdf水印排布问题_java 实现 PDF 加水印功能
使用java代码实现给PDF加水印的功能 首先导入所需要的依赖 com.itextpdf itextpdf 5.5.11 com.itextpdf itext-asian 5.2.0 java 代码实 ...
- LayUi集成下载Excel、word、PDF、CSV扩展
LayUi集成下载Excel.word.PDF.CSV扩展 Excel.CSV Word PDF 根据项目需求,主要用的layui这个前段框架,现在需要支持将页面下载为四种格式的文件. Excel.C ...
- Java使用aopse实现word转换pdf
Java使用aopse实现word转换pdf 需要引用aspose包,引入操作我写了一个博客,地址如下 https://blog.csdn.net/weixin_46713508/article/de ...
- java 使用jacob实现word转pdf
java 使用jacob实现word转pdf(IDEA Maven项目) 步骤: 一. 插件与jar包下载 SaveAsPDFandXPS 下载地址: http://www.microsoft.com ...
最新文章
- HDU1874(Dijstra算法)
- 团队项目第二阶段冲刺站立会议06
- pyqt5 实现右键自定义_《快速掌握PyQt5》第十七章 事件处理
- 技术人必看:15张图对比高效与瞎忙的区别!
- 读取properties资源文件中的参数
- PyTorch学习笔记(五):模型定义、修改、保存
- linux系统下载r软件安装,Linux安装R语言包
- laravel下载文件
- JavaScript发送短信案例
- Qt如何调用xlsl的方法!
- PTA 新浪微博热门话题 详细题解 附额外样例
- PHP date() 和 strtotime() 使用详解
- 用python全方位解析2019新冠疫情词云图
- php注册阻止相同用户名,php如何禁止重复注册用户名
- 【GlobalMapper精品教程】004:生成标准经纬网图幅(1:100万)案例教程
- 趣味题系列:帽子戏法;警察抓逃犯问题 ;史密斯夫妇握手问题
- zxing换行_微博换行功能最新资讯
- 刨析 SpringBoot 自动装配原理,其实很简单
- datawhale 10月学习——树模型与集成学习:两种并行集成的树模型
- 智慧消防物联网(智慧消防远程监控管理系统)