Class PD4ML
- java.lang.Object
-
- com.pd4ml.PD4ML
-
public class PD4ML extends java.lang.ObjectThe 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:
- 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. - Read and parse the source document with one of the
readHTML(...)methods. - Lay out the document and write the result with
writePDF(OutputStream),writeRTF(OutputStream, boolean),writeDOCX(OutputStream)or one of therenderAsImages(...)methods.
An instance converts exactly one document: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); }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 (seeapplyLicense(String)).Page scopes
Several methods take ascopeargument that selects the pages a setting applies to. A scope is a comma-separated list of the following items;nullmeans 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.
- 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
-
-
Field Summary
Fields Modifier and Type Field Description static booleandisableBatikGlobal switch,falseby default.static booleandisableMathMLGlobal switch,falseby 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 voidaddCustomResourceProvider(java.lang.String customProviderClassName)Adds a custom resource loader, for example to load resources over a proprietary protocol or from a database.voidaddCustomTagHandler(java.lang.String customTagName, CustomTag implementation)Registers a handler that renders a custom HTML tag, for example<chart>...</chart>.voidaddDocumentActionHandler(java.lang.String actionType, java.lang.String javaScript)Adds JavaScript that the PDF viewer runs on a document event.voidaddMetadata(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.voidaddStyle(java.lang.String stylesheet, boolean overrideDocumentStyles)Applies additional CSS rules to the document.voidaddStyle(java.net.URL stylesheet, boolean overrideDocumentStyles)Applies an additional CSS stylesheet, loaded from a URL, to the document.voidadjustHtmlWidth(boolean adjust)Fits the HTML width to the actual width of the content.voidapplyKerning(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.booleanapplyLicense(java.lang.String license)Applies a license to this instance, replacing the one applied before.voidasyncResourceLoader(int threadPoolSize)Loads external resources (images, attachments and so on) in parallel, which can speed up documents that reference many remote resources.java.lang.Stringdump(int mode)Returns a text dump of internal structures, for diagnostics and support requests.voidembedTTFs(boolean embed, boolean allGlyphs)Controls how TrueType/OpenType fonts are stored in the resulting PDF.voidenableHyperlinks(boolean enable)Controls whether HTML links become clickable links in the resulting PDF.voidenableLigatures(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.voidfitPageVertically(int align)Scales the whole document down so that it fits on a single page vertically, including the page header and footer.voidgenerateBookmarksFromAnchors(boolean enable)Generates the PDF bookmarks (outline) from named anchors, that is from<a name="destination">Label</a>tags.voidgenerateBookmarksFromHeadings(boolean enable)Generates the PDF bookmarks (outline) from the document headings: each<h1>to<h6>becomes a bookmark, nested by heading level.voidgenerateForms(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.voidgenerateForms(boolean enable, java.lang.String useTtfFont, java.lang.String formFontCharRange)Converts HTML form controls to interactive PDF form fields, likegenerateForms(boolean, String), and embeds the glyphs for the characters users may type into the fields.voidgenerateMulticolumn(int columns, int span, boolean millimeters)Intended to lay out the document in several columns per page.java.lang.ObjectgetCache()Returns the font and resource cache of this instance, so later conversions can reuse it withsetCache(Object)instead of loading the same fonts and resources again.java.lang.StringgetDocumentTitle()Returns the document title: the one set withsetDocumentTitle(String), or else the<title>of the HTML document.shortgetFitPageVertically()Returns the alignment set byfitPageVertically(int).intgetHeight(int width)Calculates the height of the whole document laid out at the given width, ignoring page breaks.java.lang.ObjectgetLastRenderInfo(java.lang.String key)Returns information about the last conversion, after awrite...orrenderAsImages(...)call.PageMarginsgetPageMargins(int pageNum, boolean imageGeneration)Returns the margins of a page, as determined by the defaults,setPageMargins(...)calls and, afterreadHTML(...), CSS@pagerules of the document.PageSizegetPageSize(int pageNum)Returns the size of a page, as determined by the default page size,setPageSize(...)calls and, afterreadHTML(...), CSS@pagerules of the document.static java.lang.StringgetVersion()Returns the version of the PD4ML library.static java.util.DategetVersionBuildDate()Returns the build date of the PD4ML library.voidinjectHtml(java.lang.String htmlSnippet, boolean prependBodyContent)Inserts HTML code into the document body without changing the document source.booleanisDemoMode()Tells whether the converter runs in demo mode, that is, without a valid license.booleanisPro()Tells whether the applied license enables Pro features, such as TTF font embedding (useTTF(String)), PDF forms,addStyle(String, boolean)andmerge(PdfDocument, int, int, boolean).voidmerge(PdfDocument pdf, int fromPage, int toPage, boolean append)Combines the PDF produced by the nextwritePDF(OutputStream)call with pages of an existing PDF document.voidmonitorProgressWith(ProgressListener listener)Registers a listener that is notified about the progress of the conversion, for example to show a progress bar.voidoutputRange(java.lang.String description)Limits the output to the selected pages.voidoverrideDocumentEncoding(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 intpredictPageHeight(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 frompredictScale(PageMargins, PageSize, int).static floatpredictScale(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.voidprotectPhysicalUnitDimensions(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.voidreadHTML(java.io.InputStream isr)Reads and parses an HTML document from a stream.voidreadHTML(java.io.InputStream isr, java.net.URL base)Reads and parses an HTML document from a stream, decoding it with the platform default encoding (thefile.encodingsystem property).voidreadHTML(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.voidreadHTML(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).voidreadHTML(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.FilerenderAsImages(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.voidsetAuthorName(java.lang.String name)Sets the author stored in the document properties (metadata) of the output.voidsetCache(java.lang.Object fontCache)Makes this instance reuse the font and resource cache of an earlier conversion.voidsetCookie(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.voidsetDocumentTitle(java.lang.String title)Sets the title stored in the document properties (metadata) of the output, overriding the<title>of the HTML document.voidsetDynamicData(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.voidsetErrorPolicy(Constants.ErrorPolicy policy)Sets how strictly problems found during conversion are treated.voidsetHtmlWidth(int width)Sets the width, in pixels, of the virtual browser window the document is laid out in.voidsetHttpOptions(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.voidsetInitialPageNumber(int initialPageNumber)Sets the number of the first page, for example when the output is going to be appended to another document.voidsetLogLevel(int level)Sets which log and diagnostic messages are written to the console.voidsetPageBackground(java.lang.String htmlCode)Sets HTML content to draw under the page content of every page, for example a letterhead or a page frame.voidsetPageBackground(java.lang.String htmlCode, java.lang.String scope)Sets HTML content to draw under the page content of the selected pages.voidsetPageFooter(java.lang.String htmlCode, int heightPx)Sets an HTML page footer for all pages.voidsetPageFooter(java.lang.String htmlCode, int heightPx, java.lang.String scope)Sets an HTML page footer for the selected pages.voidsetPageHeader(java.lang.String htmlCode, int heightPx)Sets an HTML page header for all pages.voidsetPageHeader(java.lang.String htmlCode, int heightPx, java.lang.String scope)Sets an HTML page header for the selected pages.voidsetPageMargins(PageMargins margins)Sets the page margins for all pages.voidsetPageMargins(PageMargins margins, java.lang.String scope)Sets the page margins for the selected pages.voidsetPageSize(PageSize d)Sets the page size for all pages.voidsetPageSize(PageSize d, java.lang.String scope)Sets the page size for the selected pages.voidsetParam(java.lang.String key, java.lang.String value)Sets an advanced conversion parameter.voidsetPermissions(java.lang.String password, int permissions)Encrypts the resulting PDF with 128-bit AES and restricts what users may do with it.voidsetPermissions(java.lang.String password, int permissions, int encryptionMethod)Encrypts the resulting PDF with the given algorithm and restricts what users may do with it.voidsetRenderingHints(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.voidsetSessionID(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.voidsetWatermark(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.voidterminate()Requests termination of a running conversion and clears the font cache.voidtestTermination()Checks whetherterminate()has been called, and aborts the conversion if so.static floattranslateToPt(float mm)Converts millimeters to points (1/72 inch) atConstants.TRANSLATE_FACTORpoints per millimeter.voiduseHttpRequest(java.lang.Object httpRequest, java.lang.Object httpResponse)Passes the current servlet request and response to PD4ML, for conversions running inside a web application.voiduseTTF(java.lang.String pathToFontDirs)Registers a directory of TrueType/OpenType fonts to use in the output.voiduseTTF(java.lang.String pathToFontDirs, boolean generateFontMappingFileIfMissing)Registers a font directory likeuseTTF(String), and optionally creates its pd4fonts.properties mapping file.voiduseTTF(java.lang.String pathToFontDirs, java.lang.String fontFileNameFilter)Registers only the fonts of a directory whose names match a filter.voidwriteDOCX(java.io.OutputStream os)Lays out the document read byreadHTML(...)and writes it as a Microsoft Word (DOCX) document.voidwritePDF(java.io.OutputStream os)Lays out the document read byreadHTML(...)and writes it as a PDF 1.7 document.voidwritePDF(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.voidwritePDF(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.voidwriteRTF(java.io.OutputStream os, boolean convertImagesToWMF)Lays out the document read byreadHTML(...)and writes it as an RTF document.
-
-
-
Field Detail
-
disableBatik
public static boolean disableBatik
Global switch,falseby default. When set totrue, 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,falseby default. When set totrue, 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.licfile in the current working directory, then as apd4ml.licresource 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, afile:,http:orhttps:URL, or ajava:URL to load it from the classpath. An empty string looks forpd4ml.licin the current working directory and then in the classpath.nullskips the license lookup, so the converter runs in demo mode.loglevel- the log output to enable:0disables logging, otherwise a bitmask of theLOG_*constants inherited byConstants, for exampleConstants.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 inPD4ML().- Parameters:
loglevel- the log output to enable:0disables logging, otherwise a bitmask of theLOG_*constants inherited byConstants, for exampleConstants.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; seePD4ML(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 beforereadHTML(...). 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
StatusMessageerror is recorded and can be read withgetLastRenderInfo(String). PDF/A and PDF/UA output without a matching license is also watermarked with "PD4ML PDF/A EVALUATION MODE".
isPro()).- Parameters:
license- the license string, or the location of a license file (a file path, or afile:,http:,https:orjava:URL). If the string is not a valid license, it is tried as a location.- Returns:
trueif 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:
trueif no valid license has been applied- Since:
- v1.1.0
- See Also:
applyLicense(String)
-
isPro
public final boolean isPro()
Tells whether the applied license enables Pro features, such as TTF font embedding (useTTF(String)), PDF forms,addStyle(String, boolean)andmerge(PdfDocument, int, int, boolean).- Returns:
trueif a valid license with Pro features has been applied- Since:
- v3.8.1
-
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
nullif 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 nextwritePDF(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 documentfromPage- the first page of the existing document to include (1-based)toPage- the last page of the existing document to include, or-1for all pages up to the last oneappend-trueto put the existing pages after the conversion result,falseto 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 aForcedTerminationException. A termination request is reset whenreadHTML(...)starts.- See Also:
testTermination()
-
readHTML
public void readHTML(java.io.InputStream isr) throws InvokeException, java.io.IOExceptionReads 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 supportsmark/reset(for example aBufferedInputStreamor aByteArrayInputStream), 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 isnull, or the method has already been called for this instancejava.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.IOExceptionReads and parses an HTML document from a stream, decoding it with the platform default encoding (thefile.encodingsystem property).<meta>charset declarations in the document are ignored. To detect the encoding from the document instead, usereadHTML(InputStream, URL, String)with anullencoding.- Parameters:
isr- the HTML document streambase- the base URL to resolve relative references to images, stylesheets and other resources against, for examplenew URL("file:/path/to/document/dir/"). A<base href="...">tag in the document overrides it.- Throws:
InvokeException- if the stream isnull, or the method has already been called for this instancejava.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.IOExceptionReads and parses an HTML document from a stream, with an explicit encoding.- Parameters:
isr- the HTML document streambase- the base URL to resolve relative references to images, stylesheets and other resources against, ornullfor 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.nulldetects the encoding as described inreadHTML(InputStream).- Throws:
InvokeException- if the stream isnull, or the method has already been called for this instancejava.io.IOException- if the document cannot be read
-
readHTML
public void readHTML(java.net.URL url) throws InvokeException, java.io.IOExceptionLoads 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; seeoverrideDocumentEncoding(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 isnull, or the method has already been called for this instancejava.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.IOExceptionLoads and parses an HTML document from a URL, with an explicit encoding.- Parameters:
url- the document location; seereadHTML(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;nulldetects the encoding as described inreadHTML(URL).- Throws:
java.net.MalformedURLException- if the URL is malformedInvokeException- if the URL isnull, or the method has already been called for this instancejava.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 beforereadHTML(...)to cover the whole conversion.- Parameters:
level-0to disable logging, otherwise a bitmask of theLOG_*constants inherited byConstants: for exampleConstants.LOG_MINIMAL(errors only),Constants.LOG_VERBOSE(errors, warnings and info), or a combination such asConstants.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 anIOExceptioninstead of being logged and worked around:Constants.ErrorPolicy.RELAXED(the default): problems are logged and worked around; the conversion is not aborted;Constants.ErrorPolicy.NORMAL: input data errors, such as an image that cannot be loaded or a broken resource URL, abort the conversion;Constants.ErrorPolicy.PEDANTIC: violations of a requested standard, such as fonts that cannot be embedded in PDF/A output, abort the conversion as well;Constants.ErrorPolicy.STRICT: any warning, including problems that have a workaround (for example a missing font that can be substituted), aborts the conversion.
- Parameters:
policy- the error handling policy; must be set beforereadHTML(...)to apply to parsing and resource loading
-
useTTF
public void useTTF(java.lang.String pathToFontDirs) throws java.io.FileNotFoundExceptionRegisters a directory of TrueType/OpenType fonts to use in the output. Pro feature. Fonts used by the document are embedded in the resulting PDF (seeembedTTFs(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 linejava -jar pd4ml.jar -configure.fonts <fontdir>, or byuseTTF(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/myfontsfolder 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, afile:,http:,https:orjava: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.FileNotFoundExceptionRegisters a font directory likeuseTTF(String), and optionally creates its pd4fonts.properties mapping file. Pro feature.- Parameters:
pathToFontDirs- a local font directory path orfile:URL; other locations are registered as withuseTTF(String)generateFontMappingFileIfMissing-trueto 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.FileNotFoundExceptionRegisters 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 orfile:URLfontFileNameFilter- 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;falseto 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-trueto 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 ifembedisfalse.- 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-trueto generate PDF form fieldsuseTtfFont- the name of a Unicode TrueType font for the field values. The name must be registered in a pd4fonts.properties file (seeuseTTF(String)) or with a CSS@font-facerule.- 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, likegenerateForms(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-trueto generate PDF form fieldsuseTtfFont- the name of a Unicode TrueType font for the field values, registered in a pd4fonts.properties file or with a CSS@font-faceruleformFontCharRange- 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 pagespan- the gap between the columnsmillimeters-trueifspanis in millimeters,falseif 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'sRequestDispatcher, so dynamic and access-protected resources can be included without a separate HTTP request. SeeConstants.PD4ML_HTTP_REQUEST_DISPATCHERto disable that.- Parameters:
httpRequest- the current request, ajavax.servlet.http.HttpServletRequestor ajakarta.servlet.http.HttpServletRequesthttpResponse- the current response, ajavax.servlet.http.HttpServletResponseor ajakarta.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 whosecanLoad(...)returnstrueloads it.- Parameters:
customProviderClassName- the fully qualified name of a class that extendsResourceProviderand 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 callsgetInstance(...)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 caseimplementation- 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-trueto generate bookmarks from headings (and not from anchors);falseto 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-trueto generate bookmarks from anchors (and not from headings);falseto 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.varnamesystem property, and appending can be turned off withConstants.PD4ML_SESSIONID_APPEND. See alsosetCookie(String, String).- Parameters:
sessionID- the session ID- Throws:
InvokeException- if called afterreadHTML(...)- 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 afterreadHTML(...)- 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;falseto omit them- Since:
- v1.2.0
-
setPageHeader
public void setPageHeader(java.lang.String htmlCode, int heightPx) throws InvokeExceptionSets 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 HTMLheightPx- the header height in HTML pixels (the same units assetHtmlWidth(int)), or0or less to size the header to its content. The header area is taken from the page content area.- Throws:
InvokeException- ifhtmlCodeisnull, or the method is called afterreadHTML(...)- See Also:
setPageHeader(String, int, String)
-
setPageHeader
public void setPageHeader(java.lang.String htmlCode, int heightPx, java.lang.String scope) throws InvokeExceptionSets 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; seesetPageHeader(String, int)for the supported placeholdersheightPx- the header height in HTML pixels, or0or less to size the header to its contentscope- the pages to apply the header to (see page scopes), ornullfor all pages- Throws:
InvokeException- ifhtmlCodeisnull, or the method is called afterreadHTML(...)
-
setPageFooter
public void setPageFooter(java.lang.String htmlCode, int heightPx) throws InvokeExceptionSets 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 HTMLheightPx- the footer height in HTML pixels (the same units assetHtmlWidth(int)), or0or less to size the footer to its content. The footer area is taken from the page content area.- Throws:
InvokeException- ifhtmlCodeisnull, or the method is called afterreadHTML(...)- See Also:
setPageFooter(String, int, String)
-
setPageFooter
public void setPageFooter(java.lang.String htmlCode, int heightPx, java.lang.String scope) throws InvokeExceptionSets 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; seesetPageFooter(String, int)for the supported placeholdersheightPx- the footer height in HTML pixels, or0or less to size the footer to its contentscope- the pages to apply the footer to (see page scopes), ornullfor all pages- Throws:
InvokeException- ifhtmlCodeisnull, or the method is called afterreadHTML(...)
-
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 edgetop- the vertical position of the watermark, in points from the top page edgeopacity- the watermark opacity, from0(invisible) to1(opaque)angle- the rotation angle in degreesscale- the scale factor of the watermark content,1for its natural sizescreen-trueto show the watermark when the PDF is viewed on screenprint-trueto show the watermark when the PDF is printed. If bothscreenandprintarefalse, the call has no effect.scope- the pages to apply the watermark to (see page scopes), ornullfor all pages- Throws:
InvokeException- ifhtmlCodeisnull, or the method is called afterreadHTML(...)
-
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- ifhtmlCodeisnull, or the method is called afterreadHTML(...)- 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 HTMLscope- the pages to apply the background to (see page scopes), ornullfor all pages- Throws:
InvokeException- ifhtmlCodeisnull, or the method is called afterreadHTML(...)
-
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 assetPermissions(String, int, int)withConstants.AES_128BIT.- Parameters:
password- the password needed to open the document, ornull, an empty string or "empty" to let anyone open it and only apply the permissionspermissions- the allowed operations, a combination of theConstants.Allow*flags, for exampleConstants.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, ornull, an empty string or "empty" to let anyone open it and only apply the permissionspermissions- the allowed operations, a combination of theConstants.Allow*flags, for exampleConstants.AllowPrint | Constants.AllowCopy, orConstants.DefaultPermissionsto allow everythingencryptionMethod-Constants.AES_128BIT,Constants.AES_256BIT,Constants.RC4_128BITorConstants.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 isnullor blankvalue- the cookie value; the call is ignored if it isnullor 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", ornullfor a direct connectionbasicAuthentication- credentials for HTTP Basic authentication as "login:password", ornullfor none- Throws:
InvokeException- if called afterreadHTML(...)
-
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@pagerules, a size set here for the same scope takes precedence. The default page size is A4.- Parameters:
d- the page size, for examplePageSize.A4orPageSize.LETTER.rotate()for landscapescope- the pages to apply the size to (see page scopes), ornullfor all pages- Throws:
InvokeException- if the size isnull, 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.PageSizedefines 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 isnull, 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, afterreadHTML(...), CSS@pagerules 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 examplenew PageMargins(20, 10, 20, 10, Dimensions.Units.MM)- Throws:
InvokeException- if the margins arenullor 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@pagerules, margins set here for the same scope take precedence.- Parameters:
margins- the page marginsscope- the pages to apply the margins to (see page scopes), ornullfor all pages- Throws:
InvokeException- if the margins arenullor 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, afterreadHTML(...), CSS@pagerules of the document.- Parameters:
pageNum- the page number, starting from 1imageGeneration- selects the defaults for pages no setting covers:truefor image output (no margins),falsefor PDF, RTF and DOCX output (10 mm on each side)- Returns:
- the page margins
-
setHtmlWidth
public void setHtmlWidth(int width) throws InvokeExceptionSets 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 bysetHtmlWidth(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.
- 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-trueto 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_ALIGNorConstants.RIGHT_ALIGN;0turns the mode off- See Also:
getFitPageVertically()
-
getFitPageVertically
public short getFitPageVertically()
Returns the alignment set byfitPageVertically(int).- Returns:
- the alignment constant, or
0if 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 withConstants.PD4ML_INITIAL_PAGE_NUMBER.- Parameters:
initialPageNumber- the page number of the first page;1by default
-
addStyle
public final void addStyle(java.net.URL stylesheet, boolean overrideDocumentStyles) throws InvokeExceptionApplies 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 locationoverrideDocumentStyles-trueto apply the stylesheet after the document's own styles, so its rules win over them at equal specificity;falseto 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 InvokeExceptionApplies 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-trueto apply the rules after the document's own styles, so they win over them at equal specificity;falseto 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;nullis ignoredprependBodyContent-trueto insert the code right after the opening<body>tag,falseto insert it right before the closing</body>tag- Throws:
InvokeException- if called afterreadHTML(...)
-
testTermination
public void testTermination() throws ForcedTerminationExceptionChecks whetherterminate()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.IOExceptionCalculates 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 afterreadHTML(...).- 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 InvokeExceptionReturns the document title: the one set withsetDocumentTitle(String), or else the<title>of the HTML document.- Returns:
- the document title, or
nullif there is none - Throws:
InvokeException- if called beforereadHTML(...)
-
writePDF
public void writePDF(java.io.OutputStream os) throws java.io.IOExceptionLays out the document read byreadHTML(...)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- ifreadHTML(...)has not been calledjava.io.IOException- if the output cannot be written, or a problem occurred that the error policy treats as fatal (seesetErrorPolicy(ErrorPolicy))- See Also:
writePDF(OutputStream, PdfSpec)
-
writePDF
public void writePDF(java.io.OutputStream os, java.lang.String pdfFormat) throws java.io.IOExceptionLays out the document and writes it as a regular PDF, a PDF/A or a PDF/UA document. For other standards and combinations usewritePDF(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, readConstants.PD4ML_PDFA_STATUSwithgetLastRenderInfo(String)afterwards.- Parameters:
os- the stream to write the PDF to; it is closed afterwardspdfFormat-Constants.PDFfor PDF 1.7,Constants.PDFAfor PDF/A-1b, orConstants.PDFUAfor 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, orreadHTML(...)has not been calledjava.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.IOExceptionLays 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 examplePdfSpec.PDF_1_7.combine(PdfSpec.PDFA_3B), orPdfSpec.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)andConstants.PD4ML_PDFA_STATUS. To fail instead of writing a non-compliant document, set the error policy toConstants.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 afterwardspdfFormat- the PDF version and standards to conform to- Throws:
InvokeException- ifreadHTML(...)has not been calledjava.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.IOExceptionLays out the document read byreadHTML(...)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 afterwardsconvertImagesToWMF-trueto convert images to WMF, for RTF viewers such as WordPad that cannot display other image formats (the file becomes much larger);falseto embed images in their original format, which Microsoft Word and most other editors support- Throws:
InvokeException- ifreadHTML(...)has not been calledjava.io.IOException- if the output cannot be written
-
writeDOCX
public void writeDOCX(java.io.OutputStream os) throws java.io.IOExceptionLays out the document read byreadHTML(...)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- ifreadHTML(...)has not been calledjava.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 byRenderingHints.Key, ornullto 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.IOExceptionLays 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>.pngfor the first page,<prefix>_1.pngfor the second,<prefix>_2.pngfor 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, ornullfor the system temp directory (java.io.tmpdir)fileNamePrefix- the file name prefixformat- selects the color model:Constants.PNG24for 32-bit color with transparency, other values for 24-bit color. The files are always written as PNG; for TIFF output userenderAsImages(String).- Returns:
- the file of the first page
- Throws:
InvokeException- ifreadHTML(...)has not been calledjava.io.IOException- if the files cannot be written
-
renderAsImages
public byte[][] renderAsImages(java.lang.String format) throws java.io.IOExceptionLays 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_TIFForConstants.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- ifreadHTML(...)has not been calledjava.io.IOException- if the images cannot be encoded
-
renderAsImages
public java.awt.image.BufferedImage[] renderAsImages() throws java.io.IOExceptionLays 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- ifreadHTML(...)has not been calledjava.io.IOException- if the layout fails- See Also:
setRenderingHints(Map)
-
dump
public java.lang.String dump(int mode) throws java.io.IOExceptionReturns a text dump of internal structures, for diagnostics and support requests.- Parameters:
mode- bit flags selecting what to dump:0x01or0x02dump the parsed document tree, which is available afterreadHTML(...); higher bits (for example0x04for table structure,0x08for layout information) dump the layout, which requires a priorwrite...orrenderAsImages(...)call- Returns:
- the dump
- Throws:
InvokeException- if the requested information is not available yetjava.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)orfitPageVertically(int), which change the scale factor in their own way.- Parameters:
keepPhysicalUnitDimensions-trueto 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) atConstants.TRANSLATE_FACTORpoints 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 marginspageSize- the page sizeuserSpace- the HTML width in pixels (seesetHtmlWidth(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 frompredictScale(PageMargins, PageSize, int). Page headers and footers reduce the actual value.- Parameters:
pageMargins- the page marginspageSize- the page sizeuserSpace- 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, withmap.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
-
setParam
public void setParam(java.lang.String key, java.lang.String value)Sets an advanced conversion parameter. Call it beforereadHTML(...).The accepted keys are the
PD4ML_*constants ofConstantswhose documentation refers to this method, for exampleConstants.PD4ML_SOCKET_TIMEOUT,Constants.PD4ML_MEDIA_TYPE_PRINT,Constants.PD4ML_DOCUMENT_VIEW_MODEorConstants.PD4ML_ALLOWED_RESOURCE_LOCATION. Some parameters are read from JVM system properties instead and are ignored here; their documentation says so. Unknown keys are ignored.- Parameters:
key- the parameter namevalue- the parameter value
-
getLastRenderInfo
public java.lang.Object getLastRenderInfo(java.lang.String key) throws ForcedTerminationExceptionReturns information about the last conversion, after awrite...orrenderAsImages(...)call.- Parameters:
key- one of:Constants.PD4ML_TOTAL_PAGES: the number of pages, as aLong;Constants.PD4ML_DOCUMENT_HEIGHT_PX: the height of the laid-out document in pixels, ignoring page breaks, as aLong;Constants.PD4ML_RIGHT_EDGE_PX: the right edge of the content in pixels, as aLong; compare it with the HTML width to detect content that does not fit;Constants.PD4ML_PDFA_STATUS: the warnings and errors recorded during the conversion, as aStatusMessage[]. Despite the name, it covers all recorded problems, such as standard violations in PDF/A output or license restrictions.
- Returns:
- the requested information, or
nullfor 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 afterreadHTML(...)- 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 valuehide-falseto store the property in the Adobe PDF namespace (pdfx:), where PDF viewers such as Adobe Acrobat show it among the custom document properties;trueto 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-trueto 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-trueto enable shaping;falseby 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 withsetCache(Object)instead of loading the same fonts and resources again. The cache is created byreadHTML(...).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
nullifreadHTML(...)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 beforereadHTML(...). The font directories and font embedding settings are part of the cache, so those of the earlier instance remain in effect, anduseTTF(String)andembedTTFs(boolean, boolean)calls on this instance have no effect.- Parameters:
fontCache- a cache returned bygetCache()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:0or1to 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
-
-