Package org.apache.batik.apps.rasterizer
Class SVGConverter
- java.lang.Object
-
- org.apache.batik.apps.rasterizer.SVGConverter
-
public class SVGConverter extends java.lang.ObjectThis application can be used to convert SVG images to raster images.
Possible result raster image formats are PNG, JPEG, TIFF, and PDF. The Batik Transcoder API is used to execute the conversion. FOP is needed to be able to transcode to the PDF format
The source has to be list of files or URL (set by thesetSourcesmethod).
The destination can be:- unspecified. In that case, only file sources can be converted and a file in the same directory as the source will be created.
- a directory, set by the
setDstmethod. In that case, the output files are created in that destination directory - a file. In case there is a single
source, the destination can be a single named file
(set with the
setDstmethod.)
There are a number of options which control the way the image is converted to the destination format:- destinationType: controls the type of conversion which should be done.
see the
DestinationTypedocumentation. - width/height: they control the desired width and height, in user space, for the output image.
- maxWidth/maxHeight: control the maximum width and height, in user space, of the output image.
- area: controls the specific sub-area of the image which should be rendered.
- backgroundColor: controls the color which is used to fill the background before rendering the image
- quality: relevant only for JPEG destinations, this controls the encoding quality.
- indexed: relevant only for PNG, controls the number of bits used in writting of a palletized files.
- mediaType: controls the CSS media, or list of media, for which the image should be rendered.
- alternate: controls the alternate CSS stylesheet to activate, if any.
- language: controls the user language with which the SVG document should be converted.
- userStylesheet: defines the user stylesheet to apply to SVG documents in addition to other stylesheets referenced by or embedded in the SVG documents.
- pixelUnitToMillimeter: defines the size of a pixel in millimeters to use when processing the SVG documents.
- Version:
- $Id: SVGConverter.java 1871084 2019-12-09 12:24:18Z ssteiner $
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classSVGConverter.SVGFileFilterConvenience class to filter svg files
-
Field Summary
Fields Modifier and Type Field Description protected java.lang.StringallowedScriptTypesSet of allowed script types.protected booleanallowExternalResourcesprotected java.lang.StringalternateStylesheetAlternate stylesheet for which should be applied to the SVGprotected java.awt.geom.Rectangle2DareaOutput AOI area.protected java.awt.ColorbackgroundColorBackground color for the output images.protected booleanconstrainScriptOriginControls whether scripts can only have the same origin as the document which references them.protected SVGConverterControllercontrollerControls some aspects of the converter's operation, such as whether or not it should proceed in some error situations.protected static floatDEFAULT_HEIGHTDefault heightprotected static floatDEFAULT_QUALITYDefault quality value.protected static DestinationTypeDEFAULT_RESULT_TYPEDefault result typeprotected static floatDEFAULT_WIDTHDefault widthprotected java.lang.StringdefaultFontFamilyDefault value for the font-family when it is unspecifiedprotected DestinationTypedestinationTypeResult typeprotected java.io.FiledstDestination image path.static java.lang.StringERROR_CANNOT_ACCESS_TRANSCODERstatic java.lang.StringERROR_CANNOT_COMPUTE_DESTINATIONstatic java.lang.StringERROR_CANNOT_OPEN_OUTPUT_FILEstatic java.lang.StringERROR_CANNOT_OPEN_SOURCEstatic java.lang.StringERROR_CANNOT_READ_SOURCEstatic java.lang.StringERROR_CANNOT_USE_DST_FILEstatic java.lang.StringERROR_NO_SOURCES_SPECIFIEDstatic java.lang.StringERROR_OUTPUT_NOT_WRITEABLEstatic java.lang.StringERROR_SOURCE_SAME_AS_DESTINATIONstatic java.lang.StringERROR_UNABLE_TO_CREATE_OUTPUT_DIRstatic java.lang.StringERROR_WHILE_RASTERIZING_FILEprotected booleanexecuteOnloadExecute the 'onload' scripts flagprotected java.util.ListfilesContents offilesetelements.protected floatheightOutput image height.protected intindexedShould output Image be indexed .protected java.lang.StringlanguageLanguageprotected floatmaxHeightMaximum output image height.protected static floatMAXIMUM_QUALITYMaximum quality valueprotected floatmaxWidthMaximum output image width.protected java.lang.StringmediaTypeMedia type for which the SVG image should be renderedprotected floatpixelUnitToMillimeterMillimeters Per Pixelprotected floatqualityOutput image quality.protected booleansecurityOffControls whether scripts should be run securely or notprotected floatsnapshotTimeDocument time to seek to.protected java.util.ListsourcesSources files or URLsprotected static java.lang.StringSVG_EXTENSIONSVG file extensionprotected java.lang.StringuserStylesheetUser stylesheetprotected booleanvalidateValidation flagprotected floatwidthOutput image width.
-
Constructor Summary
Constructors Constructor Description SVGConverter()SVGConverter(SVGConverterController controller)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected java.util.ListcomputeDstFiles(java.util.List sources)Populates a vector with destination files names computed from the names of the files in the sources vector and the value of the dst propertyprotected java.util.ListcomputeSources()Populates a vector with the set of SVG files from the srcDir if it is not null and with the sources (files or URLs) if any.protected java.util.MapcomputeTranscodingHints()Computes the set of transcoding hints to use for the operationprotected voidcreateOutputDir(java.io.File output)Creates directories for output files if needed.voidexecute()Starts the conversion process.java.lang.StringgetAllowedScriptTypes()Returns the list of allowed script types.java.lang.StringgetAlternateStylesheet()java.awt.geom.Rectangle2DgetArea()java.awt.ColorgetBackgroundColor()booleangetConstrainScriptOrigin()Returns whether scripts can only be loaded from the same origin as the documents referencing them.java.lang.StringgetDefaultFontFamily()protected java.lang.StringgetDestinationFile(java.lang.String file)Get the name of the result image file.DestinationTypegetDestinationType()java.io.FilegetDst()booleangetExecuteOnload()Returns true if the scripts attached to the DOM using 'onload' event attribute is going to be executed before rasterizing, false otherwise.java.lang.String[]getFileNRef(java.lang.String fileName)floatgetHeight()intgetIndexed()java.lang.StringgetLanguage()floatgetMaxHeight()floatgetMaxWidth()java.lang.StringgetMediaType()floatgetPixelUnitToMillimeter()floatgetQuality()booleangetSecurityOff()Returns whether or not scripts will be run securelyfloatgetSnapshotTime()Returns the document to to seek to before rasterizing.java.util.ListgetSources()java.lang.StringgetUserStylesheet()booleangetValidate()floatgetWidth()protected booleanisFile(java.io.File f)Returns true if f is a File.protected booleanisWriteable(java.io.File file)Checks if the application is allowed to write to the file.voidsetAllowedScriptTypes(java.lang.String allowedScriptTypes)Sets the set of allowed script types (i.e., the set of possible values for the type attribute in the <script> element), as a comma separated list of allowed values.voidsetAlternateStylesheet(java.lang.String alternateStylesheet)Sets thealternateStyleSheetvalue.voidsetArea(java.awt.geom.Rectangle2D area)Sets theareaas a Rectangle.voidsetBackgroundColor(java.awt.Color backgroundColor)Sets thebackgroundColorvalue.voidsetConstrainScriptOrigin(boolean constrainScriptOrigin)Sets whether scripts should only be loaded from the same location as the documents referencing them.voidsetDefaultFontFamily(java.lang.String defaultFontFamily)Sets thedefaultFontFamilyvalue.voidsetDestinationType(DestinationType destinationType)Sets thedestinationTypeattribute value.voidsetDst(java.io.File dst)When converting a single source, dst can be a file.voidsetExecuteOnload(boolean b)Sets whether or not scripts attached to the DOM using 'onload' event attribute must be executed before rasterizing.voidsetHeight(float height)In less than or equal to zero, the height is not constrained on the output image.voidsetIndexed(int bits)Tells the PNG encoder to reduce the image to 256 colors, so the PNG file is indexed.voidsetLanguage(java.lang.String language)Sets the user language.voidsetMaxHeight(float height)If less than or equal to zero, the maximum height does not have any effect on the output image.voidsetMaxWidth(float width)If less than or equal to zero, the maximum width does not have any effect on the output image.voidsetMediaType(java.lang.String mediaType)Sets themediaTypevalue.voidsetPixelUnitToMillimeter(float pixelUnitToMillimeter)Sets the millimeters per pixel constant.voidsetQuality(float quality)Sets the JPEG encoding quality.voidsetSecurityOff(boolean securityOff)Sets whether or not scripts should be run securelyvoidsetSnapshotTime(float t)Sets the document time to seek to before rasterizing.voidsetSources(java.lang.String[] sources)Sets the list of individual SVG sources.voidsetUserStylesheet(java.lang.String userStylesheet)Sets the user stylesheet.voidsetValidate(boolean validate)Defines whether or not input sources should be validated in the conversion processvoidsetWidth(float width)In less than or equal to zero, the width is not constrained on the output image.protected voidtranscode(SVGConverterSource inputFile, java.io.File outputFile, Transcoder transcoder)Converts the input image to the result image.
-
-
-
Field Detail
-
ERROR_NO_SOURCES_SPECIFIED
public static final java.lang.String ERROR_NO_SOURCES_SPECIFIED
- See Also:
- Constant Field Values
-
ERROR_CANNOT_COMPUTE_DESTINATION
public static final java.lang.String ERROR_CANNOT_COMPUTE_DESTINATION
- See Also:
- Constant Field Values
-
ERROR_CANNOT_USE_DST_FILE
public static final java.lang.String ERROR_CANNOT_USE_DST_FILE
- See Also:
- Constant Field Values
-
ERROR_CANNOT_ACCESS_TRANSCODER
public static final java.lang.String ERROR_CANNOT_ACCESS_TRANSCODER
- See Also:
- Constant Field Values
-
ERROR_SOURCE_SAME_AS_DESTINATION
public static final java.lang.String ERROR_SOURCE_SAME_AS_DESTINATION
- See Also:
- Constant Field Values
-
ERROR_CANNOT_READ_SOURCE
public static final java.lang.String ERROR_CANNOT_READ_SOURCE
- See Also:
- Constant Field Values
-
ERROR_CANNOT_OPEN_SOURCE
public static final java.lang.String ERROR_CANNOT_OPEN_SOURCE
- See Also:
- Constant Field Values
-
ERROR_OUTPUT_NOT_WRITEABLE
public static final java.lang.String ERROR_OUTPUT_NOT_WRITEABLE
- See Also:
- Constant Field Values
-
ERROR_CANNOT_OPEN_OUTPUT_FILE
public static final java.lang.String ERROR_CANNOT_OPEN_OUTPUT_FILE
- See Also:
- Constant Field Values
-
ERROR_UNABLE_TO_CREATE_OUTPUT_DIR
public static final java.lang.String ERROR_UNABLE_TO_CREATE_OUTPUT_DIR
- See Also:
- Constant Field Values
-
ERROR_WHILE_RASTERIZING_FILE
public static final java.lang.String ERROR_WHILE_RASTERIZING_FILE
- See Also:
- Constant Field Values
-
SVG_EXTENSION
protected static final java.lang.String SVG_EXTENSION
SVG file extension- See Also:
- Constant Field Values
-
DEFAULT_QUALITY
protected static final float DEFAULT_QUALITY
Default quality value. A value of -1 means disabled.- See Also:
- Constant Field Values
-
MAXIMUM_QUALITY
protected static final float MAXIMUM_QUALITY
Maximum quality value- See Also:
- Constant Field Values
-
DEFAULT_RESULT_TYPE
protected static final DestinationType DEFAULT_RESULT_TYPE
Default result type
-
DEFAULT_WIDTH
protected static final float DEFAULT_WIDTH
Default width- See Also:
- Constant Field Values
-
DEFAULT_HEIGHT
protected static final float DEFAULT_HEIGHT
Default height- See Also:
- Constant Field Values
-
destinationType
protected DestinationType destinationType
Result type
-
height
protected float height
Output image height.
-
width
protected float width
Output image width.
-
maxHeight
protected float maxHeight
Maximum output image height.
-
maxWidth
protected float maxWidth
Maximum output image width.
-
quality
protected float quality
Output image quality.
-
indexed
protected int indexed
Should output Image be indexed .
-
area
protected java.awt.geom.Rectangle2D area
Output AOI area.
-
language
protected java.lang.String language
Language
-
userStylesheet
protected java.lang.String userStylesheet
User stylesheet
-
pixelUnitToMillimeter
protected float pixelUnitToMillimeter
Millimeters Per Pixel
-
validate
protected boolean validate
Validation flag
-
executeOnload
protected boolean executeOnload
Execute the 'onload' scripts flag
-
snapshotTime
protected float snapshotTime
Document time to seek to.
-
allowedScriptTypes
protected java.lang.String allowedScriptTypes
Set of allowed script types.
-
constrainScriptOrigin
protected boolean constrainScriptOrigin
Controls whether scripts can only have the same origin as the document which references them.
-
allowExternalResources
protected boolean allowExternalResources
-
securityOff
protected boolean securityOff
Controls whether scripts should be run securely or not
-
sources
protected java.util.List sources
Sources files or URLs
-
dst
protected java.io.File dst
Destination image path. Can be a file (for single source) or a directory
-
backgroundColor
protected java.awt.Color backgroundColor
Background color for the output images.
-
mediaType
protected java.lang.String mediaType
Media type for which the SVG image should be rendered
-
defaultFontFamily
protected java.lang.String defaultFontFamily
Default value for the font-family when it is unspecified
-
alternateStylesheet
protected java.lang.String alternateStylesheet
Alternate stylesheet for which should be applied to the SVG
-
files
protected java.util.List files
Contents offilesetelements.
-
controller
protected SVGConverterController controller
Controls some aspects of the converter's operation, such as whether or not it should proceed in some error situations. SeeSVGConverterController
-
-
Constructor Detail
-
SVGConverter
public SVGConverter()
-
SVGConverter
public SVGConverter(SVGConverterController controller)
-
-
Method Detail
-
setDestinationType
public void setDestinationType(DestinationType destinationType)
Sets thedestinationTypeattribute value. Should not be null.
-
getDestinationType
public DestinationType getDestinationType()
-
setHeight
public void setHeight(float height)
In less than or equal to zero, the height is not constrained on the output image. The height is in user space.
-
getHeight
public float getHeight()
-
setWidth
public void setWidth(float width)
In less than or equal to zero, the width is not constrained on the output image. The width is in user space.
-
getWidth
public float getWidth()
-
setMaxHeight
public void setMaxHeight(float height)
If less than or equal to zero, the maximum height does not have any effect on the output image. The maximum height is in user space.
-
getMaxHeight
public float getMaxHeight()
-
setMaxWidth
public void setMaxWidth(float width)
If less than or equal to zero, the maximum width does not have any effect on the output image. The maximum width is in user space.
-
getMaxWidth
public float getMaxWidth()
-
setQuality
public void setQuality(float quality) throws java.lang.IllegalArgumentExceptionSets the JPEG encoding quality. The value should be strictly less than 1. If the value is less than zero, then the maximum encoding quality is used.- Throws:
java.lang.IllegalArgumentException
-
getQuality
public float getQuality()
-
setIndexed
public void setIndexed(int bits) throws java.lang.IllegalArgumentExceptionTells the PNG encoder to reduce the image to 256 colors, so the PNG file is indexed.- Throws:
java.lang.IllegalArgumentException
-
getIndexed
public int getIndexed()
-
setLanguage
public void setLanguage(java.lang.String language)
Sets the user language. If the value is null, then the default (seeUserAgent.getLanguages()) is used.
-
getLanguage
public java.lang.String getLanguage()
-
setUserStylesheet
public void setUserStylesheet(java.lang.String userStylesheet)
Sets the user stylesheet. May be null.
-
getUserStylesheet
public java.lang.String getUserStylesheet()
-
setPixelUnitToMillimeter
public void setPixelUnitToMillimeter(float pixelUnitToMillimeter)
Sets the millimeters per pixel constant. A negative value will cause the default value (seeUserAgent.getPixelUnitToMillimeter()) to be used.
-
getPixelUnitToMillimeter
public float getPixelUnitToMillimeter()
-
setArea
public void setArea(java.awt.geom.Rectangle2D area)
Sets theareaas a Rectangle. This value can be null in which case the whole image will be rendered. If the area is not null, then only the portion of the image it defines will be rendered.
-
getArea
public java.awt.geom.Rectangle2D getArea()
-
setSources
public void setSources(java.lang.String[] sources)
Sets the list of individual SVG sources. The strings can be either URLs or file names. Note that invalid sources (e.g., read-protected files or invalid URLs) will causeSVGConverterExceptionsto be thrown during the transcoding process (seeexecute());
-
getSources
public java.util.List getSources()
-
setDst
public void setDst(java.io.File dst)
When converting a single source, dst can be a file. Othewise, it should be a directory.
-
getDst
public java.io.File getDst()
-
setBackgroundColor
public void setBackgroundColor(java.awt.Color backgroundColor)
Sets thebackgroundColorvalue. This can be null in which case no color will be used to fill the background before rendering this SVG image.
-
getBackgroundColor
public java.awt.Color getBackgroundColor()
-
setMediaType
public void setMediaType(java.lang.String mediaType)
Sets themediaTypevalue. This value controls the CSS media for which the image should be rendered. It can be null, in which case no specific media selectors will apply. If it is not null, it can contain space separated values of the medias for which the image should be rendered. For example, "screen", "print" or "scree projection" are valid values.
-
getMediaType
public java.lang.String getMediaType()
-
setDefaultFontFamily
public void setDefaultFontFamily(java.lang.String defaultFontFamily)
Sets thedefaultFontFamilyvalue. This value controls the default value for the font-family CSS property when that property is unspecified.
-
getDefaultFontFamily
public java.lang.String getDefaultFontFamily()
-
setAlternateStylesheet
public void setAlternateStylesheet(java.lang.String alternateStylesheet)
Sets thealternateStyleSheetvalue. This value controls the CSS alternate stylesheet to select in the rendered SVG file(s). It may be null, in which case no alternate stylesheet will be selected.
-
getAlternateStylesheet
public java.lang.String getAlternateStylesheet()
-
setValidate
public void setValidate(boolean validate)
Defines whether or not input sources should be validated in the conversion process
-
getValidate
public boolean getValidate()
-
setExecuteOnload
public void setExecuteOnload(boolean b)
Sets whether or not scripts attached to the DOM using 'onload' event attribute must be executed before rasterizing.- Parameters:
b- true means scripts will be executed
-
getExecuteOnload
public boolean getExecuteOnload()
Returns true if the scripts attached to the DOM using 'onload' event attribute is going to be executed before rasterizing, false otherwise.
-
setSnapshotTime
public void setSnapshotTime(float t)
Sets the document time to seek to before rasterizing.- Parameters:
t- the document time, in seconds
-
getSnapshotTime
public float getSnapshotTime()
Returns the document to to seek to before rasterizing.
-
setAllowedScriptTypes
public void setAllowedScriptTypes(java.lang.String allowedScriptTypes)
Sets the set of allowed script types (i.e., the set of possible values for the type attribute in the <script> element), as a comma separated list of allowed values.
-
getAllowedScriptTypes
public java.lang.String getAllowedScriptTypes()
Returns the list of allowed script types.- See Also:
setAllowedScriptTypes(java.lang.String)
-
setConstrainScriptOrigin
public void setConstrainScriptOrigin(boolean constrainScriptOrigin)
Sets whether scripts should only be loaded from the same location as the documents referencing them.
-
getConstrainScriptOrigin
public boolean getConstrainScriptOrigin()
Returns whether scripts can only be loaded from the same origin as the documents referencing them.
-
setSecurityOff
public void setSecurityOff(boolean securityOff)
Sets whether or not scripts should be run securely
-
getSecurityOff
public boolean getSecurityOff()
Returns whether or not scripts will be run securely
-
isFile
protected boolean isFile(java.io.File f)
Returns true if f is a File.fis found to be a file if it exists and is a file. If it does not exist, it is declared to be a file if it has the same extension as the DestinationType.
-
execute
public void execute() throws SVGConverterExceptionStarts the conversion process.- Throws:
SVGConverterException- thrown if parameters are not set correctly.
-
computeDstFiles
protected java.util.List computeDstFiles(java.util.List sources) throws SVGConverterExceptionPopulates a vector with destination files names computed from the names of the files in the sources vector and the value of the dst property- Throws:
SVGConverterException
-
computeSources
protected java.util.List computeSources() throws SVGConverterExceptionPopulates a vector with the set of SVG files from the srcDir if it is not null and with the sources (files or URLs) if any.- Throws:
SVGConverterException
-
getFileNRef
public java.lang.String[] getFileNRef(java.lang.String fileName)
-
computeTranscodingHints
protected java.util.Map computeTranscodingHints()
Computes the set of transcoding hints to use for the operation
-
transcode
protected void transcode(SVGConverterSource inputFile, java.io.File outputFile, Transcoder transcoder) throws SVGConverterException
Converts the input image to the result image. with the given transcoder. If a failure happens, the controller is notified and decides whether to proceed or not. If it decides to proceed, the converter will continue processing other files. Otherwise, it will throw an exception.- Throws:
SVGConverterException
-
getDestinationFile
protected java.lang.String getDestinationFile(java.lang.String file)
Get the name of the result image file.This method modifies the result filename, it changes the existing suffix to correspong the result file type. It also adds the suffix if the file doesn't have one.
- Parameters:
file- Result file name as a String object.- Returns:
- Name of the file. The directory of the file is not returned. The returned string is empty if the parameter is not a file.
-
createOutputDir
protected void createOutputDir(java.io.File output) throws SVGConverterExceptionCreates directories for output files if needed.- Parameters:
output- Output file with path.- Throws:
SVGConverterException- Output directory doesn't exist and it can't be created.
-
isWriteable
protected boolean isWriteable(java.io.File file)
Checks if the application is allowed to write to the file.- Parameters:
file- File to be checked.- Returns:
trueif the file is writeable andfalseotherwise.
-
-