public class PD4ML extends Object
Constructor and Description |
---|
PD4ML()
PD4ML Constructor
Creates and initializes an instance of the converter
|
PD4ML(int loglevel)
PD4ML Constructor
Creates and initializes an instance of the converter
|
PD4ML(String license)
PD4ML Constructor
Creates and initializes an instance of the converter
|
PD4ML(String license,
int loglevel)
PD4ML Constructor
Creates and initializes an instance of the converter
|
Modifier and Type | Method and Description |
---|---|
void |
addCustomResourceProvider(String customProviderClassName)
add custom resource loader for non-standard or customized transport protocols
|
void |
addCustomTagHandler(String customTagName,
CustomTag implementation)
adds a proprietary HTML tag implementation
|
void |
addDocumentActionHandler(String actionType,
String javaScript)
method defines JavaScript action handler for generated document.
|
void |
addMetadata(String key,
String value,
boolean hide)
The method defines custom properties for PDF document meta data.
|
void |
addStyle(String stylesheet,
boolean overrideDocumentStyles)
Apply additional stylesheet to the document
|
void |
addStyle(URL stylesheet,
boolean overrideDocumentStyles)
Apply additional stylesheet to the document
|
void |
adjustHtmlWidth(boolean adjust)
sets htmlWidth to the most right margin of the HTML block content.
|
void |
applyKerning(boolean enable)
Forces PD4ML to align font glyphs to each other according to the font kerning hints (if available).
|
boolean |
applyLicense(String license)
applies license code.
|
void |
asyncResourceLoader(int threadPoolSize)
enables asynchronous resource loading (graphics, attachments etc) if thread pool size is not equal 0.
|
String |
dump(int mode)
debug/diagnostics method
|
void |
embedTTFs(boolean embed,
boolean allGlyphs) |
void |
enableHyperlinks(boolean enable)
enables converting of HTML to PDF hyperlinks.
|
void |
enableLigatures(boolean enable)
Forces PD4ML to load TTF/OTF glyph susbstitution tables, to apply ligature replacements and to build compound glyphs.
|
void |
fitPageVertically(int align)
forces PD4ML to downscale entire HTML layout to fit a single PDF page vertically.
|
void |
generateBookmarksFromAnchors(boolean enable) |
void |
generateBookmarksFromHeadings(boolean enable) |
void |
generateForms(boolean enable,
String useTtfFont)
forces PD4ML to convert HTML forms into PDF forms (Acroforms).
|
void |
generateForms(boolean enable,
String useTtfFont,
String formFontCharRange)
forces PD4ML to convert HTML forms into PDF forms (Acroforms).
|
void |
generateMulticolumn(int columns,
int span,
boolean millimeters)
switches PD4ML into multicolumn mode.
|
Object |
getCache() |
String |
getDocumentTitle() |
short |
getFitPageVertically() |
int |
getHeight(int width)
calculates document height for given document width.
|
Object |
getLastRenderInfo(String key)
returns statistics for the last render() call
|
PageMargins |
getPageMargins(int pageNum,
boolean imageGeneration)
Returns page margins object for a specified page number.
|
PageSize |
getPageSize(int pageNum)
Returns page dimensions object for a specified page number.
|
static String |
getVersion()
returns current version number
|
static Date |
getVersionBuildDate() |
void |
injectHtml(String htmlSnippet,
boolean prependBodyContent)
Injects a portion of HTML to the source
|
boolean |
isDemoMode() |
boolean |
isPro() |
void |
merge(PdfDocument pdf,
int fromPage,
int toPage,
boolean append)
Merges conversion result with an already existing PDF document
|
void |
monitorProgressWith(ProgressListener listener)
conversion progress callback support
|
void |
outputRange(String description) |
void |
overrideDocumentEncoding(String encoding)
sets default encoding for URL-addressed HTML documents
|
static int |
predictPageHeight(PageMargins pageMargins,
PageSize pageSize,
int userSpace)
predicts page height for given conversion parameters
|
static float |
predictScale(PageMargins pageMargins,
PageSize pageSize,
int userSpace)
predicts document HTML-to-PDF mapping scale for given conversion parameters
|
void |
protectPhysicalUnitDimensions(boolean keepPhysicalUnitDimensions)
makes PD4ML to output PDF objects respecting dimensions/font sizes given in "in", "pt", "cm" etc.
|
void |
readHTML(InputStream isr)
converts input data to PDF
|
void |
readHTML(InputStream isr,
URL base)
converts input data to PDF.
|
void |
readHTML(InputStream isr,
URL base,
String encoding)
converts input data to PDF
|
void |
readHTML(URL url)
input data referred by URL to PDF
|
void |
readHTML(URL url,
String encoding)
input data referred by URL to PDF
|
BufferedImage[] |
renderAsImages()
renders document in RAM as a set of images, represent document pages
|
File |
renderAsImages(File dir,
String fileNamePrefix,
String format)
renders document as a set of image files, represent document pages
|
byte[][] |
renderAsImages(String format)
renders document in RAM as a set of images, represent document pages
|
void |
setAuthorName(String name)
sets an author name for the document
|
void |
setCache(Object fontCache) |
void |
setCookie(String name,
String value)
makes PD4ML to add a cookie with given name and value to each URL connection request
|
void |
setDocumentTitle(String title)
forces to override HTML title
|
void |
setDynamicData(Map<String,String> map) |
void |
setHtmlWidth(int width)
defines desired HTML page width in screen pixels.
|
void |
setHttpOptions(String proxy,
String basicAuthentication)
specifies HTTP options
|
void |
setInitialPageNumber(int initialPageNumber)
sets page number counter to given value.
|
void |
setLogLevel(int level)
enables an output of log/diagnostics messages.
|
void |
setPageBackground(String htmlCode)
defines HTML code to be rendered under each page content
|
void |
setPageBackground(String htmlCode,
String scope)
defines HTML code to be rendered under each page content
|
void |
setPageFooter(String htmlCode,
int heightPx)
defines HTML code to be rendered as page footer(s).
|
void |
setPageFooter(String htmlCode,
int heightPx,
String scope)
defines HTML code to be rendered as page footer(s).
|
void |
setPageHeader(String htmlCode,
int heightPx)
defines HTML code to be rendered as page header(s).
|
void |
setPageHeader(String htmlCode,
int heightPx,
String scope)
defines HTML code to be rendered as page header(s).
|
void |
setPageMargins(PageMargins margins)
defines page margins for all document pages
|
void |
setPageMargins(PageMargins margins,
String scope)
defines page margins for specified range(s) of pages
|
void |
setPageSize(PageSize d)
defines page size for all document pages.
|
void |
setPageSize(PageSize d,
String scope)
defines page size for specified range(s) of pages
|
void |
setParam(String key,
String value)
Sets parsing/rendering parameters
|
void |
setPermissions(String password,
int permissions)
forces the resulting document to be encrypted with the given password
|
void |
setRenderingHints(Map hints)
Replaces the values of all preferences for the image rendering
algorithms with the specified
hints . |
void |
setSessionID(String sessionID)
the method informs PD4ML about current session ID (in web application environments).
|
void |
setWatermark(String htmlCode,
float left,
float top,
float opacity,
float angle,
float scale,
boolean screen,
boolean print,
String scope)
defines page watermark.
|
void |
terminate()
Terminates conversion process and cleans the font cache
|
void |
testTermination() |
static float |
translateToPt(float mm)
converts from millimeters to points
|
void |
useHttpRequest(javax.servlet.http.HttpServletRequest httpRequest,
javax.servlet.http.HttpServletResponse httpResponse)
method allows to inform PD4ML about actual HTTP request context (if any).
|
void |
useTTF(String pathToFontDirs)
enables TTF font embedding subsystem.
|
void |
useTTF(String pathToFontDirs,
boolean generateFontMappingFileIfMissing) |
void |
useTTF(String pathToFontDirs,
String fontFileNameFilter)
registers font directory and forces to index fonts, whose names match the filter patterns (for example, "arial,courier").
|
void |
writePDF(OutputStream os)
renders and writes parsed HTML as PDF document
|
void |
writePDF(OutputStream os,
String pdfFormat) |
void |
writeRTF(OutputStream os,
boolean convertImagesToWMF) |
public PD4ML()
public PD4ML(String license, int loglevel)
loglevel
- bitmask to control logging verbositylicense
- license string or license file URIpublic PD4ML(int loglevel)
loglevel
- bitmask to control logging verbositypublic PD4ML(String license)
license
- license string or license file URIpublic boolean applyLicense(String license)
PD4ML(String)
If the method is not invoked, the software runs in demo mode: its output is watermarked and supplied with an ad footer.
An applying of evalution license removes the watermarks but the footer message remains.
An applying of a commercial license removes both watermark and footer in permitted output modes.license
- license string or license file URIPD4ML(String)
public final boolean isDemoMode()
public final boolean isPro()
public static String getVersion()
public static Date getVersionBuildDate()
public void merge(PdfDocument pdf, int fromPage, int toPage, boolean append)
pdf
- PDF documentfromPage
- start page of the existing document (1 or greater)toPage
- end page of the existing document (-1 means all pages)append
- 'true' forces to append the existing PDF to the conversion result. Otherwise the existing document will lead the conversion result.public void terminate()
public void readHTML(InputStream isr) throws InvokeException, IOException
isr
- input stream of formatted data. Determines encoding from BOM bytes or from HTML's meta tagInvokeException
- the input or output stream is nullIOException
- input/output problemspublic void readHTML(InputStream isr, URL base) throws InvokeException, IOException
isr
- input stream of formatted data. Determines encoding from BOM bytes or from HTML's meta tagbase
- base URL to lookup referred resources like images or CSS. Can be specified
in HTML body with <base href="..."> tagInvokeException
- the input or output stream is nullIOException
- input/output problemspublic void readHTML(InputStream isr, URL base, String encoding) throws InvokeException, IOException
isr
- input stream of formatted data. Determines encoding from BOM bytes or from HTML's meta tagbase
- base URL to lookup referred resources like images or CSS. Can be specified
in HTML body with <base href="..."> tagencoding
- content encoding. Value "default" corresponds to current OS encodingInvokeException
- the input or output stream is nullIOException
- input/output problemspublic void readHTML(URL url) throws InvokeException, IOException
url
- text representation of the input data URLMalformedURLException
- invalid URLInvokeException
- the input or output stream is nullIOException
- input/output problemspublic void readHTML(URL url, String encoding) throws MalformedURLException, InvokeException, IOException
url
- text representation of the input data URLencoding
- encoding name to overrideMalformedURLException
- invalid URLInvokeException
- the input or output stream is nullIOException
- input/output problemspublic void setLogLevel(int level)
level
- log output verbosity levelpublic void useTTF(String pathToFontDirs) throws FileNotFoundException
pathToFontDirs
- URL of a font directory or a path to pd4fonts.properties mapping file
The font directory should contain pd4fonts.properties mapping file. The file records have the following format:In order to support J2EE deployments a PD4ML-specific protocol "java:" is supported to load font resources via ClassLoader.
font_name=file_name
- font_name - font name used in the source HTML.
- file_name - font file name (should exist in the font directory)
Example:
Book\ Antiqua=BKANT.TTF
To generate the file automatically you may use the command line call:
java -jar pd4ml.jar -configure.fonts <fontdir>
After the generation, please edit the file and remove manually all references to the fonts, that are not allowed to be redistributed. Contact your TTF fonts provider for the info.
Example: useTTF("java:myfonts");
In that case the runtime looks for a fonts folder named "/myfonts" in all JAR files available for the application class loaders. The content of the folder should correspond to the rules described above: pd4fonts.properties + *.ttf
Example: useTTF("java:");
The simplest case. The runtime looks for a JAR file which contains pd4fonts.properties + *.ttf in the root directory.
FileNotFoundException
- if pd4fonts.properties file is not found or the file
refers to missing font filespublic void useTTF(String pathToFontDirs, boolean generateFontMappingFileIfMissing) throws FileNotFoundException
pathToFontDirs
- URI of TTF file directorygenerateFontMappingFileIfMissing
- forces to index available fonts (if they are not indexed yet).
The indexing may be time/resource consuming. If true, make sure PD4ML has write permission to pathToFontDirsFileNotFoundException
- font directory not founduseTTF(String)
public void useTTF(String pathToFontDirs, String fontFileNameFilter) throws FileNotFoundException
pathToFontDirs
- URI of TTF file directory,fontFileNameFilter
- a comma-separated list of font family names or name partsFileNotFoundException
- font directory not founduseTTF(String)
public void embedTTFs(boolean embed, boolean allGlyphs)
embed
- if true forces PD4ML to include used font glyphs to the resulting PDF, otherwise it registers only font family names
(expecting the TTFs present in the PDF reader environment)allGlyphs
- if true (and if param 'embed' is true) forces PD4ML to include all font glyphs to the resulting PDFpublic void generateForms(boolean enable, String useTtfFont)
useTtfFont
- - UNICODE TTF font name to be used for form input. The name must appear in pd4fonts.properties or
specified via @font-face CSS at-ruleenable
- enables or disables the featureuseTTF(String)
public void generateForms(boolean enable, String useTtfFont, String formFontCharRange)
useTtfFont
- - UNICODE TTF font name to be used for form input. The name must appear in pd4fonts.properties or
specified via @font-face CSS at-ruleenable
- enables or disables the featureformFontCharRange
- - specifies ranges of characters to be embedded to the resulting PDF to cover possible user input,
e.g. "0-9a-zA-Z*.,:"useTTF(String)
public void generateMulticolumn(int columns, int span, boolean millimeters)
columns
- - number of columns per pagespan
- - space between the columnsmillimeters
- - if 'true' the gap is in millimeters, otherwise in pointspublic void useHttpRequest(javax.servlet.http.HttpServletRequest httpRequest, javax.servlet.http.HttpServletResponse httpResponse)
httpRequest
- actual HTTP requesthttpResponse
- actual HTTP responsepublic void addCustomResourceProvider(String customProviderClassName)
customProviderClassName
- name of class, derived from CustomResourceProvider. The class implementation must be in the classpathpublic void addCustomTagHandler(String customTagName, CustomTag implementation)
customTagName
- HTML tag nameimplementation
- an instance of implementation classpublic void generateBookmarksFromHeadings(boolean enable)
enable
- if set to true, PD4ML creates PDF bookmark tree structure derived from
<H1>-<H6> structure.generateBookmarksFromAnchors(boolean)
public void generateBookmarksFromAnchors(boolean enable)
enable
- if true, PD4ML creates PDF bookmarks from headings (
<a name="destination">Label</a> tags). If a label attribute is not defined, it uses
destination string as visible label.generateBookmarksFromHeadings(boolean)
public void setSessionID(String sessionID)
sessionID
- actual session IDpublic void overrideDocumentEncoding(String encoding)
encoding
- encoding name, matches Java encoding naming specifics (i.e. "ISO8859_1" instead of "ISO-8859-1")public void enableHyperlinks(boolean enable)
enable
- if false, PD4ML does not generate active hyperlinks in
resulting PDF. Default is "true"public void setPageHeader(String htmlCode, int heightPx) throws InvokeException
htmlCode
- header HTML codeheightPx
- header height (in screen pixels)InvokeException
- method called with invalid parameterspublic void setPageHeader(String htmlCode, int heightPx, String scope) throws InvokeException
htmlCode
- header HTML codeheightPx
- header height (in screen pixels)scope
- scope of pages to apply the headerInvokeException
- method called with invalid parameterspublic void setPageFooter(String htmlCode, int heightPx) throws InvokeException
htmlCode
- footer HTML codeheightPx
- footer height (in screen pixels)InvokeException
- method called with invalid parameterspublic void setPageFooter(String htmlCode, int heightPx, String scope) throws InvokeException
htmlCode
- footer HTML codeheightPx
- footer height (in screen pixels)scope
- scope of pages to apply the footerInvokeException
- method called with invalid parameterspublic void setWatermark(String htmlCode, float left, float top, float opacity, float angle, float scale, boolean screen, boolean print, String scope)
htmlCode
- watermark HTML codeleft
- horizintal positiontop
- vertical positionopacity
- watermark opacity from 0 to 1angle
- rotate watermark layout to a given degreescale
- watermark content scale from 0 to 1screen
- if true, watermarks screen viewprint
- if true, watermarks printed outputscope
- scope of pages to apply the watermarkpublic void setPageBackground(String htmlCode)
htmlCode
- background layout HTML codepublic void setPageBackground(String htmlCode, String scope)
htmlCode
- background layout HTML codescope
- scope of pages to apply the backgroundpublic void setPermissions(String password, int permissions)
password
- password. If is set to "empty", than no password assigned to document, only permissions.permissions
- an integer value according to PDF encryption specificationpublic void setCookie(String name, String value)
name
- cookie namevalue
- cookie valuepublic void setHttpOptions(String proxy, String basicAuthentication)
proxy
- null or HTTP proxy settings in "host:port" formatbasicAuthentication
- HTTP authentication pair in "login:password" formatpublic void addDocumentActionHandler(String actionType, String javaScript)
actionType
- "OpenAction", "DC" (document close), "WS" (will save), "DS" (did save), "WP" (will print) or "DP" (did print)javaScript
- handler codepublic void setPageSize(PageSize d, String scope)
d
- page dimensionsscope
- scope of pages to apply the sizepublic void setPageSize(PageSize d) throws InvokeException
d
- page PageSizeInvokeException
- when the specified page format is null or
does not fit to already defined page insetspublic PageSize getPageSize(int pageNum)
pageNum
- One-based indexed page number (the leading page is #1)public void setPageMargins(PageMargins margins)
margins
- page marginspublic void setPageMargins(PageMargins margins, String scope)
margins
- page marginsscope
- scope of pages to apply the marginspublic PageMargins getPageMargins(int pageNum, boolean imageGeneration)
pageNum
- One-based indexed page number (the leading page is #1)imageGeneration
- selects default margin settings. By imageGeneration=true by default there is no margins.public void setHtmlWidth(int width) throws InvokeException
width
- HTML width in screen pixelsInvokeException
- when the width is not a positive value great that 0.public void adjustHtmlWidth(boolean adjust)
adjust
- enables the adjustmentspublic void fitPageVertically(int align)
align
- content alignmentConstants.LEFT_ALIGN
,
Constants.CENTER_ALIGN
,
Constants.RIGHT_ALIGN
public short getFitPageVertically()
public final void setAuthorName(String name)
name
- author's namepublic final void setDocumentTitle(String title)
title
- document titlepublic void setInitialPageNumber(int initialPageNumber)
initialPageNumber
- page number of the first generated pagepublic final void addStyle(URL stylesheet, boolean overrideDocumentStyles) throws InvokeException
stylesheet
- of css stylesheetoverrideDocumentStyles
- if true, applies the stylesheet after styles defined in the document header.InvokeException
- too many styles addedpublic final void addStyle(String stylesheet, boolean overrideDocumentStyles) throws InvokeException
stylesheet
- stylesheet contentoverrideDocumentStyles
- if true, applies the stylesheet after styles defined in the document header.InvokeException
- too many styles addedpublic void injectHtml(String htmlSnippet, boolean prependBodyContent)
htmlSnippet
- HTML codeprependBodyContent
- if true, the HTML injected after opening <body> tag, otherwise right before closing
</body> tag.public void testTermination() throws ForcedTerminationException
ForcedTerminationException
- if terminatedpublic int getHeight(int width) throws IOException
width
- desired withs in screen pixelsIOException
- general IO exceptionpublic String getDocumentTitle() throws InvokeException
InvokeException
- if readHTML() is not invoked beforepublic void writePDF(OutputStream os) throws IOException
os
- output stream to write PDF document bytesIOException
- general IO exceptionpublic void writePDF(OutputStream os, String pdfFormat) throws IOException
pdfFormat
- Forces PD4ML to output either a regular PDF or a PDF format compliant with PDF/A specification.
PDF/A specification requires all used fonts to be embedded to the resulting document.
So the method call cannot guarantee the resulting doc is PDF/A, for example,
if TTF embedding is disabled or not configured.
To make sure a resulting document matches PDF/A requirements, request the last rendering status.os
- output stream to write generated PDF bytesIOException
- general IO exceptionConstants.PD4ML_PDFA_STATUS
,
getLastRenderInfo(String)
public void writeRTF(OutputStream os, boolean convertImagesToWMF) throws IOException
os
- output stream to write generated RTF document bytesconvertImagesToWMF
- converts images to bulky WMF format for compatibility with restricted RTF viewersIOException
- general IO exceptionpublic void setRenderingHints(Map hints)
hints
.
The existing values for all rendering hints are discarded and
the new set of known hints and values are initialized from the
specified Map
object.
Hint categories include controls for rendering quality and
overall time/quality trade-off in the rendering process.
Refer to the java.awt.RenderingHints
class for definitions of
some common keys and values.hints
- the image rendering hints to be setRenderingHints
public File renderAsImages(File dir, String fileNamePrefix, String format) throws IOException
dir
- target directoryfileNamePrefix
- file name prefix for image files. The prefix is followed by page number and file extension,
corresponds the requested image type.format
- image formatIOException
- general IO exceptionConstants.PNG24
,
Constants.PNG8
,
Constants.MULTIPAGE_TIFF
,
Constants.MULTIPAGE_TIFF_COMPRESSED
,
Constants.TIFF
,
Constants.TIFF_COMPRESSED
public byte[][] renderAsImages(String format) throws IOException
format
- image formatIOException
- general IO exceptionConstants.PNG24
,
Constants.PNG8
,
Constants.MULTIPAGE_TIFF
,
Constants.MULTIPAGE_TIFF_COMPRESSED
,
Constants.TIFF
,
Constants.TIFF_COMPRESSED
public BufferedImage[] renderAsImages() throws IOException
IOException
- general IO exceptionpublic String dump(int mode) throws IOException
mode
- dump verbosity flagsIOException
- general IO exceptionpublic void protectPhysicalUnitDimensions(boolean keepPhysicalUnitDimensions)
keepPhysicalUnitDimensions
- enable if truepublic static final float translateToPt(float mm)
mm
- value in millimeterspublic static final float predictScale(PageMargins pageMargins, PageSize pageSize, int userSpace)
pageMargins
- page marginspageSize
- page sizeuserSpace
- HTML width in screen pixelspublic static final int predictPageHeight(PageMargins pageMargins, PageSize pageSize, int userSpace)
pageMargins
- page marginspageSize
- page sizeuserSpace
- HTML width in screen pixelspublic void setDynamicData(Map<String,String> map)
map
- a set of key/value (String/String) pairs to dynamically substitute placeholders in HTML template (like "$[key]").
Key names "page", "total" and "title" are reserved for PDF headers and footers.public void setParam(String key, String value)
key
- parameter namevalue
- parameter valuepublic Object getLastRenderInfo(String key) throws ForcedTerminationException
key
- - one of the currently supported keys: "pd4ml.document.height.px", "pd4ml.right.edge.px" or "pd4ml.total.pages".ForcedTerminationException
- if terminate()
invoked beforeConstants.PD4ML_DOCUMENT_HEIGHT_PX
,
Constants.PD4ML_RIGHT_EDGE_PX
,
Constants.PD4ML_TOTAL_PAGES
public void outputRange(String description)
description
- a string with output rules. Currently allows to limit a scope of generated pages. Examples: "2+" - skip the first page,
"1-2" - output only the first and the second pages, "even" or "odd" - it is obvious. The rules may
be combined: "3-7,odd"public void monitorProgressWith(ProgressListener listener)
listener
- receiver of progress update messagespublic void addMetadata(String key, String value, boolean hide)
key
- a unique name, which must not be one of the standard property names Title, Author, Subject,
Keywords, Creator, Producer, CreationDate, ModDate and Trappedvalue
- data itselfhide
- makes the metadata not appear in the PDF document properties dialog of Acroreadpublic void applyKerning(boolean enable)
enable
- - enables the featurepublic void enableLigatures(boolean enable)
enable
- - enables the featurepublic Object getCache()
setCache(Object)
public void setCache(Object fontCache)
fontCache
- cache object returned by other PD4ML instancegetCache()
public void asyncResourceLoader(int threadPoolSize)
threadPoolSize
- loader thread pool size. If the value is negative, it it does not limit the pool size:
creates new threads as needed, but will reuse previously constructed threads when they are available.Revision 4.1.0 / 20201216-0554