Overview
ThePdfSignatureService provides comprehensive digital signature functionality for PDF documents using HexaPDF. It handles signature field detection, metadata extraction, digital signing with certificates, and image stamping.
Key Features:
- Detect signature fields in PDFs
- Read signature metadata (signer, date, reason, location)
- Sign PDFs with digital certificates (P12/PFX or PEM)
- Stamp signature images without certificates
- PAdES-compliant signatures (Adobe compatible)
hexapdfgem for signature operationshexapdf/image_loaderfor image processing
app/services/pdf_signature_service.rb
SignatureInfo Structure
Signature metadata is returned as aStruct:
Name of the signer
Timestamp when document was signed (PDF date format)
Reason for signing (e.g., “Document approval”)
Location where document was signed
Contact information of the signer
Signature format (e.g., “adbe.pkcs7.detached”)
Class Methods
list_signature_fields
Lists all signature fields in a PDF document and their status.Path to the PDF file to analyze
Array of hashes containing signature field information. Returns empty array on error.
Fully qualified field name
Whether the field contains a signature
Signature metadata if signed,
nil if unsignedsignature_info
Retrieves signature metadata for a specific field.Path to the PDF file
Name of the signature field to query
Signature metadata if field is signed,
nil if unsigned or field not foundsign
Digitally signs a PDF document in a specified signature field.Path to the input PDF file
Path where the signed PDF will be saved
Name of the signature field to sign
Path to certificate file (.p12, .pfx, or .pem)
Password for P12/PFX certificate (required for P12/PFX)
Path to PEM key file (required when using PEM certificate)
Reason for signing (e.g., “Document approval”)
Location where document is signed
Contact information of the signer
Name of the signer (displayed in signature appearance)
Path to signature image (PNG/JPG) for visual appearance
Path to the signed PDF file
- If
signature_image_pathis provided: Image is embedded in the signature field - Otherwise: Text-based appearance is generated with signer name, reason, and location
- Uses
adbe.pkcs7.detachedsub-filter (PAdES basic, Adobe compatible) - Attempts Ruby API first, falls back to CLI on failure
- Validates signature field exists before signing
- Raises error if field not found or signing fails
stamp_signature_image
Stamps a signature image onto a signature field without digital certificate.Path to the input PDF file
Path where the stamped PDF will be saved
Name of the signature field where image will be placed
Path to signature image file (PNG/JPG)
Maintain image aspect ratio within field bounds
Internal margin (in points) within the signature field
Allow upscaling image beyond original size (may reduce quality)
Path to the output PDF file
- Opens PDF and locates signature field widget (visible rectangle)
- Calculates image dimensions considering margins and scaling
- Draws image as overlay on the page containing the field
- Centers image within field if
scale_to_fitis true - Writes optimized PDF with embedded image
- Raises error if image file not found
- Raises error if signature field not found
- Falls back to
validate: falseif PDF has annotation validation issues - Logs errors and re-raises exceptions
- Handwritten signatures from signature pads
- Client signatures captured via web forms
- Visual representation without legal binding
- Preview signatures before final signing
Internal Methods
signature_field?
Checks if a field is a signature field.true if field type is :Sig.
extract_signature_info
Extracts signature metadata from a signed field.SignatureInfo struct or nil if unsigned.
extract_field_name
Robustly extracts field name across HexaPDF versions.fully_qualified_name, full_name, name, and falls back to field[:T].
build_signer
Creates a HexaPDF signer object from certificate.- P12/PFX: Uses
certificate_path+certificate_password - PEM: Uses
certificate_path+key_path
build_appearance_text
Generates text-based signature appearance.Complete Workflow Example
Certificate Formats
P12/PFX (Recommended)
- Single file contains certificate + private key
- Password protected
- Industry standard
PEM Certificate + Key
- Separate storage of certificate and key
- Common in Unix/Linux environments
Best Practices
Check Before Signing
Use
list_signature_fields to verify field exists and is unsignedSecure Certificates
Store certificates securely and use environment variables for passwords
Include Metadata
Always provide reason, location, and signer name for audit trails
Image + Certificate
Combine
signature_image_path with certificate for visual + legal validityError Handling
- “Campo de firma no encontrado”: Field name doesn’t exist
- “Se requiere key_path para certificado PEM”: Missing key file for PEM cert
- “Imagen de firma no encontrada”: Image path is invalid
- “Widget del campo no encontrado”: Signature field has no visible widget
Related Services
- PdfFormsParserService - Form field parsing and filling
- PdfMergingService - PDF merging with signatures