我目前正在开发一个ERP应用程序,它使用iText创建和签署PDF文件。我们的想法是应用程序可以生成带有帐单的PDF文件,然后使用PdfStamper或任何其他类来使用数字签名对其进行签名。这是我的代码:
创建和编辑提单
File f1 = null;
f1 = new File("myFilePath");
f1.delete();
if ((f1 != null) && (f1.createNewFile()))
{
//Here I call the procedure that creates the bill
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f1));
PdfFormField field = PdfFormField.createSignature(writer);
PdfSigner pdfSigner = new PdfSigner();
pdfSigner.setFileIn(f1.getAbsolutePath());
pdfSigner.setFileKey("myKeyPath.pfx");
pdfSigner.setFileKeyPassword("myPassword");
pdfSigner.setFileOut("myOutputPath");
if (pdfGenerator.factura(writer, pdfSigner, document))
{
//Here I show the File to the user
}
}
else
{
//Here I show an error
}
程序“factura”
public boolean factura (PdfWriter writer, PdfSigner signer, Document document) throws NullPointerException
{
try
{
//Here I set a PdfPageEvent before attaching it to the PdfWriter
writer.setPageEvent(myPdfPageEvent);
document.open();
//Here I manipulate the Document to generate the bill
signer.signPdf();
document.close();
return true;
}
//catch 4 or 5 different types of exceptions and return false if needed
}
CLASS PdfSigner
public class PdfSigner
{
private String fileKey = null;
private String fileKeyPassword = null;
private String fileIn = null;
private String fileOut = null;
public PdfSigner() {}
public boolean signPdf() throws IOException, DocumentException, Exception
{
if (fileKey == null || fileKeyPassword == null || fileIn == null || fileOut == null) return false;
try
{
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(fileKey), fileKeyPassword.toCharArray());
String alias = (String) ks.aliases().nextElement();
PrivateKey key = (PrivateKey) ks.getKey(alias, fileKeyPassword.toCharArray());
Certificate[] chain = ks.getCertificateChain(alias);
//BOOOOOM!
PdfReader pdfReader = new PdfReader((new File(fileIn)).getAbsolutePath());
FileOutputStream outputFile = new FileOutputStream(fileOut);
PdfStamper pdfStamper = PdfStamper.createSignature(pdfReader, outputFile, '?');
PdfSignatureAppearance sap = pdfStamper.getSignatureAppearance();
sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
sap.setVisibleSignature(new Rectangle(10, 10, 50, 30), 1, "sign_rbl");
pdfStamper.close();
return true;
}
catch (Exception key)
{
throw new Exception(key);
}
}
//getters and setters
}
嗯,这是错的,但我不知道它在哪里失败了。如果我尝试运行它,它通常会在设置PdfReader之前在我用“BOOOOM!”标记的行中抛出异常。但是如果我尝试在程序“factura”之外签名,在关闭文档之后,当我关闭PdfStamper时,异常通常会抛出到最后一行。在这两种情况下,原因始终相同:“找不到PDF标题签名。”
任何人都知道发生了什么?我99%肯定我给这个程序的路径是正确的,数字签名和密码也是正确的......
由于
PS:我发誓我已经尝试在这个页面的多个答案中找到解决方案,但它们都没有对我有用