Module: Itext::Signing

Included in:
Itext
Defined in:
lib/itext/signing.rb

Overview

This module will allow you signing PDF document with certificate

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Hook with some initalization



24
25
26
27
28
29
# File 'lib/itext/signing.rb', line 24

def self.included(base)
  base.extend(ClassMethods)

  attr_reader :private_key_path
  attr_reader :password
end

Instance Method Details

#enable_signing!(opts = {}) ⇒ Object

Enable document signing Required options: { private_key_path: ‘/path/key’ } Optional options: { password: ” }

Raises:

  • (ArgumentError)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/itext/signing.rb', line 34

def enable_signing!(opts = {})
  raise ArgumentError, "Please provide :private_key_path"            unless opts[:private_key_path]
  raise ArgumentError, "Specified :private_key_path does not exists" unless File.exists?(opts[:private_key_path])

  @private_key_path = opts[:private_key_path]
  @password         = opts[:password].to_s.to_java.toCharArray

  @keystore = Java::JavaSecurity::KeyStore.getInstance('pkcs12')
  @keystore.load(Java::JavaIo::FileInputStream.new(@private_key_path), @password)

  keystore_alias = @keystore.aliases().nextElement()
  @private_key   = @keystore.getKey(keystore_alias, @password).to_java(Java::JavaSecurity::PrivateKey)
  @cert_chain    = @keystore.getCertificateChain(keystore_alias)
end

#initialize(*args, &block) ⇒ Object

Add processing hook



16
17
18
19
20
21
# File 'lib/itext/signing.rb', line 16

def initialize(*args, &block)
  @hooks     ||= []
  @hooks.push ->{ process_signing }

  super rescue nil
end

#initialize_stamperObject

Change default behavior of stamper if using signing



55
56
57
# File 'lib/itext/signing.rb', line 55

def initialize_stamper
  Java::ComLowagieTextPdf::PdfStamper.createSignature(@reader, @buffer, 0x00.to_java(Java::JavaLang::Character)) if sign_file?
end

#sign_file?Boolean

Check if signing file should be done

Returns:

  • (Boolean)


50
51
52
# File 'lib/itext/signing.rb', line 50

def sign_file?
  @private_key_path && File.exists?(@private_key_path)
end