最近要实现一个使用手写板对PDF文档进行手写签名的功能,下面记录一下关键过程。
实现的思路如下:1、在画板中显示PDF文档的内容2、用户使用签名版对PDF文档进行签名3、保存签名后的画板内容到新的PDF中
其中使用pdfbox把PDF文档转成图片,签名后又把签名后的图片转回PDF保存。
pdfbox(http://pdfbox.apache.org/)是一个处理PDF文档的JAVA库。
import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;import org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg;import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;import javax.imageio.ImageIO;import javax.swing.*;import java.awt.*;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.geom.AffineTransform;import java.awt.image.AffineTransformOp;import java.awt.image.BufferedImage;import java.awt.image.ColorModel;import java.awt.image.PixelGrabber;import java.io.File;import java.io.IOException;import java.util.logging.Level;import java.util.logging.Logger;class TestDraw extends Canvas {
Image image;
boolean init = true;
public static final int WIDTH = 1024;
public static final int HEIGHT = 1024;
public Image screen = createImage(WIDTH, HEIGHT, true);// 双缓冲
private Graphics graphics = screen.getGraphics();
public Image resultImage;
int x1 = -1;
int y1 = -1;
int x2 = -1;
int y2 = -1;
public TestDraw() {
this.setBackground(Color.white);
this.addMouseListener(new MyMouseListener(this));
this.addMouseMotionListener(new MyMouseMotionListener(this));
image = pdfToImg("pdf/tests.pdf");
// 设定初始构造时面板大小
setPreferredSize(new Dimension(WIDTH, HEIGHT));
// 初始导入一张图片
ImageIcon icon = new ImageIcon(image);
resultImage = icon.getImage();
}
public void paint(Graphics g) {
update(g);
}
@Override