Package com.pd4ml

Class PD4ML


  • public class PD4ML
    extends java.lang.Object
    The main entry point of PD4ML: converts HTML/CSS documents to PDF, PDF/A, PDF/UA, RTF, DOCX or page images.

    A conversion has three steps:

    1. Create an instance and configure it: page size and margins, HTML width, fonts, headers and footers, security, extra stylesheets and so on. Most configuration methods must be called before the document is read; the ones that cannot be called later throw InvokeException.
    2. Read and parse the source document with one of the readHTML(...) methods.
    3. Lay out the document and write the result with writePDF(OutputStream), writeRTF(OutputStream, boolean), writeDOCX(OutputStream) or one of the renderAsImages(...) methods.
    
     PD4ML pd4ml = new PD4ML();
     pd4ml.setPageSize(PageSize.A4);
     pd4ml.setPageMargins(new PageMargins(20, 10, 20, 10, Dimensions.Units.MM));
     pd4ml.setHtmlWidth(1000);
     pd4ml.readHTML(new URL("file:/path/to/document.html"));
     try (OutputStream os = new FileOutputStream("document.pdf")) {
         pd4ml.writePDF(os);
     }
     
    An instance converts exactly one document: readHTML(...) can be called only once per instance. Instances are not thread-safe; use a separate instance per thread or per conversion. Without a valid license the converter runs in demo mode and watermarks its output (see applyLicense(String)).

    Page scopes

    Several methods take a scope argument that selects the pages a setting applies to. A scope is a comma-separated list of the following items; null means all pages ("1+"):
    • 3 - a single page (pages are numbered from 1);
    • 2-5 - a range of pages;
    • 2+ - a page and all pages after it;
    • odd, even - restricts the selection to odd or even pages;
    • skiplast - excludes the last page.
    For example, "2+,even" selects the even pages starting from page 2, and "odd" selects all odd pages.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static boolean disableBatik
      Global switch, false by default.
      static boolean disableMathML
      Global switch, false by default.
    • Constructor Summary

      Constructors 
      Constructor Description
      PD4ML()
      Creates a converter instance with logging disabled.
      PD4ML​(int loglevel)
      Creates a converter instance with the given log level.
      PD4ML​(java.lang.String license)
      Creates a converter instance with the given license and logging disabled.
      PD4ML​(java.lang.String license, int loglevel)
      Creates a converter instance with the given license and log level.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void addCustomResourceProvider​(java.lang.String customProviderClassName)
      Adds a custom resource loader, for example to load resources over a proprietary protocol or from a database.
      void addCustomTagHandler​(java.lang.String customTagName, CustomTag implementation)
      Registers a handler that renders a custom HTML tag, for example <chart>...</chart>.
      void addDocumentActionHandler​(java.lang.String actionType, java.lang.String javaScript)
      Adds JavaScript that the PDF viewer runs on a document event.
      void addMetadata​(java.lang.String key, java.lang.String value, boolean hide)
      Adds a custom property to the XMP metadata of the resulting PDF, for example a document ID for a document management system.
      void addStyle​(java.lang.String stylesheet, boolean overrideDocumentStyles)
      Applies additional CSS rules to the document.
      void addStyle​(java.net.URL stylesheet, boolean overrideDocumentStyles)
      Applies an additional CSS stylesheet, loaded from a URL, to the document.
      void adjustHtmlWidth​(boolean adjust)
      Fits the HTML width to the actual width of the content.
      void applyKerning​(boolean enable)
      Applies the kerning information of TrueType/OpenType fonts, which adjusts the spacing of specific character pairs (such as "AV") for more even-looking text.
      boolean applyLicense​(java.lang.String license)
      Applies a license to this instance, replacing the one applied before.
      void asyncResourceLoader​(int threadPoolSize)
      Loads external resources (images, attachments and so on) in parallel, which can speed up documents that reference many remote resources.
      java.lang.String dump​(int mode)
      Returns a text dump of internal structures, for diagnostics and support requests.
      void embedTTFs​(boolean embed, boolean allGlyphs)
      Controls how TrueType/OpenType fonts are stored in the resulting PDF.
      void enableHyperlinks​(boolean enable)
      Controls whether HTML links become clickable links in the resulting PDF.
      void enableLigatures​(boolean enable)
      Enables OpenType text shaping with TrueType/OpenType fonts: glyph substitution (GSUB tables) for ligatures such as "fi" and "fl", and the compound glyphs that complex scripts such as Devanagari need for correct rendering.
      void fitPageVertically​(int align)
      Scales the whole document down so that it fits on a single page vertically, including the page header and footer.
      void generateBookmarksFromAnchors​(boolean enable)
      Generates the PDF bookmarks (outline) from named anchors, that is from <a name="destination">Label</a> tags.
      void generateBookmarksFromHeadings​(boolean enable)
      Generates the PDF bookmarks (outline) from the document headings: each <h1> to <h6> becomes a bookmark, nested by heading level.
      void generateForms​(boolean enable, java.lang.String useTtfFont)
      Converts HTML form controls (<input>, <textarea>, <select>) to interactive PDF form fields (AcroForm) instead of static images of them.
      void generateForms​(boolean enable, java.lang.String useTtfFont, java.lang.String formFontCharRange)
      Converts HTML form controls to interactive PDF form fields, like generateForms(boolean, String), and embeds the glyphs for the characters users may type into the fields.
      void generateMulticolumn​(int columns, int span, boolean millimeters)
      Intended to lay out the document in several columns per page.
      java.lang.Object getCache()
      Returns the font and resource cache of this instance, so later conversions can reuse it with setCache(Object) instead of loading the same fonts and resources again.
      java.lang.String getDocumentTitle()
      Returns the document title: the one set with setDocumentTitle(String), or else the <title> of the HTML document.
      short getFitPageVertically()
      Returns the alignment set by fitPageVertically(int).
      int getHeight​(int width)
      Calculates the height of the whole document laid out at the given width, ignoring page breaks.
      java.lang.Object getLastRenderInfo​(java.lang.String key)
      Returns information about the last conversion, after a write... or renderAsImages(...) call.
      PageMargins getPageMargins​(int pageNum, boolean imageGeneration)
      Returns the margins of a page, as determined by the defaults, setPageMargins(...) calls and, after readHTML(...), CSS @page rules of the document.
      PageSize getPageSize​(int pageNum)
      Returns the size of a page, as determined by the default page size, setPageSize(...) calls and, after readHTML(...), CSS @page rules of the document.
      static java.lang.String getVersion()
      Returns the version of the PD4ML library.
      static java.util.Date getVersionBuildDate()
      Returns the build date of the PD4ML library.
      void injectHtml​(java.lang.String htmlSnippet, boolean prependBodyContent)
      Inserts HTML code into the document body without changing the document source.
      boolean isDemoMode()
      Tells whether the converter runs in demo mode, that is, without a valid license.
      boolean isPro()
      Tells whether the applied license enables Pro features, such as TTF font embedding (useTTF(String)), PDF forms, addStyle(String, boolean) and merge(PdfDocument, int, int, boolean).
      void merge​(PdfDocument pdf, int fromPage, int toPage, boolean append)
      Combines the PDF produced by the next writePDF(OutputStream) call with pages of an existing PDF document.
      void monitorProgressWith​(ProgressListener listener)
      Registers a listener that is notified about the progress of the conversion, for example to show a progress bar.
      void outputRange​(java.lang.String description)
      Limits the output to the selected pages.
      void overrideDocumentEncoding​(java.lang.String encoding)
      Forces the encoding of the HTML document, overriding the encoding reported by the server, the byte order mark and <meta> charset declarations.
      static int predictPageHeight​(PageMargins pageMargins, PageSize pageSize, int userSpace)
      Calculates how many HTML pixels of content fit on one page for the given settings: the printable page height (page height minus top and bottom margins) divided by the scale factor from predictScale(PageMargins, PageSize, int).
      static float predictScale​(PageMargins pageMargins, PageSize pageSize, int userSpace)
      Calculates the scale factor from HTML pixels to PDF points for the given settings: the printable page width (page width minus left and right margins) divided by the HTML width.
      void protectPhysicalUnitDimensions​(boolean keepPhysicalUnitDimensions)
      Keeps sizes given in physical units (in, cm, mm, pt, pc) at their exact physical size in the PDF, regardless of the HTML width.
      void readHTML​(java.io.InputStream isr)
      Reads and parses an HTML document from a stream.
      void readHTML​(java.io.InputStream isr, java.net.URL base)
      Reads and parses an HTML document from a stream, decoding it with the platform default encoding (the file.encoding system property).
      void readHTML​(java.io.InputStream isr, java.net.URL base, java.lang.String encoding)
      Reads and parses an HTML document from a stream, with an explicit encoding.
      void readHTML​(java.net.URL url)
      Loads and parses an HTML document from a URL (file:, http:, https:, java: for classpath resources, or a protocol handled by a custom resource provider).
      void readHTML​(java.net.URL url, java.lang.String encoding)
      Loads and parses an HTML document from a URL, with an explicit encoding.
      java.awt.image.BufferedImage[] renderAsImages()
      Lays out the document and draws each page as an image in memory, for example to display or post-process the pages.
      java.io.File renderAsImages​(java.io.File dir, java.lang.String fileNamePrefix, java.lang.String format)
      Lays out the document and writes each page as a PNG image file.
      byte[][] renderAsImages​(java.lang.String format)
      Lays out the document and encodes each page as an image in memory.
      void setAuthorName​(java.lang.String name)
      Sets the author stored in the document properties (metadata) of the output.
      void setCache​(java.lang.Object fontCache)
      Makes this instance reuse the font and resource cache of an earlier conversion.
      void setCookie​(java.lang.String name, java.lang.String value)
      Adds a cookie to every HTTP request PD4ML makes to load the document and its resources, for example to pass an authentication or session cookie.
      void setDocumentTitle​(java.lang.String title)
      Sets the title stored in the document properties (metadata) of the output, overriding the <title> of the HTML document.
      void setDynamicData​(java.util.Map<java.lang.String,​java.lang.String> map)
      Sets values for $[key] placeholders in the document, so the HTML can be used as a template.
      void setErrorPolicy​(Constants.ErrorPolicy policy)
      Sets how strictly problems found during conversion are treated.
      void setHtmlWidth​(int width)
      Sets the width, in pixels, of the virtual browser window the document is laid out in.
      void setHttpOptions​(java.lang.String proxy, java.lang.String basicAuthentication)
      Sets the proxy and the credentials for HTTP requests PD4ML makes to load the document and its resources.
      void setInitialPageNumber​(int initialPageNumber)
      Sets the number of the first page, for example when the output is going to be appended to another document.
      void setLogLevel​(int level)
      Sets which log and diagnostic messages are written to the console.
      void setPageBackground​(java.lang.String htmlCode)
      Sets HTML content to draw under the page content of every page, for example a letterhead or a page frame.
      void setPageBackground​(java.lang.String htmlCode, java.lang.String scope)
      Sets HTML content to draw under the page content of the selected pages.
      void setPageFooter​(java.lang.String htmlCode, int heightPx)
      Sets an HTML page footer for all pages.
      void setPageFooter​(java.lang.String htmlCode, int heightPx, java.lang.String scope)
      Sets an HTML page footer for the selected pages.
      void setPageHeader​(java.lang.String htmlCode, int heightPx)
      Sets an HTML page header for all pages.
      void setPageHeader​(java.lang.String htmlCode, int heightPx, java.lang.String scope)
      Sets an HTML page header for the selected pages.
      void setPageMargins​(PageMargins margins)
      Sets the page margins for all pages.
      void setPageMargins​(PageMargins margins, java.lang.String scope)
      Sets the page margins for the selected pages.
      void setPageSize​(PageSize d)
      Sets the page size for all pages.
      void setPageSize​(PageSize d, java.lang.String scope)
      Sets the page size for the selected pages.
      void setParam​(java.lang.String key, java.lang.String value)
      Sets an advanced conversion parameter.
      void setPermissions​(java.lang.String password, int permissions)
      Encrypts the resulting PDF with 128-bit AES and restricts what users may do with it.
      void setPermissions​(java.lang.String password, int permissions, int encryptionMethod)
      Encrypts the resulting PDF with the given algorithm and restricts what users may do with it.
      void setRenderingHints​(java.util.Map hints)
      Sets the Java2D rendering hints used to draw pages in image output (renderAsImages(...)), for example to enable antialiasing or to trade quality for speed.
      void setSessionID​(java.lang.String sessionID)
      Sets the web application session ID to send with resource requests, so resources that require the user's session (stylesheets, images and so on) can be loaded.
      void setWatermark​(java.lang.String htmlCode, float left, float top, float opacity, float angle, float scale, boolean screen, boolean print, java.lang.String scope)
      Adds a watermark: HTML content drawn over the page content of the selected pages.
      void terminate()
      Requests termination of a running conversion and clears the font cache.
      void testTermination()
      Checks whether terminate() has been called, and aborts the conversion if so.
      static float translateToPt​(float mm)
      Converts millimeters to points (1/72 inch) at Constants.TRANSLATE_FACTOR points per millimeter.
      void useHttpRequest​(java.lang.Object httpRequest, java.lang.Object httpResponse)
      Passes the current servlet request and response to PD4ML, for conversions running inside a web application.
      void useTTF​(java.lang.String pathToFontDirs)
      Registers a directory of TrueType/OpenType fonts to use in the output.
      void useTTF​(java.lang.String pathToFontDirs, boolean generateFontMappingFileIfMissing)
      Registers a font directory like useTTF(String), and optionally creates its pd4fonts.properties mapping file.
      void useTTF​(java.lang.String pathToFontDirs, java.lang.String fontFileNameFilter)
      Registers only the fonts of a directory whose names match a filter.
      void writeDOCX​(java.io.OutputStream os)
      Lays out the document read by readHTML(...) and writes it as a Microsoft Word (DOCX) document.
      void writePDF​(java.io.OutputStream os)
      Lays out the document read by readHTML(...) and writes it as a PDF 1.7 document.
      void writePDF​(java.io.OutputStream os, PdfSpec pdfFormat)
      Lays out the document and writes it as a PDF that conforms to the given PDF version and, optionally, to PDF/A, PDF/UA, ZUGFeRD or Factur-X.
      void writePDF​(java.io.OutputStream os, java.lang.String pdfFormat)
      Lays out the document and writes it as a regular PDF, a PDF/A or a PDF/UA document.
      void writeRTF​(java.io.OutputStream os, boolean convertImagesToWMF)
      Lays out the document read by readHTML(...) and writes it as an RTF document.
      • Methods inherited from class java.lang.Object

        equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • disableBatik

        public static boolean disableBatik
        Global switch, false by default. When set to true, the Apache Batik based SVG plugin is not used, even if Batik is on the classpath. Affects all PD4ML instances in the JVM.
      • disableMathML

        public static boolean disableMathML
        Global switch, false by default. When set to true, the MathML plugin is not used, even if its dependencies are on the classpath. Affects all PD4ML instances in the JVM.

        The MathML plugin needs JEuclid (de.rototor.jeuclid:jeuclid-core) and its runtime dependency Apache Commons Logging (commons-logging:commons-logging) on the classpath. Maven and Gradle builds get both through PD4ML's dependencies; when the jars are deployed by hand, both must be added.

    • Constructor Detail

      • PD4ML

        public PD4ML()
        Creates a converter instance with logging disabled.

        The license is looked up automatically: first as a pd4ml.lic file in the current working directory, then as a pd4ml.lic resource in the classpath. If neither is found, the converter runs in demo mode.

        See Also:
        PD4ML(String, int)
      • PD4ML

        public PD4ML​(java.lang.String license,
                     int loglevel)
        Creates a converter instance with the given license and log level.
        Parameters:
        license - the license, either as the license string itself or as the location of a license file: a file path, a file:, http: or https: URL, or a java: URL to load it from the classpath. An empty string looks for pd4ml.lic in the current working directory and then in the classpath. null skips the license lookup, so the converter runs in demo mode.
        loglevel - the log output to enable: 0 disables logging, otherwise a bitmask of the LOG_* constants inherited by Constants, for example Constants.LOG_VERBOSE. Log messages are written to the console.
        See Also:
        applyLicense(String), setLogLevel(int)
      • PD4ML

        public PD4ML​(int loglevel)
        Creates a converter instance with the given log level. The license is looked up as described in PD4ML().
        Parameters:
        loglevel - the log output to enable: 0 disables logging, otherwise a bitmask of the LOG_* constants inherited by Constants, for example Constants.LOG_VERBOSE
        See Also:
        PD4ML(String, int)
      • PD4ML

        public PD4ML​(java.lang.String license)
        Creates a converter instance with the given license and logging disabled.
        Parameters:
        license - the license string or the location of a license file; see PD4ML(String, int) for the accepted forms
        See Also:
        applyLicense(String)
    • Method Detail

      • applyLicense

        public final boolean applyLicense​(java.lang.String license)
        Applies a license to this instance, replacing the one applied before. Call it before readHTML(...). The constructors call it implicitly.

        The output depends on the license:

        • no valid license (demo mode): every page is watermarked with "PD4ML DEMO MODE";
        • evaluation license: the pages carry a lighter "PD4ML EVALUATION MODE" watermark;
        • commercial license: no watermark in the output formats the license covers. Output in a format the license does not cover (for example PDF/A, RTF/DOCX or images) is still produced, but a StatusMessage error is recorded and can be read with getLastRenderInfo(String). PDF/A and PDF/UA output without a matching license is also watermarked with "PD4ML PDF/A EVALUATION MODE".
        Features marked "Pro" in this documentation require a license that enables Pro features (see isPro()).
        Parameters:
        license - the license string, or the location of a license file (a file path, or a file:, http:, https: or java: URL). If the string is not a valid license, it is tried as a location.
        Returns:
        true if the license is valid
        See Also:
        isDemoMode()
      • isDemoMode

        public final boolean isDemoMode()
        Tells whether the converter runs in demo mode, that is, without a valid license. In demo mode the output is watermarked.
        Returns:
        true if no valid license has been applied
        Since:
        v1.1.0
        See Also:
        applyLicense(String)
      • getVersion

        public static java.lang.String getVersion()
        Returns the version of the PD4ML library. For snapshot builds the "SNAPSHOT" suffix is replaced with the build timestamp.
        Returns:
        the version string
        See Also:
        getVersionBuildDate()
      • getVersionBuildDate

        public static java.util.Date getVersionBuildDate()
        Returns the build date of the PD4ML library.
        Returns:
        the build date, or null if it is not available (for example in a library built without resource filtering)
        See Also:
        getVersion()
      • merge

        public void merge​(PdfDocument pdf,
                          int fromPage,
                          int toPage,
                          boolean append)
        Combines the PDF produced by the next writePDF(OutputStream) call with pages of an existing PDF document. Pro feature.

        The page numbers of the conversion result take the merged pages into account: if the existing pages come first, numbering of the converted pages continues after them. Document properties (title, author, subject, keywords) not set for the conversion are taken from the existing document. Encryption set with setPermissions(String, int) is applied to the merged result. Only PDF output is affected.

        Parameters:
        pdf - the existing PDF document
        fromPage - the first page of the existing document to include (1-based)
        toPage - the last page of the existing document to include, or -1 for all pages up to the last one
        append - true to put the existing pages after the conversion result, false to put them before it
      • terminate

        public void terminate()
        Requests termination of a running conversion and clears the font cache. Call it from another thread, for example to cancel a conversion that takes too long. The conversion thread stops at its next check point with a ForcedTerminationException. A termination request is reset when readHTML(...) starts.
        See Also:
        testTermination()
      • readHTML

        public void readHTML​(java.io.InputStream isr)
                      throws InvokeException,
                             java.io.IOException
        Reads and parses an HTML document from a stream. Relative references to images, stylesheets and other resources are resolved against the current working directory, unless the document defines <base href="...">.

        The encoding is detected from the byte order mark; without one, UTF-8 is assumed. A <meta> charset declaration in the document overrides that, provided the stream supports mark/reset (for example a BufferedInputStream or a ByteArrayInputStream), so the parser can restart with the declared encoding.

        Call the configuration methods before this one; it can be called only once per instance.

        Parameters:
        isr - the HTML document stream
        Throws:
        InvokeException - if the stream is null, or the method has already been called for this instance
        java.io.IOException - if the document cannot be read
        See Also:
        readHTML(InputStream, URL, String)
      • readHTML

        public void readHTML​(java.io.InputStream isr,
                             java.net.URL base)
                      throws InvokeException,
                             java.io.IOException
        Reads and parses an HTML document from a stream, decoding it with the platform default encoding (the file.encoding system property). <meta> charset declarations in the document are ignored. To detect the encoding from the document instead, use readHTML(InputStream, URL, String) with a null encoding.
        Parameters:
        isr - the HTML document stream
        base - the base URL to resolve relative references to images, stylesheets and other resources against, for example new URL("file:/path/to/document/dir/"). A <base href="..."> tag in the document overrides it.
        Throws:
        InvokeException - if the stream is null, or the method has already been called for this instance
        java.io.IOException - if the document cannot be read
      • readHTML

        public void readHTML​(java.io.InputStream isr,
                             java.net.URL base,
                             java.lang.String encoding)
                      throws InvokeException,
                             java.io.IOException
        Reads and parses an HTML document from a stream, with an explicit encoding.
        Parameters:
        isr - the HTML document stream
        base - the base URL to resolve relative references to images, stylesheets and other resources against, or null for the current working directory. A <base href="..."> tag in the document overrides it.
        encoding - the Java name of the document encoding, for example "UTF-8" or "Cp1252". The given encoding takes precedence over <meta> charset declarations. "default" selects the platform default encoding. null detects the encoding as described in readHTML(InputStream).
        Throws:
        InvokeException - if the stream is null, or the method has already been called for this instance
        java.io.IOException - if the document cannot be read
      • readHTML

        public void readHTML​(java.net.URL url)
                      throws InvokeException,
                             java.io.IOException
        Loads and parses an HTML document from a URL (file:, http:, https:, java: for classpath resources, or a protocol handled by a custom resource provider). Relative references in the document are resolved against the URL; if the server redirects, against the final location.

        The encoding is taken from the HTTP response, the byte order mark or a <meta> charset declaration; see overrideDocumentEncoding(String) to force one. Call the configuration methods before this one; it can be called only once per instance.

        Parameters:
        url - the document location
        Throws:
        InvokeException - if the URL is null, or the method has already been called for this instance
        java.io.IOException - if the document cannot be loaded
      • readHTML

        public void readHTML​(java.net.URL url,
                             java.lang.String encoding)
                      throws java.net.MalformedURLException,
                             InvokeException,
                             java.io.IOException
        Loads and parses an HTML document from a URL, with an explicit encoding.
        Parameters:
        url - the document location; see readHTML(URL)
        encoding - the Java name of the document encoding, which takes precedence over the detected one and over <meta> charset declarations. "default" selects the platform default encoding; null detects the encoding as described in readHTML(URL).
        Throws:
        java.net.MalformedURLException - if the URL is malformed
        InvokeException - if the URL is null, or the method has already been called for this instance
        java.io.IOException - if the document cannot be loaded
      • setLogLevel

        public void setLogLevel​(int level)
        Sets which log and diagnostic messages are written to the console. Call it before readHTML(...) to cover the whole conversion.
        Parameters:
        level - 0 to disable logging, otherwise a bitmask of the LOG_* constants inherited by Constants: for example Constants.LOG_MINIMAL (errors only), Constants.LOG_VERBOSE (errors, warnings and info), or a combination such as Constants.LOG_ERROR | Constants.LOG_FONTS
      • setErrorPolicy

        public void setErrorPolicy​(Constants.ErrorPolicy policy)
        Sets how strictly problems found during conversion are treated. Under a stricter policy more problems abort the conversion with an IOException instead of being logged and worked around:
        Parameters:
        policy - the error handling policy; must be set before readHTML(...) to apply to parsing and resource loading
      • useTTF

        public void useTTF​(java.lang.String pathToFontDirs)
                    throws java.io.FileNotFoundException
        Registers a directory of TrueType/OpenType fonts to use in the output. Pro feature. Fonts used by the document are embedded in the resulting PDF (see embedTTFs(boolean, boolean)). The method can be called several times to register several directories.

        The directory must contain a pd4fonts.properties file that maps font family names to font files, one record per line:

         font_name=file_name
         
        where font_name is the family name as used in the HTML/CSS source, and file_name is the name of a font file in the same directory. Spaces in the font name must be escaped, for example:
         Book\ Antiqua=BKANT.TTF
         
        The file can be generated with the command line java -jar pd4ml.jar -configure.fonts <fontdir>, or by useTTF(String, boolean). Before you distribute it, remove the fonts you are not licensed to redistribute; ask your font vendor if in doubt.

        To load fonts from the classpath, for example from a JAR in a Java EE deployment, use the PD4ML-specific java: protocol:

        • useTTF("java:myfonts") looks for a /myfonts folder with pd4fonts.properties and the font files in the classpath;
        • useTTF("java:") looks for pd4fonts.properties and the font files in the classpath root.
        Parameters:
        pathToFontDirs - a font directory path, a file:, http:, https: or java: URL of a font directory, or the path of a pd4fonts.properties file
        Throws:
        java.io.FileNotFoundException - if a local directory or file does not exist
        See Also:
        useTTF(String, boolean), useTTF(String, String)
      • useTTF

        public void useTTF​(java.lang.String pathToFontDirs,
                           boolean generateFontMappingFileIfMissing)
                    throws java.io.FileNotFoundException
        Registers a font directory like useTTF(String), and optionally creates its pd4fonts.properties mapping file. Pro feature.
        Parameters:
        pathToFontDirs - a local font directory path or file: URL; other locations are registered as with useTTF(String)
        generateFontMappingFileIfMissing - true to index the fonts in a local directory that has no pd4fonts.properties and write the file there. Indexing a large directory can take a while, and PD4ML needs write permission to the directory.
        Throws:
        java.io.FileNotFoundException - if the directory does not exist, or the mapping file cannot be written
        See Also:
        useTTF(String)
      • useTTF

        public void useTTF​(java.lang.String pathToFontDirs,
                           java.lang.String fontFileNameFilter)
                    throws java.io.FileNotFoundException
        Registers only the fonts of a directory whose names match a filter. Pro feature. Useful for large font directories, such as the operating system font folder.

        The matching fonts are indexed into a mapping file in the system temp directory (java.io.tmpdir); the directory itself is not modified. The index is created once and reused by later calls with the same directory and filter, so delete it from the temp directory if the fonts change.

        Parameters:
        pathToFontDirs - a local font directory path or file: URL
        fontFileNameFilter - a comma-separated list of font family names or parts of names, for example "arial,courier"
        Throws:
        java.io.FileNotFoundException - if the directory does not exist, or the index cannot be written
        See Also:
        useTTF(String)
      • embedTTFs

        public void embedTTFs​(boolean embed,
                              boolean allGlyphs)
        Controls how TrueType/OpenType fonts are stored in the resulting PDF. By default the glyphs the document uses are embedded (font subsetting).
        Parameters:
        embed - true (the default) to embed the fonts; false to only reference them by name, which makes the PDF smaller but requires the fonts to be installed where the PDF is viewed. PDF/A requires embedded fonts.
        allGlyphs - true to embed complete fonts instead of only the glyphs used, for example when the PDF is going to be edited; false (the default) to embed only the used glyphs. Ignored if embed is false.
        See Also:
        useTTF(String)
      • generateForms

        public void generateForms​(boolean enable,
                                  java.lang.String useTtfFont)
        Converts HTML form controls (<input>, <textarea>, <select>) to interactive PDF form fields (AcroForm) instead of static images of them. Pro feature. Has no effect in PDF/A output, which does not allow forms.
        Parameters:
        enable - true to generate PDF form fields
        useTtfFont - the name of a Unicode TrueType font for the field values. The name must be registered in a pd4fonts.properties file (see useTTF(String)) or with a CSS @font-face rule.
        Since:
        v3.2.3 Pro
        See Also:
        generateForms(boolean, String, String)
      • generateForms

        public void generateForms​(boolean enable,
                                  java.lang.String useTtfFont,
                                  java.lang.String formFontCharRange)
        Converts HTML form controls to interactive PDF form fields, like generateForms(boolean, String), and embeds the glyphs for the characters users may type into the fields. Pro feature.

        Only the glyphs a document uses are embedded by default, so characters typed into a field later may not display. List the characters the fields must support here.

        Parameters:
        enable - true to generate PDF form fields
        useTtfFont - the name of a Unicode TrueType font for the field values, registered in a pd4fonts.properties file or with a CSS @font-face rule
        formFontCharRange - the characters to embed, as single characters and ranges, for example "0-9a-zA-Z*.,:"
        Since:
        v4.0.2
        See Also:
        useTTF(String)
      • generateMulticolumn

        public void generateMulticolumn​(int columns,
                                        int span,
                                        boolean millimeters)
        Intended to lay out the document in several columns per page. Currently has no effect: the settings are stored but not used by the layout.
        Parameters:
        columns - the number of columns per page
        span - the gap between the columns
        millimeters - true if span is in millimeters, false if it is in points
      • useHttpRequest

        public void useHttpRequest​(java.lang.Object httpRequest,
                                   java.lang.Object httpResponse)
        Passes the current servlet request and response to PD4ML, for conversions running inside a web application. PD4ML then loads resources of the same web application (images, stylesheets, JSP output) through the servlet container's RequestDispatcher, so dynamic and access-protected resources can be included without a separate HTTP request. See Constants.PD4ML_HTTP_REQUEST_DISPATCHER to disable that.
        Parameters:
        httpRequest - the current request, a javax.servlet.http.HttpServletRequest or a jakarta.servlet.http.HttpServletRequest
        httpResponse - the current response, a javax.servlet.http.HttpServletResponse or a jakarta.servlet.http.HttpServletResponse
      • addCustomResourceProvider

        public void addCustomResourceProvider​(java.lang.String customProviderClassName)
        Adds a custom resource loader, for example to load resources over a proprietary protocol or from a database. For each resource, custom loaders are asked before the built-in ones, in the order they were added; the first whose canLoad(...) returns true loads it.
        Parameters:
        customProviderClassName - the fully qualified name of a class that extends ResourceProvider and has a public no-argument constructor. The class must be loadable by PD4ML's class loader or the thread context class loader.
        See Also:
        ResourceProvider
      • addCustomTagHandler

        public void addCustomTagHandler​(java.lang.String customTagName,
                                        CustomTag implementation)
        Registers a handler that renders a custom HTML tag, for example <chart>...</chart>. For each occurrence of the tag in the document PD4ML calls getInstance(...) on the registered object with the tag's source code, and the returned instance sizes and paints the element.
        Parameters:
        customTagName - the tag name in lower case; tags in the HTML source match it in any case
        implementation - the handler, used as a factory for the per-tag instances
        See Also:
        CustomTag
      • generateBookmarksFromHeadings

        public void generateBookmarksFromHeadings​(boolean enable)
        Generates the PDF bookmarks (outline) from the document headings: each <h1> to <h6> becomes a bookmark, nested by heading level.

        Bookmarks are generated either from headings or from anchors, not both: this call also switches anchor-based bookmarks to the opposite state.

        Parameters:
        enable - true to generate bookmarks from headings (and not from anchors); false to generate them from anchors instead
        See Also:
        generateBookmarksFromAnchors(boolean)
      • generateBookmarksFromAnchors

        public void generateBookmarksFromAnchors​(boolean enable)
        Generates the PDF bookmarks (outline) from named anchors, that is from <a name="destination">Label</a> tags. The anchor text becomes the bookmark label; if the anchor has no text, the anchor name is used.

        Bookmarks are generated either from headings or from anchors, not both: this call also switches heading-based bookmarks to the opposite state.

        Parameters:
        enable - true to generate bookmarks from anchors (and not from headings); false to generate them from headings instead
        See Also:
        generateBookmarksFromHeadings(boolean)
      • setSessionID

        public void setSessionID​(java.lang.String sessionID)
        Sets the web application session ID to send with resource requests, so resources that require the user's session (stylesheets, images and so on) can be loaded. The ID is appended to the resource URLs as a path parameter: resource.jpg;jsessionid=<sessionID>?other_args.

        The parameter name "jsessionid" can be changed with the pd4ml.sessionid.varname system property, and appending can be turned off with Constants.PD4ML_SESSIONID_APPEND. See also setCookie(String, String).

        Parameters:
        sessionID - the session ID
        Throws:
        InvokeException - if called after readHTML(...)
        Since:
        v3.0.0.b1
      • overrideDocumentEncoding

        public void overrideDocumentEncoding​(java.lang.String encoding)
        Forces the encoding of the HTML document, overriding the encoding reported by the server, the byte order mark and <meta> charset declarations. Useful for documents that declare a wrong charset.
        Parameters:
        encoding - the Java name of the encoding, for example "UTF-8", "Cp1252" or "ISO8859_1"
        Throws:
        InvokeException - if called after readHTML(...)
        Since:
        v3.7.1
      • enableHyperlinks

        public void enableHyperlinks​(boolean enable)
        Controls whether HTML links become clickable links in the resulting PDF. Both external links and links to anchors inside the document are affected. The link text is rendered either way.
        Parameters:
        enable - true (the default) to generate PDF links; false to omit them
        Since:
        v1.2.0
      • setPageHeader

        public void setPageHeader​(java.lang.String htmlCode,
                                  int heightPx)
                           throws InvokeException
        Sets an HTML page header for all pages. Equivalent to placing a <pd4ml:page.header> element with the given content at the start of the document body.

        The header HTML may contain the placeholders $[page] (current page number), $[total] (total number of pages) and $[title] (document title).

        Parameters:
        htmlCode - the header content as HTML
        heightPx - the header height in HTML pixels (the same units as setHtmlWidth(int)), or 0 or less to size the header to its content. The header area is taken from the page content area.
        Throws:
        InvokeException - if htmlCode is null, or the method is called after readHTML(...)
        See Also:
        setPageHeader(String, int, String)
      • setPageHeader

        public void setPageHeader​(java.lang.String htmlCode,
                                  int heightPx,
                                  java.lang.String scope)
                           throws InvokeException
        Sets an HTML page header for the selected pages. Equivalent to placing a <pd4ml:page.header scope="..."> element with the given content at the start of the document body. Several calls with different scopes can define different headers, for example one for the first page and another for the rest.
        Parameters:
        htmlCode - the header content as HTML; see setPageHeader(String, int) for the supported placeholders
        heightPx - the header height in HTML pixels, or 0 or less to size the header to its content
        scope - the pages to apply the header to (see page scopes), or null for all pages
        Throws:
        InvokeException - if htmlCode is null, or the method is called after readHTML(...)
      • setPageFooter

        public void setPageFooter​(java.lang.String htmlCode,
                                  int heightPx)
                           throws InvokeException
        Sets an HTML page footer for all pages. Equivalent to placing a <pd4ml:page.footer> element with the given content at the start of the document body.

        The footer HTML may contain the placeholders $[page] (current page number), $[total] (total number of pages) and $[title] (document title), for example "<div align=\"right\">Page $[page] of $[total]</div>".

        Parameters:
        htmlCode - the footer content as HTML
        heightPx - the footer height in HTML pixels (the same units as setHtmlWidth(int)), or 0 or less to size the footer to its content. The footer area is taken from the page content area.
        Throws:
        InvokeException - if htmlCode is null, or the method is called after readHTML(...)
        See Also:
        setPageFooter(String, int, String)
      • setPageFooter

        public void setPageFooter​(java.lang.String htmlCode,
                                  int heightPx,
                                  java.lang.String scope)
                           throws InvokeException
        Sets an HTML page footer for the selected pages. Equivalent to placing a <pd4ml:page.footer scope="..."> element with the given content at the start of the document body. Several calls with different scopes can define different footers.
        Parameters:
        htmlCode - the footer content as HTML; see setPageFooter(String, int) for the supported placeholders
        heightPx - the footer height in HTML pixels, or 0 or less to size the footer to its content
        scope - the pages to apply the footer to (see page scopes), or null for all pages
        Throws:
        InvokeException - if htmlCode is null, or the method is called after readHTML(...)
      • setWatermark

        public void setWatermark​(java.lang.String htmlCode,
                                 float left,
                                 float top,
                                 float opacity,
                                 float angle,
                                 float scale,
                                 boolean screen,
                                 boolean print,
                                 java.lang.String scope)
        Adds a watermark: HTML content drawn over the page content of the selected pages. Equivalent to placing a <pd4ml:watermark> element in the document. Several watermarks can be added.
        Parameters:
        htmlCode - the watermark content as HTML, for example "<b style=\"font-size: 60px; color: red\">DRAFT</b>"
        left - the horizontal position of the watermark, in points from the left page edge
        top - the vertical position of the watermark, in points from the top page edge
        opacity - the watermark opacity, from 0 (invisible) to 1 (opaque)
        angle - the rotation angle in degrees
        scale - the scale factor of the watermark content, 1 for its natural size
        screen - true to show the watermark when the PDF is viewed on screen
        print - true to show the watermark when the PDF is printed. If both screen and print are false, the call has no effect.
        scope - the pages to apply the watermark to (see page scopes), or null for all pages
        Throws:
        InvokeException - if htmlCode is null, or the method is called after readHTML(...)
      • setPageBackground

        public void setPageBackground​(java.lang.String htmlCode)
        Sets HTML content to draw under the page content of every page, for example a letterhead or a page frame. Equivalent to placing a <pd4ml:page.background> element in the document.
        Parameters:
        htmlCode - the background content as HTML
        Throws:
        InvokeException - if htmlCode is null, or the method is called after readHTML(...)
        See Also:
        setPageBackground(String, String)
      • setPageBackground

        public void setPageBackground​(java.lang.String htmlCode,
                                      java.lang.String scope)
        Sets HTML content to draw under the page content of the selected pages.
        Parameters:
        htmlCode - the background content as HTML
        scope - the pages to apply the background to (see page scopes), or null for all pages
        Throws:
        InvokeException - if htmlCode is null, or the method is called after readHTML(...)
      • setPermissions

        public void setPermissions​(java.lang.String password,
                                   int permissions)
        Encrypts the resulting PDF with 128-bit AES and restricts what users may do with it. Same as setPermissions(String, int, int) with Constants.AES_128BIT.
        Parameters:
        password - the password needed to open the document, or null, an empty string or "empty" to let anyone open it and only apply the permissions
        permissions - the allowed operations, a combination of the Constants.Allow* flags, for example Constants.AllowPrint | Constants.AllowCopy
        Since:
        v1.1.0
      • setPermissions

        public void setPermissions​(java.lang.String password,
                                   int permissions,
                                   int encryptionMethod)
        Encrypts the resulting PDF with the given algorithm and restricts what users may do with it.

        A given password is used both as the user password (to open the document) and as the owner password (to change its permissions). Permissions are enforced by the PDF viewer. PDF/A does not allow encryption, so the setting is ignored for PDF/A output and a warning is recorded (see getLastRenderInfo(String)).

        Parameters:
        password - the password needed to open the document, or null, an empty string or "empty" to let anyone open it and only apply the permissions
        permissions - the allowed operations, a combination of the Constants.Allow* flags, for example Constants.AllowPrint | Constants.AllowCopy, or Constants.DefaultPermissions to allow everything
        encryptionMethod - Constants.AES_128BIT, Constants.AES_256BIT, Constants.RC4_128BIT or Constants.RC4_40BIT. Prefer AES; RC4 is weak and only for compatibility with very old PDF viewers.
        Since:
        v4.1.0
      • setCookie

        public void setCookie​(java.lang.String name,
                              java.lang.String value)
        Adds a cookie to every HTTP request PD4ML makes to load the document and its resources, for example to pass an authentication or session cookie. Call it once per cookie.
        Parameters:
        name - the cookie name; the call is ignored if it is null or blank
        value - the cookie value; the call is ignored if it is null or blank
        Since:
        v3.0.2
      • setHttpOptions

        public void setHttpOptions​(java.lang.String proxy,
                                   java.lang.String basicAuthentication)
        Sets the proxy and the credentials for HTTP requests PD4ML makes to load the document and its resources.
        Parameters:
        proxy - the HTTP proxy as "host:port", or null for a direct connection
        basicAuthentication - credentials for HTTP Basic authentication as "login:password", or null for none
        Throws:
        InvokeException - if called after readHTML(...)
      • addDocumentActionHandler

        public void addDocumentActionHandler​(java.lang.String actionType,
                                             java.lang.String javaScript)
        Adds JavaScript that the PDF viewer runs on a document event. Only viewers with JavaScript support run it, and users can disable it. A later call for the same event replaces the earlier handler.
        Parameters:
        actionType - the event: "OpenAction" (document opened), "DC" (document will close), "WS" (document will be saved), "DS" (document was saved), "WP" (document will be printed) or "DP" (document was printed). Unknown values are ignored.
        javaScript - the JavaScript code to run, for example "this.print(true);"
      • setPageSize

        public void setPageSize​(PageSize d,
                                java.lang.String scope)
        Sets the page size for the selected pages. If the document also defines page sizes with CSS @page rules, a size set here for the same scope takes precedence. The default page size is A4.
        Parameters:
        d - the page size, for example PageSize.A4 or PageSize.LETTER.rotate() for landscape
        scope - the pages to apply the size to (see page scopes), or null for all pages
        Throws:
        InvokeException - if the size is null, or its width or height is not positive
        See Also:
        setPageSize(PageSize)
      • setPageSize

        public void setPageSize​(PageSize d)
                         throws InvokeException
        Sets the page size for all pages. The default page size is A4.

        PageSize defines constants for the common ISO, JIS and North American formats. For landscape orientation, rotate the size: setPageSize(PageSize.A4.rotate()).

        Parameters:
        d - the page size
        Throws:
        InvokeException - if the size is null, or its width or height is not positive
        See Also:
        setPageSize(PageSize, String)
      • getPageSize

        public PageSize getPageSize​(int pageNum)
        Returns the size of a page, as determined by the default page size, setPageSize(...) calls and, after readHTML(...), CSS @page rules of the document. Page formats set with <pd4ml:page.break> tags in the document are not taken into account.
        Parameters:
        pageNum - the page number, starting from 1
        Returns:
        the page size
      • setPageMargins

        public void setPageMargins​(PageMargins margins)
        Sets the page margins for all pages. The default margins are 10 mm on each side for PDF, RTF and DOCX output, and none for image output. Page headers and footers are placed in the area within the margins, not in the margins.
        Parameters:
        margins - the page margins, for example new PageMargins(20, 10, 20, 10, Dimensions.Units.MM)
        Throws:
        InvokeException - if the margins are null or a margin is negative
        See Also:
        setPageMargins(PageMargins, String)
      • setPageMargins

        public void setPageMargins​(PageMargins margins,
                                   java.lang.String scope)
        Sets the page margins for the selected pages. If the document also defines margins with CSS @page rules, margins set here for the same scope take precedence.
        Parameters:
        margins - the page margins
        scope - the pages to apply the margins to (see page scopes), or null for all pages
        Throws:
        InvokeException - if the margins are null or a margin is negative
      • getPageMargins

        public PageMargins getPageMargins​(int pageNum,
                                          boolean imageGeneration)
        Returns the margins of a page, as determined by the defaults, setPageMargins(...) calls and, after readHTML(...), CSS @page rules of the document.
        Parameters:
        pageNum - the page number, starting from 1
        imageGeneration - selects the defaults for pages no setting covers: true for image output (no margins), false for PDF, RTF and DOCX output (10 mm on each side)
        Returns:
        the page margins
      • setHtmlWidth

        public void setHtmlWidth​(int width)
                          throws InvokeException
        Sets the width, in pixels, of the virtual browser window the document is laid out in. This is like resizing a browser window: it determines line breaks, the width of percentage-sized elements and so on.

        The layout is then scaled so that this width fills the printable page width (page width minus left and right margins). The larger the HTML width, the smaller the content appears on the page. The page height in pixels follows from the width and the page proportions; it cannot be set separately.

        If the width is not set, it is derived from the printable page width at Dimensions.PIXELS_PER_POINT (1.35) pixels per point, so that 1px is rendered as about 0.74pt (about 727px for an A4 page with the default margins).

        Parameters:
        width - the layout width in pixels
        Throws:
        InvokeException - if the width is not positive
        See Also:
        adjustHtmlWidth(boolean), predictScale(PageMargins, PageSize, int)
      • adjustHtmlWidth

        public void adjustHtmlWidth​(boolean adjust)
        Fits the HTML width to the actual width of the content. PD4ML first lays the document out with the width set by setHtmlWidth(int) and measures the right edge of the rendered content. Then:
        • for PDF output, if the content extends beyond the HTML width (for example a wide table or an element with a fixed width), the HTML width is increased to the right edge, so the whole content fits on the page. A narrower content does not reduce the width;
        • for RTF and DOCX output, the HTML width is set to the right edge, so the content fills the page width.
        Notes:
        • For RTF and DOCX, set setHtmlWidth(int) to a value larger than the expected content width.
        • Elements with a width of 100% always extend to the full HTML width, so in documents with such elements only overflowing content changes the result.
        • The scale factor then depends on the content, so font and object sizes differ from document to document.
        • The document is laid out twice, which takes more time.
        Parameters:
        adjust - true to enable the adjustment
        Since:
        3.0.2
      • fitPageVertically

        public void fitPageVertically​(int align)
        Scales the whole document down so that it fits on a single page vertically, including the page header and footer. A document that already fits is not enlarged. As the scaled content becomes narrower than the page, it is aligned horizontally as requested. PDF output only.
        Parameters:
        align - the horizontal alignment of the scaled content: Constants.LEFT_ALIGN, Constants.CENTER_ALIGN or Constants.RIGHT_ALIGN; 0 turns the mode off
        See Also:
        getFitPageVertically()
      • getFitPageVertically

        public short getFitPageVertically()
        Returns the alignment set by fitPageVertically(int).
        Returns:
        the alignment constant, or 0 if the fit-to-page mode is off
      • setAuthorName

        public final void setAuthorName​(java.lang.String name)
        Sets the author stored in the document properties (metadata) of the output. If not set, the value of a <meta name="author"> tag in the document is used.
        Parameters:
        name - the author name
        Since:
        v1.0.5
      • setDocumentTitle

        public final void setDocumentTitle​(java.lang.String title)
        Sets the title stored in the document properties (metadata) of the output, overriding the <title> of the HTML document.
        Parameters:
        title - the document title
        Since:
        v1.0.5
      • setInitialPageNumber

        public void setInitialPageNumber​(int initialPageNumber)
        Sets the number of the first page, for example when the output is going to be appended to another document. Affects the page numbers shown in the output, such as the $[page] placeholder in headers and footers. Can also be set with Constants.PD4ML_INITIAL_PAGE_NUMBER.
        Parameters:
        initialPageNumber - the page number of the first page; 1 by default
      • addStyle

        public final void addStyle​(java.net.URL stylesheet,
                                   boolean overrideDocumentStyles)
                            throws InvokeException
        Applies an additional CSS stylesheet, loaded from a URL, to the document. Pro feature. Useful to adapt documents for print without changing them, for example to hide navigation elements. Up to 40 stylesheets can be added.
        Parameters:
        stylesheet - the stylesheet location
        overrideDocumentStyles - true to apply the stylesheet after the document's own styles, so its rules win over them at equal specificity; false to apply it before, so the document's rules win
        Throws:
        InvokeException - if more than 40 stylesheets are added
        Since:
        v3.1.0 Pro
      • addStyle

        public final void addStyle​(java.lang.String stylesheet,
                                   boolean overrideDocumentStyles)
                            throws InvokeException
        Applies additional CSS rules to the document. Pro feature. Up to 40 stylesheets can be added.
        Parameters:
        stylesheet - the CSS rules, for example "body { font-family: Arial; }"
        overrideDocumentStyles - true to apply the rules after the document's own styles, so they win over them at equal specificity; false to apply them before, so the document's rules win
        Throws:
        InvokeException - if more than 40 stylesheets are added
        Since:
        v3.1.0 Pro
      • injectHtml

        public void injectHtml​(java.lang.String htmlSnippet,
                               boolean prependBodyContent)
        Inserts HTML code into the document body without changing the document source. Several snippets can be injected; they are inserted in the order of the calls.
        Parameters:
        htmlSnippet - the HTML code; null is ignored
        prependBodyContent - true to insert the code right after the opening <body> tag, false to insert it right before the closing </body> tag
        Throws:
        InvokeException - if called after readHTML(...)
      • testTermination

        public void testTermination()
                             throws ForcedTerminationException
        Checks whether terminate() has been called, and aborts the conversion if so. PD4ML calls it at check points during a conversion; custom tag handlers and resource providers can call it during long operations.
        Throws:
        ForcedTerminationException - if termination has been requested
      • getHeight

        public int getHeight​(int width)
                      throws java.io.IOException
        Calculates the height of the whole document laid out at the given width, ignoring page breaks. The document is laid out without producing output, which can take a while for large documents. Must be called after readHTML(...).
        Parameters:
        width - the layout width in pixels
        Returns:
        the document height in pixels
        Throws:
        java.io.IOException - if the layout fails
      • getDocumentTitle

        public java.lang.String getDocumentTitle()
                                          throws InvokeException
        Returns the document title: the one set with setDocumentTitle(String), or else the <title> of the HTML document.
        Returns:
        the document title, or null if there is none
        Throws:
        InvokeException - if called before readHTML(...)
      • writePDF

        public void writePDF​(java.io.OutputStream os)
                      throws java.io.IOException
        Lays out the document read by readHTML(...) and writes it as a PDF 1.7 document.

        The stream is closed when the method returns. Call readHTML(...) first.

        Parameters:
        os - the stream to write the PDF to; it is closed afterwards
        Throws:
        InvokeException - if readHTML(...) has not been called
        java.io.IOException - if the output cannot be written, or a problem occurred that the error policy treats as fatal (see setErrorPolicy(ErrorPolicy))
        See Also:
        writePDF(OutputStream, PdfSpec)
      • writePDF

        public void writePDF​(java.io.OutputStream os,
                             java.lang.String pdfFormat)
                      throws java.io.IOException
        Lays out the document and writes it as a regular PDF, a PDF/A or a PDF/UA document. For other standards and combinations use writePDF(OutputStream, PdfSpec).

        PDF/A requires all fonts to be embedded, so the result complies only if the document's fonts are available as TrueType/OpenType fonts (see useTTF(String)). PDF/A and PDF/UA output requires a license that covers it. To check the result, read Constants.PD4ML_PDFA_STATUS with getLastRenderInfo(String) afterwards.

        Parameters:
        os - the stream to write the PDF to; it is closed afterwards
        pdfFormat - Constants.PDF for PDF 1.7, Constants.PDFA for PDF/A-1b, or Constants.PDFUA for a tagged PDF that conforms to both PDF/UA-1 and PDF/A-2a
        Throws:
        InvokeException - if the format is not one of these values, or readHTML(...) has not been called
        java.io.IOException - if the output cannot be written, or a problem occurred that the error policy treats as fatal
      • writePDF

        public void writePDF​(java.io.OutputStream os,
                             PdfSpec pdfFormat)
                      throws java.io.IOException
        Lays out the document and writes it as a PDF that conforms to the given PDF version and, optionally, to PDF/A, PDF/UA, ZUGFeRD or Factur-X.

        Standards are combined with PdfSpec.combine(PdfSpec), for example PdfSpec.PDF_1_7.combine(PdfSpec.PDFA_3B), or PdfSpec.PDF_1_7.combine(PdfSpec.PDFA_2A).combine(PdfSpec.PDFUA_1). Standards that require a tagged PDF (PDF/A-1a, -2a, -3a and PDF/UA) make PD4ML generate the structure tree.

        PDF/A requires all fonts to be embedded, and forbids encryption and, in PDF/A-1, transparency. PD4ML adapts the output where it can and records the problems it could not solve; read them with getLastRenderInfo(String) and Constants.PD4ML_PDFA_STATUS. To fail instead of writing a non-compliant document, set the error policy to Constants.ErrorPolicy.PEDANTIC. PDF/A and PDF/UA output requires a license that covers it.

        Parameters:
        os - the stream to write the PDF to; it is closed afterwards
        pdfFormat - the PDF version and standards to conform to
        Throws:
        InvokeException - if readHTML(...) has not been called
        java.io.IOException - if the output cannot be written, or a problem occurred that the error policy treats as fatal
        See Also:
        setErrorPolicy(ErrorPolicy)
      • writeRTF

        public void writeRTF​(java.io.OutputStream os,
                             boolean convertImagesToWMF)
                      throws java.io.IOException
        Lays out the document read by readHTML(...) and writes it as an RTF document. RTF and DOCX output requires a license that covers it.

        The layout is converted to RTF text, paragraphs and tables, so the result can be edited in a word processor. Some HTML/CSS features have no RTF equivalent and are simplified.

        Parameters:
        os - the stream to write the RTF document to; it is closed afterwards
        convertImagesToWMF - true to convert images to WMF, for RTF viewers such as WordPad that cannot display other image formats (the file becomes much larger); false to embed images in their original format, which Microsoft Word and most other editors support
        Throws:
        InvokeException - if readHTML(...) has not been called
        java.io.IOException - if the output cannot be written
      • writeDOCX

        public void writeDOCX​(java.io.OutputStream os)
                       throws java.io.IOException
        Lays out the document read by readHTML(...) and writes it as a Microsoft Word (DOCX) document. RTF and DOCX output requires a license that covers it.

        The layout is converted to Word text, paragraphs and tables, so the result can be edited. Some HTML/CSS features have no DOCX equivalent and are simplified.

        Parameters:
        os - the stream to write the DOCX document to; it is closed afterwards
        Throws:
        InvokeException - if readHTML(...) has not been called
        java.io.IOException - if the output cannot be written
      • setRenderingHints

        public void setRenderingHints​(java.util.Map hints)
        Sets the Java2D rendering hints used to draw pages in image output (renderAsImages(...)), for example to enable antialiasing or to trade quality for speed. Replaces hints set before. Has no effect on PDF, RTF and DOCX output.
        
         Map<RenderingHints.Key, Object> hints = new HashMap<>();
         hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
         hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
         pd4ml.setRenderingHints(hints);
         
        Parameters:
        hints - the rendering hints, keyed by RenderingHints.Key, or null to use the defaults
        See Also:
        RenderingHints
      • renderAsImages

        public java.io.File renderAsImages​(java.io.File dir,
                                           java.lang.String fileNamePrefix,
                                           java.lang.String format)
                                    throws java.io.IOException
        Lays out the document and writes each page as a PNG image file. Image output requires a license that covers it.

        The files are named after the prefix: <prefix>.png for the first page, <prefix>_1.png for the second, <prefix>_2.png for the third and so on. Existing PNG files in the directory whose names start with the prefix are deleted. The page size in pixels follows from the HTML width; by default image pages have no margins.

        Parameters:
        dir - the target directory, or null for the system temp directory (java.io.tmpdir)
        fileNamePrefix - the file name prefix
        format - selects the color model: Constants.PNG24 for 32-bit color with transparency, other values for 24-bit color. The files are always written as PNG; for TIFF output use renderAsImages(String).
        Returns:
        the file of the first page
        Throws:
        InvokeException - if readHTML(...) has not been called
        java.io.IOException - if the files cannot be written
      • renderAsImages

        public byte[][] renderAsImages​(java.lang.String format)
                                throws java.io.IOException
        Lays out the document and encodes each page as an image in memory. Image output requires a license that covers it.

        The page size in pixels follows from the HTML width; by default image pages have no margins. Use outputRange(String) to render only some of the pages.

        Parameters:
        format - the image format: Constants.PNG24, Constants.PNG8, Constants.TIFF, Constants.TIFF_COMPRESSED, Constants.MULTIPAGE_TIFF or Constants.MULTIPAGE_TIFF_COMPRESSED. TIFF formats require the JAI library in the classpath.
        Returns:
        the encoded images, one array element per page. For the multipage TIFF formats the array has a single element that contains all pages.
        Throws:
        InvokeException - if readHTML(...) has not been called
        java.io.IOException - if the images cannot be encoded
      • renderAsImages

        public java.awt.image.BufferedImage[] renderAsImages()
                                                      throws java.io.IOException
        Lays out the document and draws each page as an image in memory, for example to display or post-process the pages. Image output requires a license that covers it.
        Returns:
        the page images (ARGB), one per page
        Throws:
        InvokeException - if readHTML(...) has not been called
        java.io.IOException - if the layout fails
        See Also:
        setRenderingHints(Map)
      • dump

        public java.lang.String dump​(int mode)
                              throws java.io.IOException
        Returns a text dump of internal structures, for diagnostics and support requests.
        Parameters:
        mode - bit flags selecting what to dump: 0x01 or 0x02 dump the parsed document tree, which is available after readHTML(...); higher bits (for example 0x04 for table structure, 0x08 for layout information) dump the layout, which requires a prior write... or renderAsImages(...) call
        Returns:
        the dump
        Throws:
        InvokeException - if the requested information is not available yet
        java.io.IOException - if the dump fails
      • protectPhysicalUnitDimensions

        public void protectPhysicalUnitDimensions​(boolean keepPhysicalUnitDimensions)
        Keeps sizes given in physical units (in, cm, mm, pt, pc) at their exact physical size in the PDF, regardless of the HTML width.

        By default such sizes are converted to pixels before the layout, and the whole layout is then scaled from the HTML width to the page width, so a "10pt" font is printed at exactly 10pt only if that scale is 1. With this option, physically sized objects keep their size while pixel-sized objects are still scaled. As there is then no single scale factor for the document, the layout can look different from the browser rendering; use it with care.

        Do not combine it with adjustHtmlWidth(boolean) or fitPageVertically(int), which change the scale factor in their own way.

        Parameters:
        keepPhysicalUnitDimensions - true to keep physical sizes
        Since:
        v3.0.4, v4.0.9
      • translateToPt

        public static final float translateToPt​(float mm)
        Converts millimeters to points (1/72 inch) at Constants.TRANSLATE_FACTOR points per millimeter. Note that the result includes a rounding offset of 0.5 but is not truncated, so it is about half a point larger than the exact value.
        Parameters:
        mm - the value in millimeters
        Returns:
        the value in points
      • predictScale

        public static final float predictScale​(PageMargins pageMargins,
                                               PageSize pageSize,
                                               int userSpace)
        Calculates the scale factor from HTML pixels to PDF points for the given settings: the printable page width (page width minus left and right margins) divided by the HTML width. For example, a factor of 0.75 means a 16px font is printed at 12pt.
        Parameters:
        pageMargins - the page margins
        pageSize - the page size
        userSpace - the HTML width in pixels (see setHtmlWidth(int))
        Returns:
        the number of points per HTML pixel
      • predictPageHeight

        public static final int predictPageHeight​(PageMargins pageMargins,
                                                  PageSize pageSize,
                                                  int userSpace)
        Calculates how many HTML pixels of content fit on one page for the given settings: the printable page height (page height minus top and bottom margins) divided by the scale factor from predictScale(PageMargins, PageSize, int). Page headers and footers reduce the actual value.
        Parameters:
        pageMargins - the page margins
        pageSize - the page size
        userSpace - the HTML width in pixels
        Returns:
        the printable page height in HTML pixels
      • setDynamicData

        public void setDynamicData​(java.util.Map<java.lang.String,​java.lang.String> map)
        Sets values for $[key] placeholders in the document, so the HTML can be used as a template. For example, with map.put("customer", "ACME") every $[customer] in the document is replaced with "ACME".

        The values are inserted as text: HTML markup in a value is not interpreted, unless enabled with Constants.PD4ML_HTML_IN_DYNAMIC_DATA. The keys "page", "total" and "title" are reserved for headers and footers and are removed from the map.

        Parameters:
        map - the placeholder names (without $[]) and their values; the map is copied
      • getLastRenderInfo

        public java.lang.Object getLastRenderInfo​(java.lang.String key)
                                           throws ForcedTerminationException
        Returns information about the last conversion, after a write... or renderAsImages(...) call.
        Parameters:
        key - one of:
        Returns:
        the requested information, or null for other keys
        Throws:
        ForcedTerminationException - declared for compatibility; not thrown by the current implementation
        Since:
        3.5.1
      • outputRange

        public void outputRange​(java.lang.String description)
        Limits the output to the selected pages. The whole document is still laid out; only the selected pages are written.
        Parameters:
        description - the pages to output (see page scopes), for example "2+" to skip the first page, "1-2" for the first two pages, "odd" for odd pages, or "3-7,odd" for pages 3, 5 and 7
        Since:
        v3.5.5
      • monitorProgressWith

        public void monitorProgressWith​(ProgressListener listener)
        Registers a listener that is notified about the progress of the conversion, for example to show a progress bar. The listener is called on the conversion thread.
        Parameters:
        listener - the listener
        Throws:
        InvokeException - if called after readHTML(...)
        See Also:
        ProgressListener
      • addMetadata

        public void addMetadata​(java.lang.String key,
                                java.lang.String value,
                                boolean hide)
        Adds a custom property to the XMP metadata of the resulting PDF, for example a document ID for a document management system. PDF output only.
        Parameters:
        key - the property name. It must be a valid XML element name, and must not be one of the standard names Title, Author, Subject, Keywords, Creator, Producer, CreationDate, ModDate or Trapped.
        value - the property value
        hide - false to store the property in the Adobe PDF namespace (pdfx:), where PDF viewers such as Adobe Acrobat show it among the custom document properties; true to store it outside that namespace, so viewers do not show it
      • applyKerning

        public void applyKerning​(boolean enable)
        Applies the kerning information of TrueType/OpenType fonts, which adjusts the spacing of specific character pairs (such as "AV") for more even-looking text. Has an effect only with fonts that contain kerning data, and only in PDF output.
        Parameters:
        enable - true to apply kerning; false (the default) to use the plain glyph widths
        See Also:
        useTTF(String)
      • enableLigatures

        public void enableLigatures​(boolean enable)
        Enables OpenType text shaping with TrueType/OpenType fonts: glyph substitution (GSUB tables) for ligatures such as "fi" and "fl", and the compound glyphs that complex scripts such as Devanagari need for correct rendering.

        Shaping makes the conversion slower, so enable it only when the fonts and the text need it.

        Parameters:
        enable - true to enable shaping; false by default
        See Also:
        useTTF(String)
      • getCache

        public java.lang.Object getCache()
        Returns the font and resource cache of this instance, so later conversions can reuse it with setCache(Object) instead of loading the same fonts and resources again. The cache is created by readHTML(...).

        The cache is not thread-safe: use it in one conversion at a time, for example by keeping one cache per thread.

        Returns:
        the cache, or null if readHTML(...) has not been called yet
        See Also:
        setCache(Object)
      • setCache

        public void setCache​(java.lang.Object fontCache)
        Makes this instance reuse the font and resource cache of an earlier conversion. Call it before readHTML(...). The font directories and font embedding settings are part of the cache, so those of the earlier instance remain in effect, and useTTF(String) and embedTTFs(boolean, boolean) calls on this instance have no effect.
        Parameters:
        fontCache - a cache returned by getCache() of another instance; other objects are ignored
        See Also:
        getCache()
      • asyncResourceLoader

        public void asyncResourceLoader​(int threadPoolSize)
        Loads external resources (images, attachments and so on) in parallel, which can speed up documents that reference many remote resources. By default resources are loaded one after another on the conversion thread. The loader starts its own threads, so avoid it in Java EE containers that do not allow that.
        Parameters:
        threadPoolSize - the number of loader threads: 0 or 1 to load resources sequentially (the default), a larger value for a fixed-size thread pool, or a negative value for a pool that creates threads as needed and reuses idle ones