English · Français

A PDF page describes what to paint. Its logical structure describes what the content means and in which order to read it. The optional pdftoolkit/pdf-to-html module uses that second description to derive HTML according to Deriving HTML from PDF 1.2, the PDF Association publication retained with its source code.

The PDFToolkit/pdf-to-html repository was created specifically to implement the rules in this reference document. Version 0.8.4 distinguishes executable rules, security decisions, browser adaptations and capabilities supplied by the application. The requirements ledger links the document's clauses to decisions and tests; the coverage guide describes accepted inputs and independent evidence.

This tutorial runs the real examples/01-derive-tagged-pdf.php example from the selected module release. The input PDF, every rendered page, actual HTML output, JSON diagnostics and complete PHP source appear below. The HTML is produced during the documentation build; it is not a handwritten substitute for a result.

Version 0.6.0 preserves native MathML layout instead of emitting automatic CSS display:inline or display:block on mathematical elements. Root block Placement uses math[display="block"]; explicit author CSS and MathML display retain their priority. The MathML coverage guide explains shared classes, attribute precedence and the independent browser checks.

Install the optional module

composer require "pdftoolkit/pdf:^0.12.4" "pdftoolkit/pdf-to-html:^0.8.4"

This installs the core and reader dependencies. Core-only applications acquire no HTML conversion dependency. PHP 8.3+ with DOM and mbstring is required.

For JPEG, JPEG 2000 and JBIG2 images, Reader selects a compatible native decoder, then the optional PHP library when installed:

composer require "pdftoolkit/pdf-codecs:^0.1"

The image guide explains PDF colour-space precedence, sample precision and opacity. Unsupported browser representations retain an explicit rendering diagnostic. The interactive gallery includes real JPEG, JPEG 2000 and JBIG2 inputs converted by PHP in the browser.

Supply the PDF and keep each processing step explicit

The executable example receives input and output paths:

php examples/01-derive-tagged-pdf.php tests/Fixtures/tagged.pdf _build/derived.html

The application reads the chosen file and supplies its bytes to DocumentReader. ReadPdfSource traverses the supported logical structure and content to build a TaggedDocument. It preserves the distinction between structure, Unicode text, properties and annotations rather than inferring a document from coordinates.

Derive the document and inspect diagnostics

HtmlDeriver resolves roles and namespaces, derives attributes and content, and serializes semantic HTML. The result exposes HTML, CSS, assets and diagnostics explicitly. The script writes the selected output and reports its operation in JSON. Applications choose storage and publication themselves.

The script also writes every returned asset beside the HTML, and reports each filename, media type and SHA-256. Keep those files with the HTML when copying a conversion. In application code, persist $result->assets explicitly or remap resource URLs consistently. Trusted scripts, when deliberately enabled, are external pdf-script-<sha256>.js assets; example 01 shown here exports none.

Read diagnostics before publishing. A source model capable of representing a mechanism does not imply that the file adapter accepts every font encoding, operator, filter or encryption mechanism found in external PDFs.

Understand the tested rules and choose a profile

Tests cover inverse ParentTree associations, namespaces, ActualText replacements, table header/cell relationships and the precedence of explicit HTML/CSS attributes. A Lbl nested inside a Form remains associated with the right field; the PDF-Page-X navigation identifier belongs to the parent of the content actually derived for that page. Pages with no retained content produce a diagnostic without being assigned another page's content.

The selected profile determines which capabilities to provide:

Need Explicit construction
Reuse headings, text, tables and images The default semantic profile and inspection of diagnostics.
Preserve a complete figure's appearance preferVisualFigures: true and a ContentRenderer backed by your application's engine.
Restore selected fields to their PDF default values FormActionPolicy(allowReset: true), without enabling PDF scripts.
Export embedded ECMAScript from a trusted document allowActiveContent: true, following the application's trust decision.

Strict reading rejects inconsistent inverse associations. Permissive reading reports them; it does not disable cycle checks or budgets. Encrypted PDFs require an explicit authentication capability, and the receiving HTML viewer must enforce verified permissions. The policies guide explains these objects and their responsibilities.

Authenticate an encrypted input explicitly

Version 0.3 uses the reader's native Standard-password operation when selected:

use PDF\Html\PdfToHtml;
use PDF\Reading\DocumentReader;
use PDF\Reading\FileBytes;
use PDF\Reading\Security\StandardPasswordAuthentication;
use PDF\Security\Saslprep;

$reader = new DocumentReader(authentication: new StandardPasswordAuthentication(
    (new Saslprep())->prepare($rawUtf8Password),
));
$result = (new PdfToHtml(reader: $reader))->convert(
    new FileBytes($pdfBytes),
    'protected.pdf',
);

Historical R=2–4 instead takes PdfDocEncodedPassword with explicitly encoded bytes. Wrong credentials fail; they do not trigger fallback authentication. The authenticated source's effective user/owner mask becomes data-pdf-perms and a diagnostic. The receiving viewer must enforce it; HTML attributes are not access control. Reusing a converter does not reuse a previous document's rights. Public-key authentication requires pdftoolkit/pdf-reader:^0.8.1. Inject PublicKeyAuthentication to select Adobe.PubSec source authentication explicitly. The HTML adapter propagates its effective recipient mask through the same permission contract; keys, CMS decryption and permission byte order remain application choices. Signature trust remains outside this operation. The authentication guide details the native path and the separate application-provider contract.

Require the original source MAC

Version 0.4 can require an ISO/TS 32004 MAC before tagged content is interpreted:

use PDF\Reading\Security\SourceIntegrityPolicy;

$converter = new PdfToHtml(
    reader: $reader,
    sourceIntegrity: SourceIntegrityPolicy::RequirePdfMac,
);
$result = $converter->convert(new FileBytes($pdfBytes), 'protected.pdf');

The converter preserves or strengthens the injected reader's requirement. Both native and provider paths must return the same authenticated source bytes, verified permissions and the required MAC status. A permissive converter default cannot weaken a reader that already requires integrity. The compatible default also accepts unprotected PDFs; RequirePdfMac rejects them, including files stripped of all integrity markers. Wrong credentials or a corrupt MAC do not trigger an unauthenticated fallback.

Example 04 uses the public native-user fixture credential explicitly and writes derived HTML/assets. That PDF MAC does not authenticate the new HTML: preserve ordinary HTML safety policy and usage permissions. The application still chooses its credential preparation and file I/O.

The AuthenticationProvider port changes in 0.4: authenticate() receives the effective SourceIntegrityPolicy as its third argument and returns a ReadDocument, replacing a directly supplied TaggedDocument. The converter checks original-source identity, permissions and required verification before the shared tagged adapter runs. A provider remains trusted application code; the port alone does not prove its cryptography or certificate trust. See the migration and MAC boundaries.

Export a figure and supply the rendering engine

Example 02 reads a tagged PDF, finds a Figure and passes its ContentGroup to GraphicPdfExporter:

php examples/02-export-figure.php tests/Fixtures/tagged.pdf figure.pdf

The exporter builds a real isolated one-page PDF in memory. It retains the resources, transformations, clipping and text advances the figure needs while omitting unselected painting operations. The CLI writes figure.pdf and reports its source page, dimensions in points and SHA-256. The rendering document contains no catalog actions, AcroForm or scripts from the source document.

A Form XObject can also be referenced directly by an OBJR, without a page Do call. Version 0.3.2 then retains its /BBox clipping in the Form's local coordinates, including a sheared matrix, and its transparency /Group. Its /Matrix is applied only once. An explicit viewport uses page coordinates; it does not receive the Form matrix a second time. The independent pixel oracle compares Poppler renderings to verify clipping and transparency, beyond the mere presence of these entries in the exported PDF.

To obtain an image in the HTML, supply an object implementing GraphicsRasterizer::rasterize(RenderingDocument): ImageContent. This object receives the isolated PDF and returns PNG, JPEG or GIF bytes produced by your engine:

use PDF\Html\DerivationPolicy;
use PDF\Html\HtmlDeriver;
use PDF\Html\PdfToHtml;
use PDF\Html\Rendering\RasterContentRenderer;
use PDF\Reading\FileBytes;

// $rasterizer is the application's explicit GraphicsRasterizer object.
$renderer = new RasterContentRenderer($rasterizer);
$converter = new PdfToHtml(deriver: new HtmlDeriver(
    policy: new DerivationPolicy(preferVisualFigures: true),
    renderer: $renderer,
));
$result = $converter->convert(new FileBytes($pdfBytes), 'chart.pdf');

RasterContentRenderer connects the exporter and that engine; it preserves the rendering viewport's logical dimensions independently of raster resolution. The requested visual profile fails explicitly when its engine is missing or declines the group. Applications choose installation, isolation and execution limits. See the graphics guide for retained GraphicProgram objects and Poppler pixel checks.

Reset a field group without executing PDF scripts

Example 03 constructs an object source model and produces a standalone HTML form:

php examples/03-safe-form-reset.php safe-form-reset.html

The Person.Name field starts with “Grace Hopper” as /V and has “Ada Lovelace” as /DV. The button selects the Person group:

use PDF\Html\Forms\FormActionPolicy;
use PDF\Html\Forms\ResetFormAction;

$resetAction = new ResetFormAction(['Person']);
$policy = new \PDF\Html\DerivationPolicy(
    formActions: new FormActionPolicy(allowReset: true),
);

In the complete script, this ResetFormAction object belongs to the button's field. Its selection includes Person.Name and other descendants of Person, without including Personality.Name. exclude: true reverses the selection; an explicitly empty list does not mean “all fields”. An absent /DV clears the value instead of restoring its initial /V.

This policy exports only the library-owned form runtime. PDF document, page and widget scripts remain disabled, and submissions remain disabled too. The example writes the returned JavaScript beside the HTML. Keep both to try the reset in your browser; this site's sandboxed preview executes no runtime.

Compare semantic output rather than page layout

Inspect headings, paragraphs and reading order in the HTML preview, then compare them with the PDF. Browser reflow and PDF pagination have different goals. The module does not infer missing structure, run OCR or promise pixel-identical output. The preview is sandboxed without permission to execute scripts or submit forms.

The fixture's red image contains one sample pixel but is painted at 20 PDF points on each side. The adapter follows its transformation matrix and derives 27 × 27 CSS pixels after rounding, using 96 CSS pixels per 72 PDF points. This preserves logical size without equating image samples with painted size or reproducing every PDF positioning/clipping operation.

The default profile exports no runtime and permits no remote resource loads. Enabling the library-owned reset behavior is separate from allowing PDF ECMAScript. The optional field/event bridge covers tested validation, calculation and page events; it does not implement the complete Acrobat/ISO 21757-1 API. The requirements ledger and coverage matrix link source classes, individual tests, HTML5/PDF oracles and Node runtime checks.

MathML fragments retain a checked vocabulary of 192 element names, including Presentation and Content MathML. Preserved Content/elementary markup does not guarantee native browser rendering; extended vocabulary produces a diagnostic, and the package supplies no rendering polyfill or mathematical evaluator.

See the module architecture, coverage and security guide for the model/file/runtime boundaries. Semantic HTML does not automatically certify accessibility or PDF/UA.

Explain the original PDF signature explicitly

The signature guide explains the source-bound SignatureValidationProvider port and its SignatureOutputValidation adapter. Example 05 requires three explicit paths and accepts one DER or PEM certificate:

php examples/05-verify-pdf-signature.php signed.pdf signer.der _build/signed.html

It checks mathematical integrity against that selected certificate, exact physical Contents provenance and the complete signed revision. The native status popover explains the result without enabling PDF JavaScript. integrity-verified is separate from certificate trust, revocation and permission for later changes. The generated HTML is not signed. Choose a fuller application provider when your validation policy requires those additional decisions.

View the input PDF

This tagged PDF is the conversion input. The HTML result is produced by the script run during the site build; its preview preserves semantic structure rather than the PDF layout.

Input PDF derive-html: page 1 of 1
Page 1 of 1
Use the browser PDF viewer

This viewer depends on your browser. If the document does not appear, use “Open the PDF” or “Download”.

Reader output

Actual script output from reading the input PDF while building this documentation. Download the console output.

{
    "input": "derive-html.pdf",
    "html": "derive-html.html",
    "htmlSha256": "05ce206b7c078c22686a07b26d2dd88da792318a045b2862c2a7208c747ff19b",
    "cssBytes": 1499,
    "assets": [
        {
            "filename": "image-b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640.png",
            "mediaType": "image\/png",
            "sha256": "b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640"
        }
    ],
    "diagnostics": [
        {
            "code": "scripts-disabled",
            "message": "PDF ECMAScript was not derived in the safe profile; use an explicitly trusted active-content profile for section 4.5 and Annex B.",
            "source": null
        },
        {
            "code": "associated-css-blocked",
            "message": "Associated stylesheets require the embedded-stylesheet or active-content policy.",
            "source": "theme.css"
        }
    ]
}

HTML result

Actual derivation output, isolated in a frame without permission to run scripts, submit forms or navigate the parent page.

Download the HTML

Read the HTML source
<!DOCTYPE html>
<html lang="fr-FR"><head><title>Independent tagged source</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>.lead:where(:not([data-pdf-math-layout])){display:block}.lead{margin-bottom:10.666667px}:where(button[data-pdf-widget-style="71592f9072f05eb6c457a501c23210600dfcfc9ce51a463804a3df448518a31b"]){appearance:none;background-color:ButtonFace;border:2px outset ButtonBorder}:where(input[data-pdf-widget-style="71592f9072f05eb6c457a501c23210600dfcfc9ce51a463804a3df448518a31b"][type="checkbox"],input[data-pdf-widget-style="71592f9072f05eb6c457a501c23210600dfcfc9ce51a463804a3df448518a31b"][type="radio"]){appearance:none;box-sizing:border-box;width:1em;height:1em;border:2px solid currentColor;padding:2px;vertical-align:middle;background-clip:content-box}:where(input[data-pdf-widget-style="71592f9072f05eb6c457a501c23210600dfcfc9ce51a463804a3df448518a31b"][type="radio"]){border-radius:50%}:where(input[data-pdf-widget-style="71592f9072f05eb6c457a501c23210600dfcfc9ce51a463804a3df448518a31b"][type="checkbox"]:checked,input[data-pdf-widget-style="71592f9072f05eb6c457a501c23210600dfcfc9ce51a463804a3df448518a31b"][type="radio"]:checked){background-image:linear-gradient(currentColor,currentColor)}:where(input[data-pdf-widget-style="71592f9072f05eb6c457a501c23210600dfcfc9ce51a463804a3df448518a31b"][type="checkbox"]:indeterminate){background-image:linear-gradient(currentColor,currentColor);background-size:100% 25%;background-repeat:no-repeat;background-position:center}:where([data-pdf-widget-style="71592f9072f05eb6c457a501c23210600dfcfc9ce51a463804a3df448518a31b"]:active){filter:invert(1)}</style></head><body><nav hidden="" id="PDF-PageNavigation" role="doc-pagelist"><a href="#PDF-Page-1">Intro-i</a></nav><form name="acroform" id="acroform_id"></form><div id="pdf-se-1" data-pdf-se-type="Document" data-pdf-se-type-original="Document"><h1 id="heading" data-pdf-se-type="H1" data-pdf-se-type-original="CustomHeading"><span id="PDF-Page-1"><span role="doc-pagebreak" aria-label="Intro-i"></span>External tagged PDF</span></h1><p id="pdf-se-2" data-pdf-se-type="P" data-pdf-se-type-original="StyledP" class="lead" style="margin-bottom:10.666667px;display:block;text-align:center"><span lang="fr">Texte remplaçant</span></p><p id="pdf-se-3" data-pdf-se-type="P" data-pdf-se-type-original="P">éABCfi</p><figure id="pdf-se-4" data-pdf-se-type="Figure" data-pdf-se-type-original="Figure"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" width="27" height="27" alt="A red pixel"></figure><a id="pdf-se-5" data-pdf-se-type="Link" data-pdf-se-type-original="Link" href="#PDF-Page-1">Read more</a><input id="pdf-se-6" name="Person.Name" form="acroform_id" type="text" value="Ada" maxlength="50" spellcheck="true" required="" data-pdf-highlight="I" data-pdf-widget-style="71592f9072f05eb6c457a501c23210600dfcfc9ce51a463804a3df448518a31b" data-pdf-se-type="Form" data-pdf-se-type-original="Form"></div></body></html>

Complete source code

Code from pdftoolkit/pdf-to-html · View the source at the documented commit ↗ · Input PDF source ↗

Read the commented script: 01-derive-tagged-pdf.php
<?php

declare(strict_types=1);

require dirname(__DIR__) . '/vendor/autoload.php';

use PDF\Html\PdfToHtml;
use PDF\Reading\FileBytes;
use PDF\Reading\ReaderLimits;

// File access belongs to this application, not to the library's source objects.
$input = $argv[1] ?? dirname(__DIR__) . '/tests/Fixtures/tagged.pdf';
$output = $argv[2] ?? dirname(__DIR__) . '/_build/derived.html';
if (!stream_is_local($input) || !is_file($input)) {
    throw new RuntimeException('The input must identify an existing local PDF file.');
}
$stream = fopen($input, 'rb');
if ($stream === false) {
    throw new RuntimeException('The input PDF could not be opened.');
}
try {
    $maximum = (new ReaderLimits())->maxFileBytes;
    $bytes = stream_get_contents($stream, $maximum + 1);
} finally {
    fclose($stream);
}
if ($bytes === false || strlen($bytes) > $maximum) {
    throw new RuntimeException('The input PDF exceeds the configured file limit.');
}

// Parsing, interpretation and derivation are separate injectable objects.
// The default profile performs no network access and emits no active scripts.
$result = (new PdfToHtml())->convert(new FileBytes($bytes), basename($input));
$directory = dirname($output);
if (!is_dir($directory) && !mkdir($directory, 0777, true) && !is_dir($directory)) {
    throw new RuntimeException('The output directory could not be created.');
}
if (file_put_contents($output, $result->html) === false) {
    throw new RuntimeException('The derived HTML could not be written.');
}
foreach ($result->assets as $asset) {
    if (file_put_contents($directory . '/' . $asset->filename, $asset->bytes) === false) {
        throw new RuntimeException('A derived asset could not be written.');
    }
}

echo json_encode([
    'input' => basename($input),
    'html' => basename($output),
    'htmlSha256' => hash('sha256', $result->html),
    'cssBytes' => strlen($result->css),
    'assets' => array_map(static fn ($asset): array => ['filename' => $asset->filename, 'mediaType' => $asset->mediaType, 'sha256' => hash('sha256', $asset->bytes)], $result->assets),
    'diagnostics' => $result->diagnostics,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";

Guide source at the documented commit ↗