目录 1、引入jar包 2、pdf处理工具类 3、poi模板导出工具类 4、测试类 5、模板 6、最终效果 1、引入jar包 2、pdf处理工具类 import com.aspose.cells.PdfSaveOptions
目录
import com.aspose.cells.PdfSaveOptions;import com.aspose.cells.Workbook;import com.aspose.Words.Document; //引入aspose-words-21.5.0-jdk17包import com.aspose.words.*;import com.itextpdf.text.*;import com.itextpdf.text.pdf.*;import javax.swing.JLabel;import java.awt.FontMetrics;import java.io.*;import java.lang.reflect.Field;import java.lang.reflect.Modifier;import java.util.Arrays;public class PdfUtil {//水印字体透明度 private static float opacity = 0.1f; //水印字体大小 private static int fontsize = 20; //水印倾斜角度(0-360) private static int angle = 30; //数值越大每页竖向水印越少 private static int heightDensity = 15; //数值越大每页横向水印越少 private static int widthDensity = 2; private static final String[] WORD = {"doc", "docx", "wps", "wpt", "txt"}; private static final String[] excel = {"xls", "xlsx", "et", "xlsm"}; private static final String[] PPT = {"ppt", "pptx"}; public static void transToPdf(String filePath, String pdfPath, String suffix) { if (Arrays.asList(WORD).contains(suffix)) { word2PDF(filePath, pdfPath); } else if (Arrays.asList(EXCEL).contains(suffix)) { excel2PDF(filePath, pdfPath); } else if (Arrays.asList(PPT).contains(suffix)) { // 暂不实现,需要引入aspose.slides包 } } private static void word2PDF(String inputFile, String pdfFile) {try {Class> aClass = Class.forName("com.aspose.words.zzZDQ"); Field zzYAC = aClass.getDeclaredField("zzYAC"); zzYAC.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(zzYAC, zzYAC.getModifiers() & ~Modifier.FINAL); zzYAC.set(null,new byte[]{76, 73, 67, 69, 78, 83, 69, 68});long old = System.currentTimeMillis();File file = new File(pdfFile); // 新建一个空白pdf文档FileOutputStream os = new FileOutputStream(file);Document doc = new Document(inputFile); // inputFile是将要被转化的word文档//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换doc.save(os, com.aspose.words.SaveFormat.PDF);os.close();System.out.println(">>>>>>>>>> word文件转换pdf成功!");long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时} catch (Exception e) {e.printStackTrace();}}private static boolean getLicense2() {boolean result = false;try {InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下com.aspose.cells.License aposeLic = new com.aspose.cells.License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}private static void excel2PDF(String excelPath, String pdfPath) {if (!getLicense2()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {Workbook wb = new Workbook(excelPath);// 原始excel路径File pdfFile = new File(pdfPath);// 输出路径PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); //把excel所有内容放在一张PDF 页面上; pdfSaveOptions.setOnePagePerSheet(false); //把excel所有表头放在一张pdf上 pdfSaveOptions.setAllColumnsInOnePagePerSheet(true); FileOutputStream fileOS = new FileOutputStream(pdfFile);wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);fileOS.close();System.out.println(">>>>>>>>>> excel文件转换pdf成功!");} catch (Exception e) {e.printStackTrace();}} public static boolean addWaterMark(String inputFile, String outputFile, String waterMarkName, boolean cover) { if (!cover) { File file = new File(outputFile); if (file.exists()) { return true; } } File file = new File(inputFile); if (!file.exists()) { return false; } PdfReader reader = null; PdfStamper stamper = null; try { reader = new PdfReader(inputFile); stamper = new PdfStamper(reader, new FileOutputStream(outputFile)); BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); Rectangle pageRect = null; PdfGState gs = new PdfGState(); //这里是透明度设置 gs.setFillOpacity(opacity); //这里是条纹不透明度 gs.setStrokeOpacity(0.2f); int total = reader.getNumberOfPages() + 1; System.out.println("Pdf页数:" + reader.getNumberOfPages()); JLabel label = new JLabel(); FontMetrics metrics; int textH = 0; int textW = 0; label.setText(waterMarkName); metrics = label.getFontMetrics(label.getFont()); //字符串的高, 只和字体有关 textH = metrics.getHeight(); //字符串的宽 textW = metrics.stringWidth(label.getText()); PdfContentByte under; //循环PDF,每页添加水印 for (int i = 1; i < total; i++) { pageRect = reader.getPageSizeWithRotation(i); //在内容上方添加水印 under = stamper.getOverContent(i); under.saveState(); under.setGState(gs); under.beginText(); //这里是水印字体大小 under.setFontAndSize(base, fontsize); for (int height = textH; height < pageRect.getHeight() * 2; height = height + textH * heightDensity) { for (int width = textW; width < pageRect.getWidth() * 1.5 + textW; width = width + textW * widthDensity) { // rotation:倾斜角度 under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, angle); } } //添加水印文字 under.endText(); } System.out.println("添加水印成功!"); return true; } catch (IOException e) { System.out.println("添加水印失败!错误信息为: " + e); return false; } catch (DocumentException e) { System.out.println("添加水印失败!错误信息为: " + e); return false; } finally { //关闭流 if (stamper != null) { try { stamper.close(); } catch (DocumentException e) { System.out.println("文件流关闭失败"); } catch (IOException e) { System.out.println("文件流关闭失败"); } } if (reader != null) { reader.close(); } } }}
import java.util.*;import org.apache.poi.xWPF.usermodel.*;import org.openxmlfORMats.schemas.wordprocessingml.x2006.main.CTP;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;public class ExportWordUtil {private ExportWordUtil() { } public static void changeParagraphText(XWPFDocument document, Map textMap) { //获取段落集合 List paragraphs = document.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) { //判断此段落是否需要进行替换 String text = paragraph.getText(); if (checkText(text)) { List runs = paragraph.getRuns(); for (XWPFRun run : runs) { //替换模板原来位置 String textValue = changeValue(run.toString(), textMap); if (run.toString().toLowerCase().indexOf("checkbox_") != -1) {// 复选框填充值 run.setFontFamily("SimSun"); String[] tArr = textValue.split("@@@"); for (int i = 0; i < tArr.length; i++) { if (i == 0) { run.setText(tArr[i], 0); } else { run.setText(tArr[i]); } if (i != tArr.length-1) { run.addBreak();//换行 } } } else { run.setText(textValue, 0); } } } } } public static void copyHeaderInsertText(XWPFDocument document, List
import org.apache.poi.xwpf.usermodel.XWPFDocument;import java.io.*;import java.util.*;public class Mytest { public static void main(String args[]){ // 开始时间 long stime = System.currentTimeMillis(); // 模拟点数据 Map paragraphMap = new HashMap<>(); Map tableMap = new HashMap<>(); paragraphMap.put("name", "赵云"); paragraphMap.put("date", "2020-03-25"); paragraphMap.put("checkbox_sf", "\u25A1是" + " " + "\u2611否"); tableMap.put("name", "赵云"); tableMap.put("sex", "男"); tableMap.put("birthday", "2020-01-01"); tableMap.put("checkbox_sf", "\u25A1是s" + " " + "\u2611否d" + "@@@" + "\u25A1是" + " " + "\u2611否"); List
来源地址:https://blog.csdn.net/qq_42034594/article/details/131126848
--结束END--
本文标题: (Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出
本文链接: https://lsjlt.com/news/431749.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0