失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > java通过spire.doc实现word增加水印功能

java通过spire.doc实现word增加水印功能

时间:2019-12-08 18:12:44

相关推荐

java通过spire.doc实现word增加水印功能

目的:

动态给word文档添加水印,生成相应格式。基于Spire为免费版,以及Spire.Doc的运行无需安装Microsoft Word。而且,它可以将Microsoft Word文档创建功能集成到开发者的任何.NET应用程序。

涉及jar包:

spire-office-free.jar

直接上代码:

// 以模板形式打开word文档String filename = “word水印模板.docx”;File createTempFile = createTempFile(filename);//创建临时路径String wordPath = createTempFile.getPath();String wordPath = createTempFile.getPath();String fileName = createTempFile.getName();String oldFilePath = wordPath.substring(0, wordPath.lastIndexOf(fileName));String name = fileName .substring(0,fileName.lastIndexOf("."));String savePath = oldFilePath + name + suffix_name + ".docx";File toFile = new File(savePath);if (toFile.exists()) {toFile.delete();}Document document = new Document(wordPath); // 源文件路径Section section1 = document.getSections().get(0);//设置文档只读密码if(PubEnumsConstant.IS_READ_0.equals(is_read)){ document.protect(ProtectionType.Allow_Only_Reading,RandomStringUtils.randomAlphanumeric(10));}// 添加艺术字并设置大小ShapeObject shape = new ShapeObject(document, ShapeType.Text_Plain_Text);// 该字体为中空字体,for (int n = 0; n < document.getSections().getCount(); n++) {section = document.getSections().get(n);// 获取section的页眉HeaderFooter header = section.getHeadersFooters().getHeader();Paragraph paragraph;if (header.getParagraphs().getCount() > 0) {// 如果页眉有段落,取它第一个段落paragraph = header.getParagraphs().get(0);} else {// 否则新增加一个段落到页眉paragraph = header.addParagraph();}for (int i = 0; i < 4; i++) {// 列for (int j = 0; j < 5; j++) {// 行// 复制艺术字并设置多行多列位置shape = (ShapeObject) shape.deepClone();shape.setWidth(160);// 字体宽度shape.setHeight(10;// 字体高度shape.setRotation(330);// 旋转shape.getWordArt().setFontFamily("宋体");// 水印字体shape.getWordArt().setText(“中银金融租赁有限公司”);// 水印shape.setFillColor(new Color(128, 128, 128));// 中心填充颜色shape.setStrokeColor(new Color(204, 204, 204));// 边缘填充颜色shape.setStrokeWeight(0.5);// 字体宽度(<=1)shape.setLineStyle(ShapeLineStyle.Single);// 格式//设置循环次数,几行几列shape.setVerticalPosition(50 + 150 * i);//50代表行的起始位置shape.setHorizontalPosition(20 + 160 * j);//20代表列的起始位置paragraph.getChildObjects().add(shape);}}}// 另存为docx文件document.saveToFile(savePath, FileFormat.Docx);//savePath不可与原文件为同一个路径。} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();};/*** Description: 创建要生成的文件<br>* * @param filename* @return* @throws IOException* @author: jichen<br>* @Date:-6-22*/private File createTempFile(String filename) throws IOException {File file = new File(TEM_DIR + filename);FileOutputStream out = null;try {out = new FileOutputStream(file);this.document.write(out);} finally {IOUtils.closeQuietly(out);}return file;}

注:文档源路径与加水印文档不可为同一路径,否则不生效。可通过设置各自属性实现可配置话加水印功能。

如果觉得《java通过spire.doc实现word增加水印功能》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。