骑缝章常见于一些重要的合同或标书中,它具有防止他人增减文件页数的作用,能保证文件的完整性和有效性。本文将介绍如何借助Free Spire.PDF for Java 在Java应用程序中添加骑缝章到PDF格式的合同文件中。
产品导入
方法一:下载Free Spire.PDF for Java包并解压缩,然后将lib文件夹下的Spire.Pdf.jar包作为依赖项导入到Java应用程序中
方法二:直接通过Maven仓库安装JAR包,配置pom.xml文件的代码如下:
<repositories> <repository> <id>com.e-iceblue</id> <url>http://repo.e-iceblue.cn/repository/maven-public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf.free</artifactId> <version>3.9.0</version> </dependency> </dependencies>
添加骑缝章:
import com.spire.pdf.*; import com.spire.pdf.graphics.*; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.io.*; public class addSeamSeals { public static void main(String[] args) throws IOException { //加载示例文档 PdfDocument doc = new PdfDocument(); doc.loadFromFile("采购合同.pdf"); PdfUnitConvertor convert = new PdfUnitConvertor(); PdfPageBase pageBase = null; //获取分割后的印章图片 BufferedImage[] images = GetImage(doc.getPages().getCount()); float x = 0; float y = 0; //将图片画到PDF页面上的指定位置 for (int i = 0; i < doc.getPages().getCount(); i++) { BufferedImage image= images[ i ]; pageBase = doc.getPages().get(i); x = (float)(pageBase.getSize().getWidth()) - convert.convertUnits(image.getWidth(), PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point); y = (float) pageBase.getSize().getHeight()/ 2; pageBase.getCanvas().drawImage(PdfImage.fromImage(image), new Point2D.Float(x, y)); } //保存PDF doc.saveToFile("Result.pdf"); } //定义GetImage方法,根据PDF页数分割印章图片 static BufferedImage[] GetImage(int num) throws IOException { String originalImg = "C:\Users\Administrator\Desktop\z.png"; BufferedImage image = ImageIO.read(new File(originalImg)); int rows = 1; int cols = num; int chunks = rows * cols; int chunkWidth = image.getWidth() / cols; int chunkHeight = image.getHeight() / rows; int count = 0; BufferedImage[] imgs = new BufferedImage[ chunks ]; for (int x = 0; x < rows; x++) { for (int y = 0; y < cols; y++) { imgs[ count ] = new BufferedImage(chunkWidth, chunkHeight, image.getType()); Graphics2D gr = imgs[ count++ ].createGraphics(); gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x, chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, Color.WHITE,null); gr.dispose(); } } return imgs; } }
代码运行结果: