本文将介绍如何使用Spire.PDF在Java应用程序中给PDF格式的合同文件添加骑缝章。
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("Contract.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 = "stamp.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;
}
}
骑缝章效果图: