3

我目前正在开发一个使用 iText 创建和签署 PDF 文件的 ERP 应用程序。这个想法是该应用程序可以生成带有账单的 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
}

程序“事实”

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
}

类 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:我发誓我已尝试在此页面中的多个答案中找到解决方案,但事实证明它们对我没有任何用处

4

0 回答 0