本文将介绍如何使用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.point, pdfgraphicsunit.pixel) 40;
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;
}
}
骑缝章效果图: