html2pdf Documentation

repository·master·Indexed 23 days ago

https://github.com/spipu/html2pdf

A PHP library for converting cleaned HTML 4.01 code into PDF documents, specifically designed for structured documents like invoices and technical documentation. It features custom tags for layout control (<page>, <page_header>, <page_footer>), support for 1D and 2D barcodes and QR codes, and the ability to generate automatic page indexes via bookmarks. Requires PHP 7.2 to 8.4 and the gd and mbstring extensions.

Tokens
13.2K
Snippets
28
Records
80
Agent score
82%

What's inside html2pdf

  1. Manage PDF layout using HTML tags

    master

    Html2Pdf uses specific HTML tags to manage page layouts, headers, and footers. When providing HTML to the writeHTML() method, you must not use <body> or <html> tags. Instead, use the <page> tag to define page boundaries and layout properties.

    To include complex headers and footers, nest <page_header> and <page_footer> tags immediately after the opening <page> tag.

     <page> 
        <page_header> 
           ...              
        </page_header> 
        <page_footer> 
           ...
        </page_footer> 
        ... 
     </page> 
  2. How extension and tag overriding works

    master

    Html2Pdf allows you to override existing functionality through name collisions:

    1. Extension Overriding: If you add an extension with a name that matches an already registered extension, the new extension will replace the previous one.
    2. Tag Overriding: If a tag name matches a tag name already provided by an existing extension, the new tag will replace the original one.
  3. Important usage constraints for HTML conversion

    master

    Html2Pdf is not a general-purpose web page scraper. To ensure successful conversion:

    • Use Clean HTML: You must write specific, cleaned HTML code designed for Html2Pdf.
    • Avoid WYSIWYG/Existing Pages: Do not attempt to convert existing web pages or HTML generated by WYSIWYG editors directly, as they often contain incompatible structures.
    • Use Specific Tags: The library implements specific tags designed to adapt HTML standards for PDF output. Use these specialized tags for optimal results.
  4. Implement a custom Security service

    master
    If the default security logic is insufficient for your requirements, you can implement your own security logic by implementing the SecurityInterface. Once implemented, you can inject your custom service into the Html2Pdf instance using setSecurityService().
  5. Use Html2Pdf specific HTML tags

    master

    Html2Pdf introduces several custom tags to control PDF layout and features:

    • <page>: Determines orientation, margins (left, right, top, bottom), background image, background color, size, position, and footer. Use the attribute pageset="old" to keep the header and footer from previous pages.
    • <page_header>: Defines the page header.
    • <page_footer>: Defines the page footer.
    • <nobreak>: Forces a section to stay on the same page. If the section cannot fit in the remaining space, a page break is triggered before it.
    • <barcode>: Inserts barcodes (supports all TCPDF barcode types).
    • <qrcode>: Inserts 2D QR codes.
    • <bookmark>: Inserts bookmarks into the PDF. Can also be used to automatically create an index at the end of the document.
    • <end_last_page end_height="30mm">: Used for managing the end of the document.
  6. Create and register an extension

    master

    To register new tags in Html2Pdf, you must wrap them in an extension. An extension must implement the \[Spipu\\Html2Pdf\\Extension\\ExtensionInterface\] interface.

    Implementation Requirements

    • getName(): Returns a unique name for the extension.
    • getTags(): Returns an array of tag objects that the extension provides.

    Registering the Extension

    Use the addExtension() method on your Html2Pdf instance to activate your new tags:

    $html2pdf->addExtension(new \Example\Html2Pdf\Extension\MyExtension());

    Core Extensions

    The following extensions are included by default:

    • \Spipu\\Html2Pdf\\Extension\\Core\\HtmlExtension (contains native tags)
    • \Spipu\\Html2Pdf\\Extension\\Core\\SvgExtension
    <?php
    /**
     * Extension Example
     */
    namespace Example\Html2Pdf\Extension;
    
    use \Spipu\\Html2Pdf\\Extension\\ExtensionInterface;
    
    /**
     * Class MyExtension
     */
    class MyExtension implements ExtensionInterface
    {
        /**
         * @var array
         */
        private $tagDefinitions = array();
    
        /**
         * {@inheritDoc}
         */
        public function getName()
        {
            return 'example_extension';
        }
    
        /**
         * {@inheritDoc}
         */
        public function getTags()
        {
            if (empty($this->tagDefinitions)) {
                $this->tagDefinitions = array(
                    new \Example\Html2Pdf\Tag\Example(),
                    new \Example\Html2Pdf\Tag\Other(),
                );
            }
    
            return $this->tagDefinitions;
        }
    }
  7. Install Html2Pdf via Composer

    master

    The recommended way to install Html2Pdf is using Composer. Run the following command in your project's root directory:

    composer require spipu/html2pdf

    Note: If you choose not to use Composer, you must manually clone the Html2pdf repository and all its dependencies, and manually manage the PSR-4 autoloading. This method is not recommended and is not supported by the maintainers.

  8. Handle missing images in Html2Pdf

    master

    By default, Html2Pdf throws an ImageException if an image cannot be read. You can disable this check using setTestIsImage(false). If disabled and an image is missing, Html2Pdf will render a 16x16 grey square instead of throwing an error.

    If you disable the existence test, you can provide a specific image to use as a replacement for missing files using setFallbackImage($imageFilename).

  9. Add an electronic signature to a PDF using the <cert> tag

    master

    You can embed an electronic signature into your PDF by using a custom HTML <cert> tag within your HTML source. This tag requires a certificate file and can optionally include a private key and metadata describing the signature (name, location, reason, and contact information). The content inside the <cert> tag (the part between the opening and closing tags) can be any HTML-formatted string, such as an image or text, which will be rendered as part of the signature block.

    <cert
        src="/path/to/cert.pem"
        privkey="/path/to/priv.pem"
        name="sender_name"
        location="sender_location"
        reason="sender_reason"
        contactinfo="sender_contact"
    >
        <!-- Content inside the tag can be any HTML, e.g., an image -->
        <img src="/path/to/signature_image.png" />
    </cert>
  10. Use `<page_header>` and `<page_footer>` for complex layouts

    master

    If you need more than a simple automatic footer, use the <page_header> and <page_footer> tags.

    Requirements:

    1. They must be placed immediately after the opening <page> tag.
    2. You must specify a top margin using the backtop attribute on the parent <page> tag to prevent the header from overlapping the content.

    These tags can contain any valid HTML and support css and class attributes.