Why is model.SignatureHandler called twice, on initialize and on write?

Question

The model.SignatureHandler returned from sighandler.NewAdobeX509RSASHA1Custom is called twice when applying a digital signature to a PDF.

It is called the first time on signature.Initialize() signature being of type *model.PdfSignature
It is called the second time on appender.Write(...)appenderbeing of type*model.PdfAppender`

Why is this happening?

Answer

The extra call is made to get an initial estimate for the signature size. However, as you point out, this is not desirable when working with an external API.

In UniPDF v3.12.0 we added an option for sighandler.NewDocTimeStampWithOpts to skip this extra call by specifying a size parameter for the signature. Typically fine to make this quite a bit bigger than needed. Few extra bytes dont matter. See the release notes for an example of how to use this:
https://github.com/unidoc/unipdf/releases/tag/v3.12.0

Basically specifying it like this will avoid the extra call:

sigLen := 6000 // Reserve 6000 bytes for signature. handler, err := sighandler.NewDocTimeStampWithOpts( 		testTimestampServerURL, 		crypto.SHA512, 		&sighandler.DocTimeStampOpts{SignatureSize: sigLen}, 	)

It would make sense to create this kind of option for other signature handlers, such as the one you are using here (sighandler.NewAdobeX509RSASHA1Custom).

I recommend that you log into our Customer Service Desk and create a ticket there and we will get on this.