java使用poi操作word实现电子签章

您所在的位置:网站首页 word盖电子公章 java使用poi操作word实现电子签章

java使用poi操作word实现电子签章

2023-07-06 19:09| 来源: 网络整理| 查看: 265

这个电子签章其实并不算真正意义上的电子签章,有一些取巧的成分在。在代码之前我先简单讲一下这个操作的原理,其实就是在你的word模板上事先传上一张图片,将样式、大小都设置好,然后在代码中将图片文件进行替换。注:替换的只是图片的内容,样式、大小还是依照模板中原来的设置。

上代码! 依赖

org.apache.poi poi 4.1.0 org.apache.poi poi-ooxml 4.1.0 org.apache.poi poi-ooxml-schemas 4.1.0 InputStream is = this.getClass().getResourceAsStream("/demo.docx"); XWPFDocument document = new XWPFDocument(is); try { URL url = new URL("图片地址");//线上地址,本地地址也可以,我这里就不列举了,不难 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(3*1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 //这里的rId4可不是固定的,这个其实就是图片在word文件中的标识,下方会给出获取的方法 document.getPackagePart().removeRelationship("rId4"); //将图片插入word String ind = document.addPictureData(conn.getInputStream(),XWPFDocument.PICTURE_TYPE_PNG); //替换图片 document.getPackagePart().addRelationship(document.getPackagePart().getRelationship(ind).getTargetURI(), TargetMode.INTERNAL,XWPFRelation.IMAGES.getRelation(), "rId4"); } catch (Exception e) { System.out.println("报错了"); e.printStackTrace(); } //导出到文件 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); document.write((OutputStream) byteArrayOutputStream); String filePath = "D:/uploads/demo/"; String fileName = "demo"; File file = new File(filePath + fileName + ".docx"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(filePath + fileName + ".docx"); outputStream.write(byteArrayOutputStream.toByteArray()); outputStream.flush(); outputStream.close();

上文中的rId4的获取方法 首先准备一个word模板,复制一份出来,在副本word中插入一张图片,设置好需要的样式,然后将两个word的后缀改为zip,打开zip文件,在word文件夹下打开document.xml文件,对比两份xml文件,找到副本中多出来的部分,如下图 在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3