返回顶部
首页 > 资讯 > 后端开发 > JAVA >(Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出
  • 882
分享到

(Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出

javapdfword 2023-10-18 20:10:49 882人浏览 安东尼
摘要

目录 1、引入jar包 2、pdf处理工具类 3、poi模板导出工具类 4、测试类 5、模板 6、最终效果  1、引入jar包   2、pdf处理工具类 import com.aspose.cells.PdfSaveOptions

目录

1、引入jar包

2、pdf处理工具类

3、poi模板导出工具类

4、测试类

5、模板

6、最终效果 


1、引入jar

 

2、pdf处理工具

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();            }        }       }}

 3、poi模板导出工具类

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> tableList, String[] fields, int tableindex, int headerIndex){        if(null == tableList || null == fields){            return;        }        //获取表格对象集合        List tables = document.getTables();        XWPFTableRow copyRow = tables.get(tableindex).getRow(headerIndex);        List cellList = copyRow.getTableCells();        if (null == cellList) {            return;        }        //遍历要添加的数据的list        for (int i = 0; i < tableList.size(); i++) {            //插入一行            XWPFTableRow targetRow = tables.get(tableindex).insertNewTableRow(headerIndex + i);            //复制行属性            targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());            Map map = tableList.get(i);            // 字段匹配后,插入单元格并赋值            for (String field : fields) {                int idx = 0;                for(Map.Entry entry: map.entrySet()){                    if(!field.equals(entry.geTKEy())) continue;                    XWPFTableCell sourceCell = cellList.get(idx);                    //插入一个单元格                    XWPFTableCell targetCell = targetRow.addNewTableCell();                    //复制列属性                    targetCell.getCTTc().settcpr(sourceCell.getCTTc().getTcPr());    //targetCell.setText(entry.getValue());                                     //获取 XWPFTableCell 的CTTc                    CTTc ctTc = targetCell.getCTTc();                    //获取 CTP                     CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0);            //getParagraph(ctP) 获取 XWPFParagraph             XWPFParagraph par = targetCell.getParagraph(ctP);                    //XWPFRun   设置格式                    XWPFRun run = par.createRun();            String textValue = entry.getValue();                    // 复选框填充值                    if (field.toLowerCase().indexOf("checkbox_") != -1) {                    run.setFontFamily("SimSun");                    String[] tArr = textValue.split("@@@");                    for (int j = 0; j < tArr.length; j++) {                    if (j == 0) {                    run.setText(tArr[j], 0);                    } else {                    run.setText(tArr[j]);                    }                    if (j != tArr.length-1) {                    run.addBreak();//换行                    }                    }                    } else {                    run.setText(textValue, 0);                    }                    idx ++;                };            }        }        if (tableList.size() > 0) {        List rows = tables.get(tableindex).getRows();            int rowLength = rows.size();            deleteTable(tables.get(tableindex), tableList.size() + headerIndex, rowLength);        }    }            public static void deleteTable(XWPFTable table, int fromIndex, int toIndex){        for (int i = fromIndex; i < toIndex; i++) {            table.removeRow(fromIndex);        }    }         public static void changeTableText(XWPFDocument document, Map textMap) {        //获取表格对象集合        List tables = document.getTables();        for (int i = 0; i < tables.size(); i++) {            //只处理行数大于等于2的表格            XWPFTable table = tables.get(i);            if (table.getRows().size() > 1) {                //判断表格是需要替换还是需要插入,判断逻辑有$为替换                if (checkText(table.getText())) {                    List rows = table.getRows();                    //遍历表格,并替换模板                    eachTable(rows, textMap);                }            }        }    }         public static void eachTable(List rows, Map textMap) {        for (XWPFTableRow row : rows) {            List cells = row.getTableCells();            for (XWPFTableCell cell : cells) {                //判断单元格是否需要替换                if (checkText(cell.getText())) {                    List paragraphs = cell.getParagraphs();                    for (XWPFParagraph paragraph : paragraphs) {                        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 String changeValue(String value, Map textMap) {        Set> textSets = textMap.entrySet();        for (Map.Entry textSet : textSets) {            //匹配模板与替换值 格式${key}            String key = "${" + textSet.getKey() + "}";            if (value.indexOf(key) != -1) {                value = textSet.getValue();            }        }        //模板未匹配到区域替换为空        if (checkText(value)) {            value = "";        }        return value;    }         public static boolean checkText(String text) {        boolean check = false;        if (text.indexOf("$") != -1) {            check = true;        }        return check;    }}

 4、测试

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> tableDatalist = new ArrayList<>();                List> familyList = new ArrayList<>();        Map m = new HashMap();        m.put("name","露娜");        m.put("sex","女");        m.put("position","野友");        m.put("no","6660");        familyList.add(m);        m = new HashMap();        m.put("name","鲁班");        m.put("sex","男");        m.put("position","射友");        m.put("no","2220");        familyList.add(m);        m = new HashMap();        m.put("name","程咬金");        m.put("sex","男");        m.put("position","肉友");        m.put("no","9990");        familyList.add(m);        Map tableData = new HashMap();        tableData.put("list", familyList);        tableData.put("fields", new String[]{"name","sex","position","no"});        tableData.put("tableIndex", 1);        tableData.put("headerIndex", 1);        tableDatalist.add(tableData);                familyList = new ArrayList<>();        m = new HashMap();        m.put("name","太乙真人");        m.put("sex","男");        m.put("position","辅友");        m.put("no","1110");        m.put("checkbox_fcxz", "\u25A1商品房" + "@@@" + "\u2611福利房" + "@@@" + "\u25A1经济适用房" + "@@@"         + "\u2611限价房" + "@@@" + "\u2611自建房" + "@@@" + "\u25A1车库、车位、储藏间" + "@@@" + "\u25A1其他");        familyList.add(m);        m = new HashMap();        m.put("name","貂蝉");        m.put("sex","女");        m.put("position","法友");        m.put("no","8880");        m.put("checkbox_fcxz", "\u25A1商品房" + "@@@" + "\u2611福利房" + "@@@" + "\u2611经济适用房" + "@@@" + "\u2611限价房" + "@@@" + "\u2611自建房" + "@@@" + "\u2611车库、车位、储藏间" + "@@@" + "\u25A1其他");        familyList.add(m);        tableData = new HashMap();        tableData.put("list", familyList);        tableData.put("fields", new String[]{"name","sex","position","checkbox_fcxz"});        tableData.put("tableIndex", 2);        tableData.put("headerIndex", 1);        tableDatalist.add(tableData);        exportWord(paragraphMap,tableMap,tableDatalist);        // 结束时间        long etime = System.currentTimeMillis();        // 计算执行时间        System.out.printf("执行时长:%d 毫秒.", (etime - stime));    }    @SuppressWarnings("unchecked")private static void exportWord(Map paragraphMap,Map tableMap,List> tableDatalist){        String classpath = Mytest.class.getClass().getResource("/").getPath();                String templatePath = classpath.replace("WEB-INF/classes", "导入模板");String t_filepath = classpath.replace("WEB-INF/classes", "import");String filename = "person";File f = new File(templatePath + filename + ".docx");File f1 = new File(t_filepath + filename + ".docx");File f2 = new File(t_filepath + filename + ".pdf");File f3 = new File(t_filepath + filename + "_水印.pdf");                XWPFDocument document = null;        try {            //解析docx模板并获取document对象            document = new XWPFDocument(new FileInputStream(new File(f.getPath())));            ExportWordUtil.changeParagraphText(document, paragraphMap);            ExportWordUtil.changeTableText(document, tableMap);            for (Map map : tableDatalist) {            ExportWordUtil.copyHeaderInsertText(document, (List>) map.get("list"), (String[]) map.get("fields"),                        (Integer) map.get("tableIndex"), (Integer) map.get("headerIndex"));            }            FileOutputStream out = new FileOutputStream(new File(f1.getPath()));            document.write(out);            out.close();        } catch (IOException e) {            e.printStackTrace();        } finally {            if (document != null) {                try {                    document.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }                String suffix = f1.getPath().substring(f1.getPath().lastIndexOf(".") + 1); // 后缀// aspose 转 pdfPdfUtil.transToPdf(f1.getPath(), f2.getPath(), suffix);// itextpdf给pdf加水印PdfUtil.addWaterMark(f2.getPath(), f3.getPath(), "测试水印", true);    }}

5、模板

6、最终效果 

来源地址: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

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作