Add digital signature or digitally sign PDF in Java

Aspose.PDF for Java supports multiple signing flows through PdfFileSignature.

Sign a PDF with a certificate object

  1. Create the PdfFileSignature facade and bind the source PDF document.
  2. Create the PKCS7 signature object and configure the signing options.
  3. Apply the signature to the PDF document through PdfFileSignature.
  4. Save the updated PDF document.
public static void signPdfWithCertificateObject(Path inputFile, Path certificateFile, Path outputFile) {
    PdfFileSignature pdfSignature = new PdfFileSignature();
    try {
        pdfSignature.bindPdf(inputFile.toString());
        pdfSignature.sign(1, false, signatureRectangle(), createPkcs7(certificateFile, "Document approval"));
        pdfSignature.save(outputFile.toString());
    } finally {
        pdfSignature.close();
    }
}

This approach builds a PKCS7 signature object first and then applies it to page 1.

Sign a PDF with basic certificate parameters

  1. Create the PdfFileSignature facade and bind the source PDF document.
  2. Configure the certificate parameters required by the signing example.
  3. Apply the signature to the PDF document through PdfFileSignature.
  4. Save the updated PDF document.
public static void signPdfWithBasicParameters(Path inputFile, Path certificateFile, Path outputFile) {
    PdfFileSignature pdfSignature = new PdfFileSignature();
    try {
        pdfSignature.bindPdf(inputFile.toString());
        pdfSignature.setCertificate(certificateFile.toString(), CERTIFICATE_PASSWORD);
        pdfSignature.sign(1, "Document approval", "qa@example.com", "New York, USA", false, signatureRectangle());
        pdfSignature.save(outputFile.toString());
    } finally {
        pdfSignature.close();
    }
}

Certify a PDF with DocMDP

Use a document modification detection and prevention signature when you need certification-level restrictions:

  1. Create the PdfFileSignature facade and bind the source PDF document.
  2. Create the DocMDPSignature object and configure the DocMDPAccessPermissions signing options.
  3. Apply the certification signature and save the updated PDF document.
public static void certifyPdfWithMdpSignature(Path inputFile, Path certificateFile, Path outputFile) {
    PdfFileSignature pdfSignature = new PdfFileSignature();
    try {
        pdfSignature.bindPdf(inputFile.toString());
        DocMDPSignature signature = new DocMDPSignature(
                createPkcs7(certificateFile, "Certified for form filling and signing"),
                DocMDPAccessPermissions.FillingInForms);
        pdfSignature.certify(1, "Certified for form filling and signing", "security@example.com",
                "New York, USA", true, signatureRectangle(), signature);
        pdfSignature.save(outputFile.toString());
    } finally {
        pdfSignature.close();
    }
}