如何用Java 给 Word 文档每一页添加不同图片水印

发布时间:2023-02-25 14:24:13

  在Word中设置水印时,可以将图片加载到水印效果中,但通常在添加水印效果时,所有页面都会设置为统一效果。如果您需要在每个页面或某个页面上设置不同的水印效果,您可以参考本文中的方法。接下来,以Java代码为例,详细介绍Word每页设置不同图片的水印效果。

  方法思路

  在将水印添加到Word的每一页之前,首先需要在Word文档的每一页文本的最后一个字符后面插入连续分段符,然后在每一页的眉毛段落中添加水印图片,并设置图片的坐标位置、对齐模式、衬里等。最后保存文档。

  Jar引入

  在程序中引入Freespire.docforJava中的Spire.doc.jar文件(该文件在lib文件夹下);如果需要通过Maven下载导入,

  pom.xml:

  com.e-iceblue。

  https://repo.e-iceblue.cn/repository/maven-public/

  e-iceblue。

  spire.doc.freee。

  5.1.0

  Java代码。

  添加图片水印时,可参考以下步骤:

  创建document对象,通过document.loadfromfile(stringfilename)加载Word文档。

  通过document.getsections.get(intindex)获得指定节。

  通过section.getheadersfoters().getheader()获取页眉,headerfoter.addparagraph()方法添加段落到页眉。

  通过paragraph.appendpicture(stringfilepath)方法将图片添加到段落中,Docpicture.setverticalposition(floatvalue)方法设置水印图片位置,Docpicture.sethorizontalalignmentalue)方法设置图片对齐。

  最后,通过document.savetofile(stringfilename,fileformatfileformat)保存文档。

  在不同的页面上设置不同的图片水印效果,只需获得页面对应的部分,然后参考上述方法添加即可。

  以下是完整的Java代码示例:

  importcom.spire.doc.*;

  importcom.spire.doc.documents.Paragraph;

  importcom.spire.doc.documents.Textwrappingstyle;

  importcom.spire.doc.fields.docpicture;

  /**

  *说明:word加水印。

  *作者:FHAdmin。

  *fromfhadmin.cn。

  */

  publiclasdiferma。

  publicsticvoidmain(string[]args){

  //加载Word测试文档。

  Documentdoc=newdocument();

  doc.loadFromFile(“test.docx”);

  //获取文档的第一节。

  Sectionsection1=doc.getsections().get(0);

  //定义水印图片的纵向坐标位置。

  floaty=(float)(section1.getpagesetup.getpagesize().getheight()/3);

  //添加图片水印1。

  Headerfooterheader1=section1.getheadersfooters().getheader();//获取页眉。

  header1.getparagraphs.clear();//删除原页眉格式的段落。

  Paragra图灵ara1=header1.adparagraph();//重新添加段落。

  DocPicturepic1=para1.appendPicture(“logo1.png”);//加载图片。

  pic1.setextwrappingstyle(textwrapingstyle.behind);//图片放在文字下方。

  pic1.setverticalposition(y);

  pic1.sethorizontalignment(shapehorizontalignment.center);//设置图片对齐模式。

  Sectionsection2=doc.getsections().get(1);

  Headerfooterheader2=section2.getheadersfooters().getheader();

  header2.getparagraphs.clear();

  Paragra图灵ara2=header2.adparagraph;

  DocPicturepic2=para2.appendPicture(“logo2.png”);

  pic2.setextwrappingstyle(textwrapingstyle.behind);

  pic2.setverticalposition(y);

  pic2.sethorizontalignment(shapehorizontalignment.center);

  //同样,在第三节设置页眉中的图片水印3。

  Sectionsection3=doc.getsections().get(2);

  Headerfooterheader3=section3.getheadersfooters().getheader();

  header3.getParagraphs().clear();

  Paragraph para3= header3.addParagraph();

  DocPicture pic3 = para3.appendPicture("logo3.png");

  pic3.setTextWrappingStyle(TextWrappingStyle.Behind);

  pic3.setVerticalPosition(y);

  pic3.setHorizontalAlignment(ShapeHorizontalAlignment.Center);

  //保存文档

  doc.saveToFile("DifferentImageWatermark.docx",FileFormat.Docx_2013);

  doc.dispose();
       }
}

上一篇 java WebSocket 服务端代码
下一篇 Java里List集合中的对象根据对象的某个属性值降序或者升序排序

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题