REIGN

11 min read · 2,160 words

How to Sign a PDF File Using PHP (TCPDF and PAdES)

How to sign a PDF file using PHP

To sign a PDF with PHP you need a certificate and private key, and a library that can write a cryptographic signature into the file. TCPDF does this with one call, setSignature(), and its successor tc-lib-pdf adds PAdES signatures and timestamps. If you only want a handwritten signature picture on the page, that is a different and much simpler job, covered below.

This guide separates the two, shows example code for each, and lists which libraries are still maintained. Pick the approach that matches how much legal weight the document needs.

Two things people call “signing a PDF”

The word covers two very different features. Choose before you write code.

Visible signature imageCryptographic digital signature
What it isA picture or typed name drawn on the pageA signed hash of the file, stored inside it, tied to a certificate
Proves who signedNo. Anyone can paste an imageYes, to the extent the certificate is trusted
Detects later editsNoYes. Viewers show the signature as broken if the file changes
Needs a certificateNoYes
Typical useInternal approvals, simple consent formsContracts, invoices, official records

A digital signature does not have to show anything on the page. It can be invisible and still be checked by Adobe Acrobat or any other viewer that validates signatures. Many projects use both: a visible stamp so people can see the page was signed, backed by a real signature underneath.

Whether a signature is legally binding depends on your country and document type. In the European Union, eIDAS defines simple, advanced and qualified signatures. A self-signed certificate does not reach the advanced or qualified levels. Ask a lawyer before you automate signing for contracts. For a wider look at signing tools that are not code, see our list of software for electronic signatures on documents.

Which PHP libraries are worth using

These are the options that exist and are maintained today. Each one has recent releases on its repository and Packagist page.

  • TCPDF creates PDFs and can sign them with setSignature(). It is now in maintenance-only mode. From version 7 it is a compatibility layer over tc-lib-pdf and needs PHP 8.2 or newer. Existing code keeps working, so it is fine for current projects.
  • tc-lib-pdf is the successor from the same author and is where active development happens. Its documentation lists detached CMS signatures and PAdES profiles from baseline B-B up to B-LTA, RFC 3161 timestamps and remote key services. Choose it for new projects that need long-term validation.
  • FPDI imports pages from an existing PDF so you can use them as templates in TCPDF or FPDF. It does not sign anything itself. It is the bridge that lets you stamp and sign a PDF you did not generate.
  • SetaPDF-Signer from Setasign is a commercial component built for signing, timestamping and validating PDFs. It is a sensible choice when you have a budget and need support.

Two libraries named in older tutorials, including the earlier version of this post, are not on this list. FPDF only generates PDFs and has no signing support. “PHPSigner” is not a library I could confirm as maintained, so do not build on it. The phpseclib package is a good cryptography library, but TCPDF signs through PHP’s own OpenSSL extension, so you do not need it for this task.

If you would rather not write signing code at all, command-line tools such as JSignPdf can sign a file from a PHP exec() call. That adds a Java dependency, so weigh it against a pure PHP route.

Step 1: Get a certificate and private key

A digital signature needs two files: a private key that only you hold, and a certificate that contains the matching public key and your identity.

  • For testing, create a self-signed certificate. Viewers will warn that the signer is not trusted, which is correct.
  • For production, buy a document signing certificate from a certificate authority. Adobe’s trusted list (AATL) certificates make Acrobat show a green tick without extra setup. If you operate under eIDAS, use a provider that issues qualified certificates.

Create a test pair with OpenSSL. This asks you for a passphrase, which protects the key file:

openssl req -x509 -newkey rsa:3072 -sha256 -days 365 \
  -keyout signing.key -out signing.crt \
  -subj "/CN=Example Signer/O=Example Ltd"

You now have signing.key (private, keep secret) and signing.crt (public). Store them outside the web root, with file permissions that only the PHP user can read.

Step 2: Install the library

Use Composer. For TCPDF:

composer require tecnickcom/tcpdf

If you need to sign an existing PDF as well, add FPDI:

composer require setasign/fpdi

Check your PHP version first. The current TCPDF release requires PHP 8.2 or newer. Older TCPDF 6.x releases run on earlier PHP versions but only receive maintenance fixes.

Step 3: Generate and sign a new PDF

This script creates a one page PDF, signs it, shows a visible signature box and writes the file to disk. Read the passphrase from the environment, not from the source code.

<?php
require __DIR__ . '/vendor/autoload.php';

$cert = 'file://' . __DIR__ . '/keys/signing.crt';
$key  = 'file://' . __DIR__ . '/keys/signing.key';
$pass = getenv( 'PDF_KEY_PASSPHRASE' );

$pdf = new TCPDF( 'P', 'mm', 'A4', true, 'UTF-8', false );
$pdf->setCreator( 'Example Ltd' );
$pdf->setTitle( 'Service agreement' );
$pdf->setPrintHeader( false );
$pdf->setPrintFooter( false );

// Certificate, private key, key passphrase, extra chain certs, certification type, info.
$pdf->setSignature(
	$cert,
	$key,
	$pass,
	'',
	2,
	array(
		'Name'        => 'Example Signer',
		'Location'    => 'London',
		'Reason'      => 'Agreement approval',
		'ContactInfo' => 'legal@example.com',
	)
);

$pdf->setFont( 'helvetica', '', 12 );
$pdf->AddPage();
$pdf->writeHTML( '<h1>Service agreement</h1><p>Terms go here.</p>', true, false, true, false, '' );

// Optional visible box: x, y, width, height in mm, on the current page.
$pdf->setSignatureAppearance( 150, 240, 45, 20 );

$pdf->Output( __DIR__ . '/out/agreement-signed.pdf', 'F' );

Three details trip people up. Call setSignature() before Output(), because the signature is added when the file is written. Use file:// with an absolute path, or pass the PEM contents directly. And do not modify the PDF after signing. Any change, even re-saving, breaks the signature.

The certification type value 2 is the TCPDF default and allows form filling and further signing after yours. Value 1 means no changes are allowed at all, which suits a final contract. The TCPDF source documents the full list of values.

Step 4: Sign an existing PDF

A common request is to sign a file that someone uploaded. TCPDF cannot edit a PDF in place, but FPDI can import its pages into a new TCPDF document, which you then sign. The result is a new file with the same page content, not a patched copy of the original, so run it only on documents you are allowed to reproduce.

<?php
require __DIR__ . '/vendor/autoload.php';

use setasign\Fpdi\Tcpdf\Fpdi;

$pdf = new Fpdi();
$pdf->setPrintHeader( false );
$pdf->setPrintFooter( false );

$pdf->setSignature(
	'file://' . __DIR__ . '/keys/signing.crt',
	'file://' . __DIR__ . '/keys/signing.key',
	getenv( 'PDF_KEY_PASSPHRASE' ),
	'',
	2,
	array( 'Name' => 'Example Signer', 'Reason' => 'Approved' )
);

$pageCount = $pdf->setSourceFile( __DIR__ . '/in/contract.pdf' );
for ( $i = 1; $i <= $pageCount; $i++ ) {
	$tpl  = $pdf->importPage( $i );
	$size = $pdf->getTemplateSize( $tpl );
	$pdf->AddPage( $size['orientation'], array( $size['width'], $size['height'] ) );
	$pdf->useTemplate( $tpl );
}

$pdf->Output( __DIR__ . '/out/contract-signed.pdf', 'F' );

Test this on your own PHP and TCPDF versions before you rely on it. FPDI lists TCPDF 6.x as its tested companion, and TCPDF 7 changed its internals. Source PDFs that are encrypted or use newer compression features may not import, so reject those uploads with a clear error.

Add a visible handwritten-style signature image

If you only need a picture of a signature on the page, draw it with Image() at a fixed position. Keep the image on the server, never accept a path from a user.

$pdf->Image( __DIR__ . '/assets/signature.png', 150, 235, 40, 0, 'PNG' );
$pdf->setFont( 'helvetica', '', 9 );
$pdf->SetXY( 150, 252 );
$pdf->Cell( 40, 5, 'Signed on ' . gmdate( 'Y-m-d' ) . ' UTC', 0, 0, 'L' );

This proves nothing on its own. Combine it with setSignature() from Step 3 if the document matters.

Step 5: Verify the result

Open the signed file in Adobe Acrobat Reader and check the signature panel. With a self-signed certificate you will see that the signer’s identity is unknown, but the document integrity check should say the file has not changed since signing. You can add the test certificate to the viewer’s trusted identities to see a green state.

From the command line, pdfsig signed.pdf (part of the Poppler tools) prints the signature details and whether the digest matches. Automate that in your tests so a library upgrade cannot silently break signing.

Several signatures on one document

A PDF can carry more than one signature, each added as an incremental update after the previous one. TCPDF writes a single signature when it generates the file, so the multi-signer case needs a different tool. tc-lib-pdf and SetaPDF-Signer both document signing in stages, and a remote key service can sign in two phases. For a workflow where two or three people sign in sequence, plan this early, because it affects which library you choose.

Best practices for signing in PHP

  • Guard the private key. Keep it outside the web root, make it readable only by the PHP user, protect it with a passphrase held in the environment, and never commit it to Git. For many signers or high-value documents use an HSM or a key service, which tc-lib-pdf supports through its external signing workflow.
  • Use a trusted certificate in production. Self-signed certificates are for development.
  • Add a trusted timestamp if the document must be valid after the certificate expires. PAdES B-T and above, available in tc-lib-pdf, embeds an RFC 3161 timestamp.
  • Validate input. Treat uploaded PDFs as untrusted. Limit size, check the MIME type and reject files that fail to parse.
  • Sign last. Make every change to the document first, then sign, then store it read-only.
  • Log each signing event with the user, time and document hash, so you have an audit trail.
  • Do the work off the request. Signing large files can take seconds. Queue it as a background job instead of making a visitor wait.

Signing PDFs inside WordPress

Put the code in a small plugin, not in your theme, so it survives a theme change. Run it from a REST route or an admin-post handler that checks a nonce and a capability, and store the key path in a constant defined in wp-config.php. Save the finished file under the uploads directory in a protected subfolder, or serve it through a download handler that checks who is asking. If you run a membership or course site, this is the same pattern used for certificates of completion and signed consent forms.

Frequently asked questions

How do I sign a PDF with PHP?

Install TCPDF with Composer, create a certificate and private key, call setSignature() with them, build the document and write it with Output(). The full code is in Step 3 above. For PAdES signatures and timestamps, use tc-lib-pdf instead.

What is the difference between a digital signature and an image signature?

An image signature is a picture on the page and proves nothing. A digital signature is a cryptographic hash of the file signed with a private key, which identifies the signer and shows if the file was edited afterwards.

Can I use a self-signed certificate?

Yes, for testing. The signature will be valid, but viewers will warn that the signer is unknown. For contracts and public documents use a certificate from a recognised certificate authority.

Is TCPDF still maintained?

It is in maintenance-only mode. The project’s own README says active development has moved to tc-lib-pdf, and TCPDF 7 now wraps that engine. It still receives releases, so it is fine for existing code. New projects should look at tc-lib-pdf.

Can PHP sign a PDF that someone else created?

Yes, with FPDI and TCPDF as in Step 4, which rebuilds the document from the imported pages. A commercial component such as SetaPDF-Signer can add a signature to an existing file as an incremental update without rebuilding it.

Is a PHP-signed PDF legally binding?

It depends on the country, the document type and the certificate. A digital signature with a trusted certificate is strong evidence, but binding status is a legal question. Check the rules for your region, such as eIDAS in the European Union.

Why does the signature show as invalid after I edited the PDF?

A signature covers the exact bytes of the file at signing time. Any later change, including re-saving in another tool, breaks it. Make all edits first and sign last.

Next step

Signed documents often belong to a larger site: course certificates, member agreements, vendor contracts. Reign is the WordPress theme for building a complete community site: social network, courses, member directory, marketplace and job board on one install. See it running on the live demos, or read how a course community comes together in the course community build guide. New to the theme? Start with what Reign is.

Reading
11 min · 2,160 words
Published
Nov 29, 2024
wbcomteam
Reign contributor

Writing about WordPress communities, BuddyPress, BuddyBoss, LMS plugins, and the business of paid communities.

Keep reading

More from the Reign blog

Browse all posts on community, WordPress, BuddyPress and the studio of plugins behind Reign.

What customers say on Trustpilot

Swift and expert coding!

Swift and expert coding by Kerit to apply a personalised display adjustment on the Reign Theme for a media plugin that was not fully supported at the moment.

RussellGB