Java 新增騎縫章到PDF 文件中
阿新 • • 發佈:2020-10-27
騎縫章常見於一些重要的合同或標書中,它具有防止他人增減檔案頁數的作用,能保證檔案的完整性和有效性。本文將介紹如何藉助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 { publicstatic 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; } }
程式碼執行結果: