PDF Writer
PdfWriter (includes/PdfWriter.php) is the one door for making and stamping PDFs. A feature hands it a description of a PDF, a recipe, and gets the finished bytes back. A recipe can start from somebody else's PDF, put pictures and text on its pages, add pages of its own, and ask for the result to be sealed so that any later change is detectable.
No feature touches a PDF library itself. Reading a PDF's text is DocumentText (Document Text).
Calls
PdfWriter::available(): array // ['ok', 'reason', 'sources', 'seal']
PdfWriter::normalize(string $pdf): array // ['status', 'bytes', 'warnings', 'detail']
PdfWriter::describe(string $pdf): array // ['status', 'pages' => [['width', 'height'], ...], 'warnings', 'detail']
PdfWriter::compose(array $recipe): array // ['status', 'bytes', 'pages', 'recipe_pages', 'warnings', 'seal', 'replaced', 'detail']None of them throws. status is one of:
| Status | Meaning |
|---|---|
ok | Done |
secured | The PDF needs a password to open |
too_large | Over a limit below |
failed | Damaged file, timeout, out of memory, or a refusal; detail says which |
unavailable | A piece is missing on this box; detail names it |
unavailable is decided from what is installed, before anything runs: the library, the fonts, the qpdf program, a parser-jail launcher that can hand qpdf a file, the sealing identity. available() reports the same: sources is whether an outside PDF can be taken, seal whether a result can be sealed. A recipe with no outside PDF and no seal needs neither.normalize()
The one treatment every outside PDF gets before anything else looks at it: a file its author locked against editing is unlocked, and form values and annotation appearances are baked into the page. Without it, a value typed into a fillable form is missing from the stamped copy.
A feature that shows a PDF to people and later stamps it stores the normalized copy once and uses it for both, so what was seen is what gets stamped. Normalizing a normalized file is harmless.
warnings tells the caller what was done to the file, because the caller may need to tell a person:
| Warning | Meaning |
|---|---|
restrictions_removed | The author's "no editing" restriction was removed. Tell the person who uploaded it. |
signature_removed | The file carried a digital signature, which rewriting it destroyed. |
characters_replaced | (compose()) A character no font here has was drawn as ?; replaced holds the characters. |
describe()
Normalizes, then returns each page's width and height in points, as displayed (rotation applied).
compose()
$result = PdfWriter::compose(array(
'source' => $pdf_bytes, // optional: an outside PDF to start from
'pages' => array( // optional; default is every source page in order
array('source' => 1),
array('blank' => array(612, 792)),
),
'images' => array('sig1' => $png_bytes), // PNG or JPEG
'marks' => array(
array('page' => 1, 'kind' => 'image', 'image' => 'sig1', 'x' => 72, 'y' => 650, 'w' => 150, 'h' => 50),
array('page' => 1, 'kind' => 'text', 'text' => 'Jane Example', 'x' => 72, 'y' => 715, 'size' => 10, 'color' => '#0000a0'),
array('page' => 2, 'kind' => 'html', 'html' => '<h2>Certificate</h2>...', 'x' => 72, 'y' => 72, 'w' => 468),
),
'title' => 'Service agreement',
'seal' => true,
'seal_reason' => 'Document completed',
));- Positions are in points from the top-left corner of the page as displayed.
pagenumbers the recipe's pages from 1. A page stored rotated comes out upright, at the sizedescribe()reported. - A text mark is one line; its
yis the baseline, and a tab or line break in it is a space.sizeis in points,coloris#rrggbb, andboldis a flag. - A
sourceis always normalized first, so its warnings appear in the result. - With no
source,pagesis required and every page is blank. htmlis the library's own HTML subset: headings, paragraphs, tables. It reads no file and no URL; an<img>draws nothing.- An HTML mark that does not fit continues on added pages of the same size, placed directly after its page; recipe pages after it move down. It starts at its
xandyand keeps itswthroughout.topis the space kept clear at the top of each added page andbottomthe space kept clear at the bottom of every page it touches, 36 points each unless given. The clear space belongs to the page: where a page's HTML marks give different values, the largest is used. - A page's HTML marks are drawn after its other marks, in the order listed, each starting on the recipe's own page. A second one that runs over continues on the pages the first added.
pagesin the answer is the finished file's pages, added ones included.recipe_pagesholds, for each page of the recipe in order, the number of the finished page it became. A mark'spageis always a recipe page.- Text is drawn in Helvetica when every character is in it and in DejaVu Sans otherwise. DejaVu Sans covers Latin, Greek and Cyrillic; it has no Chinese, Japanese or Korean. A character neither font has is drawn as
?, with the warning above. - With
seal, the result carries'seal' => ['fingerprint' => <SHA-256 of the certificate>].
PdfWriter: a source of 15 MB (MAX_SOURCE_BYTES), 500 pages (MAX_PAGES), images of 4 MB together (MAX_IMAGE_BYTES), 2,000 marks (MAX_MARKS). The finished PDF has a ceiling of about 23 MB, which is DocumentText::MAX_ANSWER_BYTES once it is base64. A limit that can be told from the recipe is too_large before anything is opened; the page count of a source, the pages an HTML mark adds and the size of the result are found while composing. Added pages count toward the 500.The seal
A sealed PDF carries a signature over every byte of the file (PAdES B-B). A PDF reader shows it as valid and its issuer as not trusted: the certificate is the site's own, not one a certificate authority issued. There is no trusted timestamp, so a seal reads as expired once its certificate's ten years are over. The seal shows that the file has not changed since this site wrote it, and nothing more.
PdfSeal (includes/PdfSeal.php) holds the identity:
- The certificate and its private key are one sealed setting,
pdf_seal_identity.update_databasemints it throughPdfSeal::provisionIdentity()and renews it there when under a year remains; no request mints one. It is a regenerable sealed secret: a value that cannot be opened on this site (a database copied from another) is cleared and minted again by the sealed-secret reconciler. - A mint never overwrites a value another process wrote first, and a renewal replaces exactly the value it judged.
- A new identity retires nothing. A sealed PDF carries its own certificate and still verifies as unchanged.
- Every certificate ever minted has a row in
psc_pdf_seal_certificates(PdfSealCertificate), public part only.PdfSeal::isOurs($fingerprint)answers whether a seal was this site's, before or after a renewal. - The certificate is named for the site's host when it was minted (
<host> document seal). The name is a label; the fingerprint is the identity. A site copied together with its secret key shares the identity with its original.
How it runs
Every step that opens an outside PDF or an outside image runs in the parser jail's subprocess (Document Text § The parser jail). The web worker parses nothing.
- Classify and normalize (only with a
source): two runs of theqpdfprogram throughDocumentText::runTool(), which hands it the PDF as a file.qpdf --requires-passwordanswers by exit code: 0 needs a password (secured), 3 is owner-restricted (restrictions_removed), 2 is a plain file. Thenqpdf --decrypt --generate-appearances --flatten-annotations=all. - Build:
DocumentText::parseWith('PdfComposer', …).PdfComposer(includes/PdfComposer.php) is aSandboxParserInterfaceclass and the only file that names the PDF library's document classes (tecnickcom/tc-lib-pdf). It imports the pages, draws the marks, and, for a seal, leaves room for the signature. It is given no key. - Seal (only when asked), in the caller's process:
PdfSeal::apply(). The subprocess answered the document with the signature's room closed up, and the byte range of the finished file. That answer came from a process that parsed a stranger's file, so the range is checked before anything is signed: four non-negative whole numbers, starting at the first byte, covering exactly the bytes answered, with room of an even size between 4 and 65,536 bytes. The signature is over every byte answered and is written into the room. No PDF is parsed in this step.
DocumentText::PARSER_EXTENSIONS and nothing else. The library's file package names twelve CURLOPT_* and CURLPROTO_* constants when it loads; PdfComposer defines them, and the curl extension is not loaded.Each stage frees what it replaced before the next starts, so a compose at every limit at once stays inside a web worker's 128 MB.
Fonts
The library ships no fonts. includes/pdf_fonts/ holds the definitions PdfComposer reads: the 14 standard PDF fonts (core/, metrics only) and DejaVu Sans regular and bold (dejavu/), each with its licence. PdfComposer::sandboxReads() names that folder, which is how the fenced subprocess is allowed to read it. Nothing writes there at run time.
maintenance_scripts/dev_tools/build_pdf_fonts.php regenerates the folder from the library's own build. Run it by hand when the library is upgraded, and commit what it writes.
Dependencies
tecnickcom/tc-lib-pdfincomposer.json. The lock file pins its 14 packages; upgrade it on purpose, then rebuild the fonts and run the tests.qpdf, a system package (composer.jsonextra.joinery-system-packages), installed at the platform's root moments.- The parser-jail launcher 2.2.0 or later for outside PDFs under the jail (
stdin-fileon its features line). A box with an older launcher answersunavailablefor a recipe with a source until the next root moment installs the current one; a recipe with no source composes meanwhile.
Tests
tests/unit/pdf_writer_test.php(safe tier): marks, fonts and replaced characters, HTML reading no file or URL, an HTML mark that runs past its page (the finished page list, the map from recipe pages, order, the page limit, a second mark on the same page, the clear space), the limits, the seal verified byopenssl, every refused byte range, the key staying out of the subprocess, the subprocess's extensions, typed form values, locked and password-protected files, an earlier signature, a rotated page, every limit at once in 128 MB, and the font folder left unchanged. Checks that start from an outside PDF are skipped whereqpdfis absent.tests/functional/pdf_seal_identity_test.php(test-db tier): the first mint, a mint and a renewal that lose a race, a value that cannot be opened, and old certificates staying known.tests/unit/document_text_test.phpcovers a handler's declared folders andrunTool()handing a program a file.tests/security/parser_surfaces_test.phppins where the library andqpdfmay be named.maintenance_scripts/install_tools/joinery_jail/holds the launcher's own tests for--stdin-file(go test).