首选,要获取 PdfStamper 对象:
PdfStamper ps = new PdfStamper(reader, bos);
然后,要获取到需要创建签名域的矩形区域:
// 创建数组签名域
int x = 300, y = 400, width = 200, height = 200; // 坐标系远点位于页面左下角,左下角到右下角为 x 轴,左下角到左上角为 y 轴
Rectangle areaSignatureRect = new Rectangle(// 签名域区域,由两个对角点构成的矩形区域
x, // 点1 x坐标
y, // 点1 y坐标
x + width, // 点2 x坐标
y + height // 点2 y坐标
);
int pageNo = 1; // PDF 文件的页码从 1 开始,而不是 0
PdfFormField pdfFormField = PdfFormField.createSignature(ps.getWriter());
pdfFormField.setFieldName("AREA_SIGNATURE"); // 签名域标识
pdfFormField.setPage(pageNo);
pdfFormField.setWidget(areaSignatureRect, PdfAnnotation.HIGHLIGHT_OUTLINE); // 高亮显示
中间,可以通过 PdfAppearance 对象对这块区域的外观做下调整:
// 设置区域宽高和边框厚度,以及边框颜色,填充颜色
PdfAppearance pdfAppearance = PdfAppearance.createAppearance(
ps.getWriter(),
width,
height
);
pdfAppearance.setColorStroke(BaseColor.LIGHT_GRAY); // 边框颜色
pdfAppearance.setColorFill(BaseColor.YELLOW); // 填充颜色
// 填充矩形区域-开始
pdfAppearance.rectangle(
0, // x 轴偏移
0, // y 轴偏移
width, // 宽
height // 高
);
pdfAppearance.fillStroke();
// 填充矩形区域-结束
// 添加文字-开始
pdfAppearance.setColorFill(BaseColor.BLACK); // 填充颜色重置为黑色,显示文字
ColumnText.showTextAligned(
pdfAppearance,
Element.ALIGN_CENTER,
new Phrase("签名区域", new Font(bf)),
width / 2, // x
height / 2, // y
0 // rotation
);
// 添加文字-结束
// 将外观应用到签名域对象之上
pdfFormField.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, pdfAppearance);
最后,将签名域对象作为标注添加到 PdfStamper 对象:
ps.addAnnotation(pdfFormField, pageNo);
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有