pdfbox java,在使用PDFBox的java中,如何使用文本创建可见的数字签名-程序员宅基地

技术标签: pdfbox java  

Digital text with text and background imageI am trying to digitally sign pdf file using PDFBox in Java with visible text to appear on page similar to one that gets created when manually created in Acrobat. As shown in the image (one with only snap shot I am looking for and another with details of digital signature too), this example shows signing using image file. How to do that?

7roNi.jpg

解决方案

This code will be included among the samples in the upcoming 2.0.9 release of PDFBox. See also the discussion in PDFBOX-3198. It is more flexible and can include both text and images, or only one of the two, or vector graphics, whatever you want.

/**

* This is a second example for visual signing a pdf. It doesn't use the "design pattern" influenced

* PDVisibleSignDesigner, and doesn't create its complex multilevel forms described in the Adobe

* document

* Digital

* Signature Appearances, because this isn't required by the PDF specification. See the

* discussion in December 2017 in PDFBOX-3198.

*

* @author Vakhtang Koroghlishvili

* @author Tilman Hausherr

*/

public class CreateVisibleSignature2 extends CreateSignatureBase

{

private SignatureOptions signatureOptions;

private boolean lateExternalSigning = false;

private File imageFile;

/**

* Initialize the signature creator with a keystore (pkcs12) and pin that

* should be used for the signature.

*

* @param keystore is a pkcs12 keystore.

* @param pin is the pin for the keystore / private key

* @throws KeyStoreException if the keystore has not been initialized (loaded)

* @throws NoSuchAlgorithmException if the algorithm for recovering the key cannot be found

* @throws UnrecoverableKeyException if the given password is wrong

* @throws CertificateException if the certificate is not valid as signing time

* @throws IOException if no certificate could be found

*/

public CreateVisibleSignature2(KeyStore keystore, char[] pin)

throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, CertificateException

{

super(keystore, pin);

}

public File getImageFile()

{

return imageFile;

}

public void setImageFile(File imageFile)

{

this.imageFile = imageFile;

}

public boolean isLateExternalSigning()

{

return lateExternalSigning;

}

/**

* Set late external signing. Enable this if you want to activate the demo code where the

* signature is kept and added in an extra step without using PDFBox methods. This is disabled

* by default.

*

* @param lateExternalSigning

*/

public void setLateExternalSigning(boolean lateExternalSigning)

{

this.lateExternalSigning = lateExternalSigning;

}

/**

* Sign pdf file and create new file that ends with "_signed.pdf".

*

* @param inputFile The source pdf document file.

* @param signedFile The file to be signed.

* @param humanRect rectangle from a human viewpoint (coordinates start at top left)

* @param tsaUrl optional TSA url

* @throws IOException

*/

public void signPDF(File inputFile, File signedFile, Rectangle2D humanRect, String tsaUrl) throws IOException

{

this.signPDF(inputFile, signedFile, humanRect, tsaUrl, null);

}

/**

* Sign pdf file and create new file that ends with "_signed.pdf".

*

* @param inputFile The source pdf document file.

* @param signedFile The file to be signed.

* @param humanRect rectangle from a human viewpoint (coordinates start at top left)

* @param tsaUrl optional TSA url

* @param signatureFieldName optional name of an existing (unsigned) signature field

* @throws IOException

*/

public void signPDF(File inputFile, File signedFile, Rectangle2D humanRect, String tsaUrl, String signatureFieldName) throws IOException

{

if (inputFile == null || !inputFile.exists())

{

throw new IOException("Document for signing does not exist");

}

setTsaUrl(tsaUrl);

// creating output document and prepare the IO streams.

FileOutputStream fos = new FileOutputStream(signedFile);

try (PDDocument doc = PDDocument.load(inputFile))

{

int accessPermissions = SigUtils.getMDPPermission(doc);

if (accessPermissions == 1)

{

throw new IllegalStateException("No changes to the document are permitted due to DocMDP transform parameters dictionary");

}

// Note that PDFBox has a bug that visual signing on certified files with permission 2

// doesn't work properly, see PDFBOX-3699. As long as this issue is open, you may want to

// be careful with such files.

PDSignature signature = null;

PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();

PDRectangle rect = null;

// sign a PDF with an existing empty signature, as created by the CreateEmptySignatureForm example.

if (acroForm != null)

{

signature = findExistingSignature(acroForm, signatureFieldName);

if (signature != null)

{

rect = acroForm.getField(signatureFieldName).getWidgets().get(0).getRectangle();

}

}

if (signature == null)

{

// create signature dictionary

signature = new PDSignature();

}

if (rect == null)

{

rect = createSignatureRectangle(doc, humanRect);

}

// Optional: certify

// can be done only if version is at least 1.5 and if not already set

// doing this on a PDF/A-1b file fails validation by Adobe preflight (PDFBOX-3821)

// PDF/A-1b requires PDF version 1.4 max, so don't increase the version on such files.

if (doc.getVersion() >= 1.5f && accessPermissions == 0)

{

SigUtils.setMDPPermission(doc, signature, 2);

}

if (acroForm != null && acroForm.getNeedAppearances())

{

// PDFBOX-3738 NeedAppearances true results in visible signature becoming invisible

// with Adobe Reader

if (acroForm.getFields().isEmpty())

{

// we can safely delete it if there are no fields

acroForm.getCOSObject().removeItem(COSName.NEED_APPEARANCES);

// note that if you've set MDP permissions, the removal of this item

// may result in Adobe Reader claiming that the document has been changed.

// and/or that field content won't be displayed properly.

// ==> decide what you prefer and adjust your code accordingly.

}

else

{

System.out.println("/NeedAppearances is set, signature may be ignored by Adobe Reader");

}

}

// default filter

signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);

// subfilter for basic and PAdES Part 2 signatures

signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);

signature.setName("Name");

signature.setLocation("Location");

signature.setReason("Reason");

// the signing date, needed for valid signature

signature.setSignDate(Calendar.getInstance());

// do not set SignatureInterface instance, if external signing used

SignatureInterface signatureInterface = isExternalSigning() ? null : this;

// register signature dictionary and sign interface

signatureOptions = new SignatureOptions();

signatureOptions.setVisualSignature(createVisualSignatureTemplate(doc, 0, rect));

signatureOptions.setPage(0);

doc.addSignature(signature, signatureInterface, signatureOptions);

if (isExternalSigning())

{

System.out.println("Signing externally " + signedFile.getName());

ExternalSigningSupport externalSigning = doc.saveIncrementalForExternalSigning(fos);

// invoke external signature service

byte[] cmsSignature = sign(externalSigning.getContent());

// Explanation of late external signing (off by default):

// If you want to add the signature in a separate step, then set an empty byte array

// and call signature.getByteRange() and remember the offset signature.getByteRange()[1]+1.

// you can write the ascii hex signature at a later time even if you don't have this

// PDDocument object anymore, with classic java file random access methods.

// If you can't remember the offset value from ByteRange because your context has changed,

// then open the file with PDFBox, find the field with findExistingSignature() or

// PODDocument.getLastSignatureDictionary() and get the ByteRange from there.

// Close the file and then write the signature as explained earlier in this comment.

if (isLateExternalSigning())

{

// this saves the file with a 0 signature

externalSigning.setSignature(new byte[0]);

// remember the offset (add 1 because of "

int offset = signature.getByteRange()[1] + 1;

// now write the signature at the correct offset without any PDFBox methods

try (RandomAccessFile raf = new RandomAccessFile(signedFile, "rw"))

{

raf.seek(offset);

raf.write(Hex.getBytes(cmsSignature));

}

}

else

{

// set signature bytes received from the service and save the file

externalSigning.setSignature(cmsSignature);

}

}

else

{

// write incremental (only for signing purpose)

doc.saveIncremental(fos);

}

}

// Do not close signatureOptions before saving, because some COSStream objects within

// are transferred to the signed document.

// Do not allow signatureOptions get out of scope before saving, because then the COSDocument

// in signature options might by closed by gc, which would close COSStream objects prematurely.

// See https://issues.apache.org/jira/browse/PDFBOX-3743

IOUtils.closeQuietly(signatureOptions);

}

private PDRectangle createSignatureRectangle(PDDocument doc, Rectangle2D humanRect)

{

float x = (float) humanRect.getX();

float y = (float) humanRect.getY();

float width = (float) humanRect.getWidth();

float height = (float) humanRect.getHeight();

PDPage page = doc.getPage(0);

PDRectangle pageRect = page.getCropBox();

PDRectangle rect = new PDRectangle();

// signing should be at the same position regardless of page rotation.

switch (page.getRotation())

{

case 90:

rect.setLowerLeftY(x);

rect.setUpperRightY(x + width);

rect.setLowerLeftX(y);

rect.setUpperRightX(y + height);

break;

case 180:

rect.setUpperRightX(pageRect.getWidth() - x);

rect.setLowerLeftX(pageRect.getWidth() - x - width);

rect.setLowerLeftY(y);

rect.setUpperRightY(y + height);

break;

case 270:

rect.setLowerLeftY(pageRect.getHeight() - x - width);

rect.setUpperRightY(pageRect.getHeight() - x);

rect.setLowerLeftX(pageRect.getWidth() - y - height);

rect.setUpperRightX(pageRect.getWidth() - y);

break;

case 0:

default:

rect.setLowerLeftX(x);

rect.setUpperRightX(x + width);

rect.setLowerLeftY(pageRect.getHeight() - y - height);

rect.setUpperRightY(pageRect.getHeight() - y);

break;

}

return rect;

}

// create a template PDF document with empty signature and return it as a stream.

private InputStream createVisualSignatureTemplate(PDDocument srcDoc, int pageNum, PDRectangle rect) throws IOException

{

try (PDDocument doc = new PDDocument())

{

PDPage page = new PDPage(srcDoc.getPage(pageNum).getMediaBox());

doc.addPage(page);

PDAcroForm acroForm = new PDAcroForm(doc);

doc.getDocumentCatalog().setAcroForm(acroForm);

PDSignatureField signatureField = new PDSignatureField(acroForm);

PDAnnotationWidget widget = signatureField.getWidgets().get(0);

List acroFormFields = acroForm.getFields();

acroForm.setSignaturesExist(true);

acroForm.setAppendOnly(true);

acroForm.getCOSObject().setDirect(true);

acroFormFields.add(signatureField);

widget.setRectangle(rect);

// from PDVisualSigBuilder.createHolderForm()

PDStream stream = new PDStream(doc);

PDFormXObject form = new PDFormXObject(stream);

PDResources res = new PDResources();

form.setResources(res);

form.setFormType(1);

PDRectangle bbox = new PDRectangle(rect.getWidth(), rect.getHeight());

float height = bbox.getHeight();

Matrix initialScale = null;

switch (srcDoc.getPage(pageNum).getRotation())

{

case 90:

form.setMatrix(AffineTransform.getQuadrantRotateInstance(1));

initialScale = Matrix.getScaleInstance(bbox.getWidth() / bbox.getHeight(), bbox.getHeight() / bbox.getWidth());

height = bbox.getWidth();

break;

case 180:

form.setMatrix(AffineTransform.getQuadrantRotateInstance(2));

break;

case 270:

form.setMatrix(AffineTransform.getQuadrantRotateInstance(3));

initialScale = Matrix.getScaleInstance(bbox.getWidth() / bbox.getHeight(), bbox.getHeight() / bbox.getWidth());

height = bbox.getWidth();

break;

case 0:

default:

break;

}

form.setBBox(bbox);

PDFont font = PDType1Font.HELVETICA_BOLD;

// from PDVisualSigBuilder.createAppearanceDictionary()

PDAppearanceDictionary appearance = new PDAppearanceDictionary();

appearance.getCOSObject().setDirect(true);

PDAppearanceStream appearanceStream = new PDAppearanceStream(form.getCOSObject());

appearance.setNormalAppearance(appearanceStream);

widget.setAppearance(appearance);

try (PDPageContentStream cs = new PDPageContentStream(doc, appearanceStream))

{

// for 90° and 270° scale ratio of width / height

// not really sure about this

// why does scale have no effect when done in the form matrix???

if (initialScale != null)

{

cs.transform(initialScale);

}

// show background (just for debugging, to see the rect size + position)

cs.setNonStrokingColor(Color.yellow);

cs.addRect(-5000, -5000, 10000, 10000);

cs.fill();

// show background image

// save and restore graphics if the image is too large and needs to be scaled

cs.saveGraphicsState();

cs.transform(Matrix.getScaleInstance(0.25f, 0.25f));

PDImageXObject img = PDImageXObject.createFromFileByExtension(imageFile, doc);

cs.drawImage(img, 0, 0);

cs.restoreGraphicsState();

// show text

float fontSize = 10;

float leading = fontSize * 1.5f;

cs.beginText();

cs.setFont(font, fontSize);

cs.setNonStrokingColor(Color.black);

cs.newLineAtOffset(fontSize, height - leading);

cs.setLeading(leading);

cs.showText("(Signature very wide line 1)");

cs.newLine();

cs.showText("(Signature very wide line 2)");

cs.newLine();

cs.showText("(Signature very wide line 3)");

cs.endText();

}

// no need to set annotations and /P entry

ByteArrayOutputStream baos = new ByteArrayOutputStream();

doc.save(baos);

return new ByteArrayInputStream(baos.toByteArray());

}

}

// Find an existing signature (assumed to be empty). You will usually not need this.

private PDSignature findExistingSignature(PDAcroForm acroForm, String sigFieldName)

{

PDSignature signature = null;

PDSignatureField signatureField;

if (acroForm != null)

{

signatureField = (PDSignatureField) acroForm.getField(sigFieldName);

if (signatureField != null)

{

// retrieve signature dictionary

signature = signatureField.getSignature();

if (signature == null)

{

signature = new PDSignature();

// after solving PDFBOX-3524

// signatureField.setValue(signature)

// until then:

signatureField.getCOSObject().setItem(COSName.V, signature);

}

else

{

throw new IllegalStateException("The signature field " + sigFieldName + " is already signed.");

}

}

}

return signature;

}

/**

* Arguments are

* [0] key store

* [1] pin

* [2] document that will be signed

* [3] image of visible signature

*

* @param args

* @throws java.security.KeyStoreException

* @throws java.security.cert.CertificateException

* @throws java.io.IOException

* @throws java.security.NoSuchAlgorithmException

* @throws java.security.UnrecoverableKeyException

*/

public static void main(String[] args) throws KeyStoreException, CertificateException,

IOException, NoSuchAlgorithmException, UnrecoverableKeyException

{

// generate with

// keytool -storepass 123456 -storetype PKCS12 -keystore file.p12 -genkey -alias client -keyalg RSA

if (args.length < 4)

{

usage();

System.exit(1);

}

String tsaUrl = null;

// External signing is needed if you are using an external signing service, e.g. to sign

// several files at once.

boolean externalSig = false;

for (int i = 0; i < args.length; i++)

{

if (args[i].equals("-tsa"))

{

i++;

if (i >= args.length)

{

usage();

System.exit(1);

}

tsaUrl = args[i];

}

if (args[i].equals("-e"))

{

externalSig = true;

}

}

File ksFile = new File(args[0]);

KeyStore keystore = KeyStore.getInstance("PKCS12");

char[] pin = args[1].toCharArray();

keystore.load(new FileInputStream(ksFile), pin);

File documentFile = new File(args[2]);

CreateVisibleSignature2 signing = new CreateVisibleSignature2(keystore, pin.clone());

signing.setImageFile(new File(args[3]));

File signedDocumentFile;

String name = documentFile.getName();

String substring = name.substring(0, name.lastIndexOf('.'));

signedDocumentFile = new File(documentFile.getParent(), substring + "_signed.pdf");

signing.setExternalSigning(externalSig);

// Set the signature rectangle

// Although PDF coordinates start from the bottom, humans start from the top.

// So a human would want to position a signature (x,y) units from the

// top left of the displayed page, and the field has a horizontal width and a vertical height

// regardless of page rotation.

Rectangle2D humanRect = new Rectangle2D.Float(100, 200, 150, 50);

signing.signPDF(documentFile, signedDocumentFile, humanRect, tsaUrl, "Signature1");

}

/**

* This will print the usage for this program.

*/

private static void usage()

{

System.err.println("Usage: java " + CreateVisibleSignature2.class.getName()

+ " \n" + "" +

"options:\n" +

" -tsa sign timestamp using the given TSA server\n"+

" -e sign using external signature creation scenario");

}

}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_39553904/article/details/118831165

智能推荐

攻防世界_难度8_happy_puzzle_攻防世界困难模式攻略图文-程序员宅基地

文章浏览阅读645次。这个肯定是末尾的IDAT了,因为IDAT必须要满了才会开始一下个IDAT,这个明显就是末尾的IDAT了。,对应下面的create_head()代码。,对应下面的create_tail()代码。不要考虑爆破,我已经试了一下,太多情况了。题目来源:UNCTF。_攻防世界困难模式攻略图文

达梦数据库的导出(备份)、导入_达梦数据库导入导出-程序员宅基地

文章浏览阅读2.9k次,点赞3次,收藏10次。偶尔会用到,记录、分享。1. 数据库导出1.1 切换到dmdba用户su - dmdba1.2 进入达梦数据库安装路径的bin目录,执行导库操作  导出语句:./dexp cwy_init/[email protected]:5236 file=cwy_init.dmp log=cwy_init_exp.log 注释:   cwy_init/init_123..._达梦数据库导入导出

js引入kindeditor富文本编辑器的使用_kindeditor.js-程序员宅基地

文章浏览阅读1.9k次。1. 在官网上下载KindEditor文件,可以删掉不需要要到的jsp,asp,asp.net和php文件夹。接着把文件夹放到项目文件目录下。2. 修改html文件,在页面引入js文件:<script type="text/javascript" src="./kindeditor/kindeditor-all.js"></script><script type="text/javascript" src="./kindeditor/lang/zh-CN.js"_kindeditor.js

STM32学习过程记录11——基于STM32G431CBU6硬件SPI+DMA的高效WS2812B控制方法-程序员宅基地

文章浏览阅读2.3k次,点赞6次,收藏14次。SPI的详情简介不必赘述。假设我们通过SPI发送0xAA,我们的数据线就会变为10101010,通过修改不同的内容,即可修改SPI中0和1的持续时间。比如0xF0即为前半周期为高电平,后半周期为低电平的状态。在SPI的通信模式中,CPHA配置会影响该实验,下图展示了不同采样位置的SPI时序图[1]。CPOL = 0,CPHA = 1:CLK空闲状态 = 低电平,数据在下降沿采样,并在上升沿移出CPOL = 0,CPHA = 0:CLK空闲状态 = 低电平,数据在上升沿采样,并在下降沿移出。_stm32g431cbu6

计算机网络-数据链路层_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输-程序员宅基地

文章浏览阅读1.2k次,点赞2次,收藏8次。数据链路层习题自测问题1.数据链路(即逻辑链路)与链路(即物理链路)有何区别?“电路接通了”与”数据链路接通了”的区别何在?2.数据链路层中的链路控制包括哪些功能?试讨论数据链路层做成可靠的链路层有哪些优点和缺点。3.网络适配器的作用是什么?网络适配器工作在哪一层?4.数据链路层的三个基本问题(帧定界、透明传输和差错检测)为什么都必须加以解决?5.如果在数据链路层不进行帧定界,会发生什么问题?6.PPP协议的主要特点是什么?为什么PPP不使用帧的编号?PPP适用于什么情况?为什么PPP协议不_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输

软件测试工程师移民加拿大_无证移民,未受过软件工程师的教育(第1部分)-程序员宅基地

文章浏览阅读587次。软件测试工程师移民加拿大 无证移民,未受过软件工程师的教育(第1部分) (Undocumented Immigrant With No Education to Software Engineer(Part 1))Before I start, I want you to please bear with me on the way I write, I have very little gen...

随便推点

Thinkpad X250 secure boot failed 启动失败问题解决_安装完系统提示secureboot failure-程序员宅基地

文章浏览阅读304次。Thinkpad X250笔记本电脑,装的是FreeBSD,进入BIOS修改虚拟化配置(其后可能是误设置了安全开机),保存退出后系统无法启动,显示:secure boot failed ,把自己惊出一身冷汗,因为这台笔记本刚好还没开始做备份.....根据错误提示,到bios里面去找相关配置,在Security里面找到了Secure Boot选项,发现果然被设置为Enabled,将其修改为Disabled ,再开机,终于正常启动了。_安装完系统提示secureboot failure

C++如何做字符串分割(5种方法)_c++ 字符串分割-程序员宅基地

文章浏览阅读10w+次,点赞93次,收藏352次。1、用strtok函数进行字符串分割原型: char *strtok(char *str, const char *delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。其它:strtok函数线程不安全,可以使用strtok_r替代。示例://借助strtok实现split#include <string.h>#include <stdio.h&_c++ 字符串分割

2013第四届蓝桥杯 C/C++本科A组 真题答案解析_2013年第四届c a组蓝桥杯省赛真题解答-程序员宅基地

文章浏览阅读2.3k次。1 .高斯日记 大数学家高斯有个好习惯:无论如何都要记日记。他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?高斯出生于:1777年4月30日。在高斯发现的一个重要定理的日记_2013年第四届c a组蓝桥杯省赛真题解答

基于供需算法优化的核极限学习机(KELM)分类算法-程序员宅基地

文章浏览阅读851次,点赞17次,收藏22次。摘要:本文利用供需算法对核极限学习机(KELM)进行优化,并用于分类。

metasploitable2渗透测试_metasploitable2怎么进入-程序员宅基地

文章浏览阅读1.1k次。一、系统弱密码登录1、在kali上执行命令行telnet 192.168.26.1292、Login和password都输入msfadmin3、登录成功,进入系统4、测试如下:二、MySQL弱密码登录:1、在kali上执行mysql –h 192.168.26.129 –u root2、登录成功,进入MySQL系统3、测试效果:三、PostgreSQL弱密码登录1、在Kali上执行psql -h 192.168.26.129 –U post..._metasploitable2怎么进入

Python学习之路:从入门到精通的指南_python人工智能开发从入门到精通pdf-程序员宅基地

文章浏览阅读257次。本文将为初学者提供Python学习的详细指南,从Python的历史、基础语法和数据类型到面向对象编程、模块和库的使用。通过本文,您将能够掌握Python编程的核心概念,为今后的编程学习和实践打下坚实基础。_python人工智能开发从入门到精通pdf