Class PDFCanvas

  • All Implemented Interfaces:
    java.lang.Cloneable, PDFDrawable

    public class PDFCanvas
    extends java.lang.Object
    implements PDFDrawable

    This class represents a the visible content of a page, annotation or similar. Basically everything which is displayed in a document - pages, annotations, form fields and so on - has a Canvas at it's heart. In the PDF spec this is known as a "Content Stream".

    Using a Canvas is very similar to using a PDFPage - it's created, it's width is specified and content is drawn onto it. Once created, a Canvas can be used as the basis for a PDFImage or PDFPattern and applied to a page.

    Since:
    2.0
    • Constructor Summary

      Constructors 
      Constructor Description
      PDFCanvas​(float width, float height)
      Create a new blank canvas of the specified width and height
      PDFCanvas​(float width, float height, float opacity)
      Create a new blank canvas of the specified width and height and with the specified opacity.
      PDFCanvas​(float width, float height, float opacity, java.lang.String blendmode)
      Create a new blank canvas of the specified width and height and with the specified opacity.
      PDFCanvas​(java.lang.String pattern, float opacity)
      Load the specified resource as a canvas.
      PDFCanvas​(PDFCanvas canvas)
      Create a new Canvas that's a clone of the specified PDFCanvas.
      PDFCanvas​(PDFPage page)
      Create a new Canvas that's a clone of the specified PDFPage.
    • Method Summary

      All Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      void beginTag​(java.lang.String tag, java.util.Map<java.lang.String,​java.lang.Object> atts)
      Open a structural tag on this page.
      void clipCircle​(float x, float y, float radius)
      Set the clipping area to a circle centered on x, y with a radius of radius.
      void clipEllipse​(float x1, float y1, float x2, float y2)
      Set the clipping area to the ellipse inside the specified rectangle.
      void clipPolygon​(float[] x, float[] y)
      Set the clipping area to a polygon.
      void clipRectangle​(float x1, float y1, float x2, float y2)
      Set the clipping area to the rectangle which runs through the two corners x1,y1 and x2,y2.
      void clipRoundedRectangle​(float x1, float y1, float x2, float y2, float r)
      Set the clipping area to a rectangle with rounded corners which runs through the two corners x1,y1 and x2,y2.
      void clipShape​(java.awt.Shape shape)
      Clip a Shape
      protected java.lang.Object clone()  
      java.awt.Graphics2D createGraphics​(PDF pdf)
      Return a Graphics2D implementation that renders to this PDFCanvas.
      void drawCanvas​(PDFCanvas canvas, float x1, float y1, float x2, float y2)
      Draw a PDFCanvas at the specified position on the page.
      void drawCircle​(float x, float y, float radius)
      Draw a circle centered on x, y with a radius of radius.
      void drawCircleArc​(float x, float y, float radius, float start, float end)
      Draw an arc of the circle centered on x,y with the specified radius.
      void drawEllipse​(float x1, float y1, float x2, float y2)
      Draw an ellipse inside the specified rectangle.
      void drawEllipseArc​(float x1, float y1, float x2, float y2, float start, float end)
      Draw an ellipse arc inside the specified rectangle.
      void drawGlyphVector​(PDFGlyphVector gv, float x, float y)
      Draw a PDFGlyphVector onto the canvas.
      void drawImage​(PDFImage image, float x1, float y1, float x2, float y2)
      Draw a PDFImage at the specified position on the page
      void drawLayoutBox​(LayoutBox box, float x, float y)
      Draw a LayoutBox at the specified position on the page
      void drawLine​(float x1, float y1, float x2, float y2)
      Draw a line from x1,y1 to x2,y2.
      void drawPolygon​(float[] x, float[] y)
      Draw a polygon.
      void drawRectangle​(float x1, float y1, float x2, float y2)
      Draw a rectangle through the two corners x1,y1 and x2,y2.
      void drawRoundedRectangle​(float x1, float y1, float x2, float y2, float r)
      Draw a rectangle with rounded corners through the two corners x1,y1 and x2,y2.
      void drawShape​(java.awt.Shape shape)
      Draw a Shape.
      void endTag()
      Close a structural tag on this page.
      void flush()
      This method flushes any operations that have been written to the canvas, and closes the stream for further writes.
      float[] getBox()
      Return the canvas box, as set in the constructor or by setBox(float, float, float, float)
      java.awt.color.ColorSpace getDefaultColorSpace​(int components)
      Return the ColorSpace used by this Drawable to anchor device-dependent colors to a profile.
      float getHeight()
      Return the width of the canvas
      OptionalContentDescriptor getOptionalContentDescriptor()
      Return the OptionalContentDescriptor previously set by setOptionalContentDescriptor(org.faceless.pdf2.OptionalContentDescriptor)
      java.awt.geom.AffineTransform getTransform()
      Return a copy of the transform currently applied to the PDFCanvas
      float getWidth()
      Return the width of the canvas
      XMP getXMP()
      Return an XMP Metadata object representing any XML metadata associated with this object
      boolean pathArc​(float width, float height, float start, float end)
      Continue the open path in an arc to the specified position.
      boolean pathBezier​(float cx1, float cy1, float cx2, float cy2, float x, float y)
      Continue the open path in a bezier curve to the specified position.
      void pathCancel()
      Cancel the current path
      void pathClip()
      Close the path and set the "clipping area" of the page to be the intersection of the current clipping area and the shape defined by this path.
      void pathClipAndPaint()
      Close and paint the path as described in pathPaint(), then set the clipping area to the same are as described in pathClip()
      void pathClose()
      Close the path by drawing a straight line back to its beginning.
      boolean pathLine​(float x, float y)
      Continue the open path in a straight line to the specified position.
      void pathMove​(float x, float y)
      Start a new path at the specified position.
      void pathPaint()
      Close and paint the path.
      boolean pathShape​(java.awt.Shape shape)
      Add the path specified by a Shape to the Canvas
      void putLiteral​(java.lang.String key, java.lang.String tokens)
      Put a literal token sequnce.
      void rawWrite​(java.lang.String data)
      Write raw PDF commands to the canvas.
      void restore()
      Restore the state that was saved with the last call to save()
      void rotate​(float x, float y, double ang)
      Rotate the canvas around the specified point by the specified number of degrees.
      void save()
      Save the state of this page.
      void setBox​(float x1, float y1, float x2, float y2)
      Set the canvas box.
      void setDefaultColorSpace​(int components, java.awt.color.ColorSpace cs)
      Set the ColorSpace to use to anchor device-dependent colors on this Drawable, as described by PDFDrawable.getDefaultColorSpace(int).
      void setMask​(PDFCanvas mask, boolean alpha)
      Set the mask which will be applied when this canvas is drawn to a parent PDFCanvas or PDFPage.
      void setMetaData​(java.lang.String xmldata)
      Set the XML metadata associated with this object.
      void setOptionalContentDescriptor​(OptionalContentDescriptor descriptor)
      Set the OptionalContentDescriptor on this canvas, which can be a OptionalContentLayer or a logical expression containing several layers.
      void setPDF​(PDF pdf)
      "Attach" this PDFCanvas to the specified PDF.
      void setStyle​(PDFStyle style)
      Set the style for this Canvas
      void setWatermarkOrBackground​(boolean screen, boolean print)
      Deprecated.
      this method hasn't worked for some time.
      java.lang.String toString()  
      void transform​(double m00, double m10, double m01, double m11, double m02, double m12)
      Concatenate an AffineTransform to the canvases current transform.
      void transform​(java.awt.geom.AffineTransform transform)
      Concatenate an AffineTransform to the canvases current transform.
      • Methods inherited from class java.lang.Object

        equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Constructor Detail

      • PDFCanvas

        public PDFCanvas​(float width,
                         float height)
        Create a new blank canvas of the specified width and height
        Parameters:
        width - the canvas width in points
        height - the canvas height in points
      • PDFCanvas

        public PDFCanvas​(float width,
                         float height,
                         float opacity)
        Create a new blank canvas of the specified width and height and with the specified opacity. The Canvas will form a transparency group of the specified opacity.
        Parameters:
        width - the canvas width in points
        height - the canvas height in points
        opacity - the opacity of the canvas - from 1 (opaque) to 0 (transparent)
        Since:
        2.7.2
      • PDFCanvas

        public PDFCanvas​(float width,
                         float height,
                         float opacity,
                         java.lang.String blendmode)
        Create a new blank canvas of the specified width and height and with the specified opacity. The Canvas will form a transparency group of the specified opacity.
        Parameters:
        width - the canvas width in points
        height - the canvas height in points
        opacity - the opacity of the canvas - from 1 (opaque) to 0 (transparent)
        blendmode - the BlendMode of the canvas - see PDFStyle.setBlendMode(java.lang.String) for valid values
        Since:
        2.22
      • PDFCanvas

        public PDFCanvas​(PDFCanvas canvas)
        Create a new Canvas that's a clone of the specified PDFCanvas. Since 2.2 the canvas passed in must have had flush() called on it first, otherwise an Exception is thrown.
        Since:
        2.0
      • PDFCanvas

        public PDFCanvas​(java.lang.String pattern,
                         float opacity)
                  throws java.util.MissingResourceException
        Load the specified resource as a canvas.
        Parameters:
        pattern - the name of the resource to load, eg "stamp.stencil.Confidential"
        opacity - the opacity to apply to the canvas
        Throws:
        java.util.MissingResourceException
        Since:
        2.0
    • Method Detail

      • setPDF

        public void setPDF​(PDF pdf)
        "Attach" this PDFCanvas to the specified PDF. Although this doesn't do anything specific to the output, it allows some optimisations to be made regarding shared resources, by associating a PDF canvas with the PDF that will eventually reference it.
        Since:
        2.26.5
      • getDefaultColorSpace

        public java.awt.color.ColorSpace getDefaultColorSpace​(int components)
        Description copied from interface: PDFDrawable

        Return the ColorSpace used by this Drawable to anchor device-dependent colors to a profile. For example, the ColorSpace returned by getDefaultColorSpace(3) is used by all "Device RGB" colors on the page, effectively turning them into calibrated colors.

        The PDF API automatically sets a calibrated sRGB ColorSpace as the ColorSpace for all DeviceRGB content on the page. Unlike the use of "Output Intents" on the OutputProfile class, multiple ColorSpaces can be set, one each for Gray, RGB, and CMYK. This is a cheap way to convert pages containing both DeviceRGB and DeviceCMYK to using calibrated colors.

        Specified by:
        getDefaultColorSpace in interface PDFDrawable
        Parameters:
        components - identifies the Default ColorSpace we're requesting - valid values are 1 for Gray, 3 for RGB or 4 for CMYK.
        Returns:
        the Default ColorSpace requested, or null if none is set.
      • setDefaultColorSpace

        public void setDefaultColorSpace​(int components,
                                         java.awt.color.ColorSpace cs)
        Description copied from interface: PDFDrawable
        Set the ColorSpace to use to anchor device-dependent colors on this Drawable, as described by PDFDrawable.getDefaultColorSpace(int).
        Specified by:
        setDefaultColorSpace in interface PDFDrawable
        Parameters:
        components - identifies the Default ColorSpace to set - valid values are 1 for Gray, 3 for RGB or 4 for CMYK.
        cs - the ColorSpace to set, which must be either null (to delete the existing value) or a ColorSpace of a type that matches the "components" parameter.
      • flush

        public void flush()

        This method flushes any operations that have been written to the canvas, and closes the stream for further writes. Canvases must be flushed before they can be cloned (by calling the PDFCanvas(PDFCanvas) constructor).

        After a canvas is flushed, it can still be written to, but this will cause the canvas to be uncompressed and recompressed, which isn't a very efficient operation in terms of time or memory and is therefore best avoided.

        It is a good idea to flush a PDFCanvas after you've finished modifying it, as the library can manage them more efficiently if it knows you're not expecting to write to them again. In particular once they're flushed they may be written to disk (or similar) by a Cache

        Specified by:
        flush in interface PDFDrawable
        Throws:
        java.lang.IllegalStateException - if the canvas is incomplete - you have an open path or a save() without a matching restore().
        Since:
        2.2
      • setMask

        public void setMask​(PDFCanvas mask,
                            boolean alpha)

        Set the mask which will be applied when this canvas is drawn to a parent PDFCanvas or PDFPage. The supplied mask should be the same size as this PDFCanvas, or it may be null to remove the mask completely. The mask must be set to the desired value before the canvas is drawn to a parent page or canvas.

        If alpha is true the mask canvas will be interpreted as an "alpha" mask - the alpha channel will be used to determine how much of this canvas to apply, with transparent areas transparent, and opaque areas opaque.

        If alpha is false, the mask canvas will be interprected as a "luminance" mask. The grayscale value of each point will be used to determine opacity - white being fully opaque, black being fully transparent. The supplied canvas is assumed to be drawn over a black background, so transparency is not a factor in this calculation.

        Parameters:
        mask - the mask canvas, or null to use no mask
        alpha - is mask is not null, a value of true to use it as an alpha-mask, or false for a luminance mask
        Since:
        2.23.3
      • setBox

        public void setBox​(float x1,
                           float y1,
                           float x2,
                           float y2)
        Set the canvas box. This can be used to change the width or height of the canvas after creation if required.
        Since:
        2.23.3
      • rawWrite

        public void rawWrite​(java.lang.String data)
        Write raw PDF commands to the canvas. This is for advanced users only, but does allow those intimately familiar with the PDF specification to perform some of the more esoteric actions that aren't directly supported by the PDF library. Using this method it is easy to create invalid PDF documents, so use with caution.
        Specified by:
        rawWrite in interface PDFDrawable
        Parameters:
        data - the PDF operations to write to the stream, for instance "/Perceptual ri" to set the RenderingIntent. Line breaks will be added before and after the specified string.
        Since:
        2.1.2
      • getWidth

        public float getWidth()
        Return the width of the canvas
        Since:
        2.0
      • getHeight

        public float getHeight()
        Return the width of the canvas
        Since:
        2.0
      • drawLine

        public void drawLine​(float x1,
                             float y1,
                             float x2,
                             float y2)
        Draw a line from x1,y1 to x2,y2.
        Specified by:
        drawLine in interface PDFDrawable
        Parameters:
        x1 - the X co-ordinate of the start of the line
        y1 - the Y co-ordinate of the start of the line
        x2 - the X co-ordinate of the end of the line
        y2 - the Y co-ordinate of the end of the line
        Since:
        2.0
      • drawRectangle

        public void drawRectangle​(float x1,
                                  float y1,
                                  float x2,
                                  float y2)

        Draw a rectangle through the two corners x1,y1 and x2,y2. Whether the rectangle is drawn as an outline or filled depends on the LineColor and FillColor of the current style (see the pathPaint() method for more information).

        Specified by:
        drawRectangle in interface PDFDrawable
        Parameters:
        x1 - the X co-ordinate of the first corner of the rectangle
        y1 - the Y co-ordinate of the first corner of the rectangle
        x2 - the X co-ordinate of the second corner of the rectangle
        y2 - the Y co-ordinate of the second corner of the rectangle
        Since:
        2.0
      • drawRoundedRectangle

        public void drawRoundedRectangle​(float x1,
                                         float y1,
                                         float x2,
                                         float y2,
                                         float r)

        Draw a rectangle with rounded corners through the two corners x1,y1 and x2,y2. Whether the rectangle is drawn as an outline or filled depends on the LineColor and FillColor of the current style (see the pathPaint() method for more information).

        Specified by:
        drawRoundedRectangle in interface PDFDrawable
        Parameters:
        x1 - the X co-ordinate of the first corner of the rectangle
        y1 - the Y co-ordinate of the first corner of the rectangle
        x2 - the X co-ordinate of the second corner of the rectangle
        y2 - the Y co-ordinate of the second corner of the rectangle
        r - The radius of the circle that is used to round the corners. A value of zero give identical results to drawRectangle(float, float, float, float)
        Since:
        2.0
      • drawPolygon

        public void drawPolygon​(float[] x,
                                float[] y)

        Draw a polygon. The X and Y co-ordinates of the vertices are in the supplied arrays. Whether the polygon is drawn as an outline or filled depends on the LineColor and FillColor of the current style (see the pathPaint() method for more information).

        If the fill color is specified the polygon will be closed automatically if it isn't already.

        Specified by:
        drawPolygon in interface PDFDrawable
        Parameters:
        x - the X co-ordinates of the vertices
        y - the Y co-ordinates of the vertices
        Since:
        2.0
      • drawCircle

        public void drawCircle​(float x,
                               float y,
                               float radius)
        Draw a circle centered on x, y with a radius of radius. A more convenient way to draw circles than drawEllipse
        Specified by:
        drawCircle in interface PDFDrawable
        Parameters:
        x - the X co-ordinate of the center of the circle
        y - the Y co-ordinate of the center of the circle
        radius - the radius of the circle
        Since:
        2.0
      • drawEllipse

        public void drawEllipse​(float x1,
                                float y1,
                                float x2,
                                float y2)

        Draw an ellipse inside the specified rectangle. The top and sides of the ellipse will touch the edges of the rectangle drawn between x1,y1 and x2,y2.

        Whether the ellipse is drawn as an outline or filled depends on the LineColor and FillColor of the current style (see the pathPaint() method for more information).

        Specified by:
        drawEllipse in interface PDFDrawable
        Parameters:
        x1 - the X co-ordinate of the first corner of the rectangle
        y1 - the Y co-ordinate of the first corner of the rectangle
        x2 - the X co-ordinate of the second corner of the rectangle
        y2 - the Y co-ordinate of the second corner of the rectangle
        Since:
        2.0
      • drawEllipseArc

        public void drawEllipseArc​(float x1,
                                   float y1,
                                   float x2,
                                   float y2,
                                   float start,
                                   float end)

        Draw an ellipse arc inside the specified rectangle. The same as drawEllipse, but allows you to specify a start and end angle. If a FillColor is specified, the arc will be closed with a straight line.

        Specified by:
        drawEllipseArc in interface PDFDrawable
        Parameters:
        x1 - the X co-ordinate of the first corner of the rectangle
        y1 - the Y co-ordinate of the first corner of the rectangle
        x2 - the X co-ordinate of the second corner of the rectangle
        y2 - the Y co-ordinate of the second corner of the rectangle
        start - the start angle of the arc, in degrees clockwise from 12 o'clock
        end - the end angle of the arc, in degrees clockwise from 12 o'clock
        Since:
        2.0
      • drawCircleArc

        public void drawCircleArc​(float x,
                                  float y,
                                  float radius,
                                  float start,
                                  float end)
        Draw an arc of the circle centered on x,y with the specified radius. A more convenient way to draw circular arcs than drawEllipseArc If a FillColor is specified, the arc will be closed with a straight line.
        Specified by:
        drawCircleArc in interface PDFDrawable
        Parameters:
        x - the X co-ordinate of the center of the circle
        y - the Y co-ordinate of the center of the circle
        radius - the radius of the circle
        start - the start angle of the arc, in degrees clockwise from 12 o'clock
        end - the end angle of the arc, in degrees clockwise from 12 o'clock
        Since:
        2.0
      • drawShape

        public void drawShape​(java.awt.Shape shape)
        Draw a Shape. If the fill color is specified the Shape will be closed automatically if it isn't already.
        Specified by:
        drawShape in interface PDFDrawable
        Since:
        2.11.7
      • clipRectangle

        public void clipRectangle​(float x1,
                                  float y1,
                                  float x2,
                                  float y2)

        Set the clipping area to the rectangle which runs through the two corners x1,y1 and x2,y2.

        Specified by:
        clipRectangle in interface PDFDrawable
        Parameters:
        x1 - the X co-ordinate of the first corner of the rectangle
        y1 - the Y co-ordinate of the first corner of the rectangle
        x2 - the X co-ordinate of the second corner of the rectangle
        y2 - the Y co-ordinate of the second corner of the rectangle
        Since:
        2.0
      • clipRoundedRectangle

        public void clipRoundedRectangle​(float x1,
                                         float y1,
                                         float x2,
                                         float y2,
                                         float r)

        Set the clipping area to a rectangle with rounded corners which runs through the two corners x1,y1 and x2,y2.

        Specified by:
        clipRoundedRectangle in interface PDFDrawable
        Parameters:
        x1 - the X co-ordinate of the first corner of the rectangle
        y1 - the Y co-ordinate of the first corner of the rectangle
        x2 - the X co-ordinate of the second corner of the rectangle
        y2 - the Y co-ordinate of the second corner of the rectangle
        r - The radius of the circle that is used to round the corners. A value of zero give identical results to drawRectangle(float, float, float, float)
        Since:
        2.0
      • clipPolygon

        public void clipPolygon​(float[] x,
                                float[] y)

        Set the clipping area to a polygon. The X and Y co-ordinates of the vertices are in the supplied arrays.

        Specified by:
        clipPolygon in interface PDFDrawable
        Parameters:
        x - the X co-ordinates of the vertices
        y - the Y co-ordinates of the vertices
        Since:
        2.0
      • clipEllipse

        public void clipEllipse​(float x1,
                                float y1,
                                float x2,
                                float y2)

        Set the clipping area to the ellipse inside the specified rectangle. The top and sides of the ellipse will touch the edges of the rectangle drawn between x1,y1 and x2,y2.

        Specified by:
        clipEllipse in interface PDFDrawable
        Parameters:
        x1 - the X co-ordinate of the first corner of the rectangle
        y1 - the Y co-ordinate of the first corner of the rectangle
        x2 - the X co-ordinate of the second corner of the rectangle
        y2 - the Y co-ordinate of the second corner of the rectangle
        Since:
        2.0
      • clipCircle

        public void clipCircle​(float x,
                               float y,
                               float radius)
        Set the clipping area to a circle centered on x, y with a radius of radius.
        Specified by:
        clipCircle in interface PDFDrawable
        Parameters:
        x - the X co-ordinate of the center of the circle
        y - the Y co-ordinate of the center of the circle
        radius - the radius of the circle
        Since:
        2.0
      • clipShape

        public void clipShape​(java.awt.Shape shape)
        Clip a Shape
        Specified by:
        clipShape in interface PDFDrawable
        Since:
        2.11.7
      • pathMove

        public void pathMove​(float x,
                             float y)
        Start a new path at the specified position. If a path has already been started, move the cursor without drawing a line.
        Specified by:
        pathMove in interface PDFDrawable
        Parameters:
        x - the X co-ordinate to move to
        y - the Y co-ordinate to move to
        Since:
        2.0
      • pathLine

        public boolean pathLine​(float x,
                                float y)
        Continue the open path in a straight line to the specified position.
        Specified by:
        pathLine in interface PDFDrawable
        Parameters:
        x - the X co-ordinate to move to
        y - the Y co-ordinate to move to
        Returns:
        true if any sections were drawn on the path
        Throws:
        java.lang.IllegalStateException - if a path hasn't been started with pathMove(float, float)
        Since:
        2.0
      • pathBezier

        public boolean pathBezier​(float cx1,
                                  float cy1,
                                  float cx2,
                                  float cy2,
                                  float x,
                                  float y)
        Continue the open path in a bezier curve to the specified position.
        Specified by:
        pathBezier in interface PDFDrawable
        Parameters:
        cx1 - the X co-ordinate of the first control point for the curve
        cy1 - the Y co-ordinate of the first control point for the curve
        cx2 - the X co-ordinate of the second control point for the curve
        cy2 - the Y co-ordinate of the second control point for the curve
        x - the X co-ordinate to move to
        y - the Y co-ordinate to move to
        Returns:
        true if any sections were drawn on the path
        Throws:
        java.lang.IllegalStateException - if a path hasn't been started with pathMove(float, float)
        Since:
        2.0
      • pathArc

        public boolean pathArc​(float width,
                               float height,
                               float start,
                               float end)
        Continue the open path in an arc to the specified position.
        Specified by:
        pathArc in interface PDFDrawable
        Parameters:
        width - the width of the ellipse to take the arc from
        height - the height of the ellipse to take the arc from
        start - the start angle of the arc, in degrees clockwise from 12 o'clock
        end - the end angle of the arc, in degrees clockwise from 12 o'clock
        Returns:
        true if any sections were drawn on the path
        Throws:
        java.lang.IllegalStateException - if a path hasn't been started with pathMove(float, float)
        Since:
        2.0
      • pathShape

        public boolean pathShape​(java.awt.Shape shape)
        Add the path specified by a Shape to the Canvas
        Specified by:
        pathShape in interface PDFDrawable
        Parameters:
        shape - the shape
        Returns:
        true if any sections were drawn on the path
        Since:
        2.11.7
      • pathClose

        public void pathClose()
        Close the path by drawing a straight line back to its beginning. This does not complete the path, you still need to complete it with pathPaint() or pathCancel()
        Specified by:
        pathClose in interface PDFDrawable
        Throws:
        java.lang.IllegalStateException - if a path hasn't been started with pathMove(float, float)
        Since:
        2.0
      • pathCancel

        public void pathCancel()
        Cancel the current path
        Specified by:
        pathCancel in interface PDFDrawable
        Throws:
        java.lang.IllegalStateException - if a path hasn't been started with pathMove(float, float)
        Since:
        2.0
      • pathPaint

        public void pathPaint()
        Close and paint the path. What this actually does depends on the currently applied PDFStyle
        • If the style has a LineColor specified but no FillColor, "stroke" the path by drawing it as an outline in the current line color
        • If the style has a FillColor specified but no LineColor, call pathClose() and "fill" the path with the current fill color
        • If the style has both a FillColor and a LineColor, call pathClose(), "fill" the path with the current fill color then "stroke" the path with the current line color.
        Specified by:
        pathPaint in interface PDFDrawable
        Throws:
        java.lang.IllegalStateException - if a path hasn't been started with pathMove(float, float), or if neither a fill nor line color has been specified.
        Since:
        2.0
      • pathClipAndPaint

        public void pathClipAndPaint()
        Close and paint the path as described in pathPaint(), then set the clipping area to the same are as described in pathClip()
        Specified by:
        pathClipAndPaint in interface PDFDrawable
        Since:
        2.0
      • pathClip

        public void pathClip()

        Close the path and set the "clipping area" of the page to be the intersection of the current clipping area and the shape defined by this path. Any future graphics or text operations on the page are only applied within this area.

        There is no way to enlarge the current clipping area, or to set a new clipping area without reference to the current one. However, as the current clipping area is part of the graphics state, it can and should be nested inside calls to save() and restore() to limit its effect.

        Specified by:
        pathClip in interface PDFDrawable
        Throws:
        java.lang.IllegalStateException - if a path hasn't been started with pathMove(float, float)
        Since:
        2.0
      • save

        public void save()

        Save the state of this page. This takes a snapshot of the currently applied style, position, clipping area and any rotation/translation/scaling that has been applied, which can be later restored with a call to restore()

        Calls to save can be nested, but note that for most PDF viewers it is an error to save the page state but not restore it.

        Specified by:
        save in interface PDFDrawable
        Throws:
        java.lang.IllegalStateException - if a save is performed with an open path or if saves are nested more than 28 deep.
        Since:
        2.0
      • restore

        public void restore()
        Restore the state that was saved with the last call to save()
        Specified by:
        restore in interface PDFDrawable
        Throws:
        java.lang.IllegalStateException - if there is no previously saved state
        Since:
        2.0
      • rotate

        public void rotate​(float x,
                           float y,
                           double ang)
        Rotate the canvas around the specified point by the specified number of degrees. All further draw/path/clip actions on this canvas will be adjusted accordingly. The best way to get back to normal after a rotate is to wrap the rotate inside a save()/restore() block, eg.
           canvas.save();
           canvas.rotate(100,100,45);
           canvas.drawLayoutBox(rotatedtext, 100, 100);
           canvas.restore();
         
        Specified by:
        rotate in interface PDFDrawable
        Since:
        2.0
      • transform

        public void transform​(java.awt.geom.AffineTransform transform)
        Concatenate an AffineTransform to the canvases current transform. All future operations will be transformed by this matrix.
        Specified by:
        transform in interface PDFDrawable
        Since:
        2.11.7
      • transform

        public void transform​(double m00,
                              double m10,
                              double m01,
                              double m11,
                              double m02,
                              double m12)
        Concatenate an AffineTransform to the canvases current transform. All future operations will be transformed by this matrix. The six arguments are the same 6 arguments passed in to the AffineTransform constructor, in the same same order.
        Specified by:
        transform in interface PDFDrawable
        Since:
        2.7.7
      • getTransform

        public java.awt.geom.AffineTransform getTransform()
        Return a copy of the transform currently applied to the PDFCanvas
        Since:
        2.23.3
      • drawImage

        public void drawImage​(PDFImage image,
                              float x1,
                              float y1,
                              float x2,
                              float y2)
        Draw a PDFImage at the specified position on the page
        Specified by:
        drawImage in interface PDFDrawable
        Parameters:
        image - the image to draw
        x1 - the X co-ordinate of the left hand side of the image
        y1 - the Y co-ordinate of the bottom side of the image
        x2 - the X co-ordinate of the right hand side of the image
        y2 - the Y co-ordinate of the top side of the image
        Since:
        2.0
      • drawCanvas

        public void drawCanvas​(PDFCanvas canvas,
                               float x1,
                               float y1,
                               float x2,
                               float y2)
        Draw a PDFCanvas at the specified position on the page.
        Specified by:
        drawCanvas in interface PDFDrawable
        Parameters:
        canvas - the canvas to draw
        x1 - the X co-ordinate of the left hand side of the image
        y1 - the Y co-ordinate of the bottom side of the image
        x2 - the X co-ordinate of the right hand side of the image
        y2 - the Y co-ordinate of the top side of the image
        Throws:
        java.lang.IllegalArgumentException - if the canvas being drawn is this canvas - recursion is not allowed.
        Since:
        2.0
      • beginTag

        public void beginTag​(java.lang.String tag,
                             java.util.Map<java.lang.String,​java.lang.Object> atts)

        Open a structural tag on this page. This call must be matched by a later call to endTag().

        Structural tags add a tree structure on top of the otherwise flat structure of a PDF. They are primarily used to meet accesibility requirements, and so may be required for certain subsets of PDF such as PDF/A-1a. Using the beginTag and endtag methods is fairly simple and should be familiar to anytone that has used SAX or HTML:

         PDFCanvas canvas = new PDFCanvas(width, height);
         canvas.beginTag("Sect", null);
         LayoutBox box = new LayoutBox(600);
         box.addText("He said '", style, null);
         Map<String,Object> atts = new HashMap<String,Object>();
         atts.put("id", "quote1");
         box.beginTag("Quote", atts);
         box.addText("This is a contrived example", boldstyle, null);
         box.endTag();
         canvas.drawLayoutBox(box, x, y);
         canvas.endTag();
         

        Calls to beginTag must be matched to calls to endTag for each object - the methods exist in PDFPage, PDFCanvas and LayoutBox. A PDFCanvas with structural tags can only be drawn onto a page or another canvas once - an IllegalStateException will be thrown on a second attempt, or if it's drawn with an unclosed structural tag.

        While in general any values for tag are allowed, the following are suggested by the PDF specification

        DocumentDocument - the root element of any logical structure Document; recommended in PDF1, required in PDF2.
        PartPart - A large-scale division of a document. This type of element is appropriate for grouping articles or sections.
        ArtArticle - A relatively self-contained body of text constituting a single narrative or exposition. Articles should be disjoint; that is, they should not contain other articles as constituent elements (removed in PDF2).
        SectSection - A container for grouping related content elements. For example, a section might contain a heading, several introductory paragraphs, and two or more other sections nested within it as subsections.
        DivDivision A generic block-level element or group of elements.
        BlockQuoteBlock quotation - A portion of text consisting of one or more paragraphs attributed to someone other than the author of the surrounding text. (removed in PDF2)
        CaptionCaption - A brief portion of text describing a table or figure.
        TOCTable Of Contents - A list made up of table of contents item entries (structure type TOCI) and/or other nested table of contents entries (TOC).

        A TOC entry that includes only TOCI entries represents a flat hierarchy. A TOC entry that includes other nested TOC entries (and possibly TOCI entries) represents a more complex hierarchy. Ideally, the hierarchy of a top level TOC entry reflects the structure of the main body of the document.

        Lists of figures and tables, as well as bibliographies, can be treated as tables of contents for purposes of the standard structure types. (removed in PDF2)
        TOCITable of Contents Item - This entry’s children may be any of the following structure types: Lbl, Reference, NonStruct, P or TOC (removed in PDF2)
        IndexA sequence of entries containing identifying text accompanied by Reference elements that point out occurrences of the specified text in the main body of a document. (removed in PDF2)
        NonStructNonstructural element - A grouping element having no inherent structural significance; it serves solely for grouping purposes. This type of element differs from a Div in that it shall not be interpreted or exported to other document formats; however, its descendants shall be processed normally. (removed in PDF2)
        PrivatePrivate Element - A grouping element containing private content belonging to the application producing it. The structural significance of this type of element is unspecified and shall be determined entirely by the conforming writer. Neither the Private element nor any of its descendants shall be interpreted or exported to other document formats. (removed in PDF2)
        HHeading - A label for a subdivision of a document’s content. It should be the first child of the Div that it heads.
        H1, H2, H3, H4, H5, H6Heading with specific levels - For use in conforming writers that cannot hierarchically nest their sections and thus cannot determine the level of a heading from its level of nesting.
        PParagraph - A low-level division of text.
        LList - A sequence of items of like meaning and importance. Its immediate children should be an optional Caption followed by one or more LI
        LIList Item - An individual member of a list. Its children may be one or more combinations of Lbl or LBody
        LblLabel - A name or number that distinguishes a given item from others in the same list or other group of like items. In a dictionary list, for example, it contains the term being defined; in a bulleted or numbered list, it contains the bullet character or the number of the list item and associated punctuation.
        LBodyList Body - The descriptive content of a list item. In a dictionary list, for example, it contains the definition of the term. It may either contain the content directly or have other block-level items, perhaps including nested lists, as children.
        TableTable - A two-dimensional layout of rectangular data cells, possibly having a complex substructure. It contains either one or more TR as children; or an optional THead followed by one or more TBody and an optional TFoot. In addition, a table may have a Caption as its first or last child.
        TRTable Row - A row of headings or data in a table. It may contain TH and TD
        THTable Header Cell - A table cell containing header text describing one or more rows or columns of the table.
        TDTable Data Cell - A table cell containing data that is part of the table’s content.
        THeadTable header row group - A group of rows that constitute the header of a table. If the table is split across multiple pages, these rows may be redrawn at the top of each table fragment (although there is only one THead element).
        TBodyTable body row group - A group of rows that constitute the main body portion of a table. If the table is split across multiple pages, the body area may be broken apart on a row boundary. A table may have multiple TBody elements to allow for the drawing of a border or background for a set of rows.
        TFootTable footer row group - A group of rows that constitute the footer of a table. If the table is split across multiple pages, these rows may be redrawn at the bottom of each table fragment (although there is only one TFoot element.)
        SpanSpan - A generic inline portion of text having no particular inherent characteristics. It can be used, for example, to delimit a range of text with a given set of styling attributes, although it's not necessary to identify italic or bold text with a Span (as in HTML), as this can be derived from the text.
        QuoteQuotation - An inline portion of text attributed to someone other than the author of the surrounding text. The quoted text should be contained inline within a single paragraph. This differs from the block-level element BlockQuote, which consists of one or more complete paragraphs (or other elements presented as if they were complete paragraphs). (removed in PDF2)
        NoteNote - An item of explanatory text, such as a footnote or an endnote, that is referred to from within the body of the document. It may have a Lbl as a child. The note may be included as a child of the structure element in the body text that refers to it, or it may be included elsewhere (such as in an endnotes section) and accessed by means of a Reference. (removed in PDF2)
        ReferenceReference - A citation to content elsewhere in the document. (removed in PDF2)
        BibEntryBibliographic entry - A reference identifying the external source of some cited content. It may contain a Lbl as a child.

        Although a bibliography entry is likely to include component parts identifying the cited content’s author, work, publisher, and so forth, no standard structure types are defined at this level of detail.
        CodeCode entry - A fragment of computer program text (removed in PDF2)
        LinkLink - An association between a portion of the inline items’s content and a corresponding AnnotationLink. Its children should be zero or more content items or child inline items, and its annotation attribute should be set to the AnnotationLink
        AnnotAnnotation - An association between a portion of the inline items’s content and a corresponding PDFAnnotation. Its children should be zero or more content items or child inline items, and its annotation attribute should be set to the PDFAnnotation
        FormAnnotation - An association between a portion of the inline items’s content and a corresponding WidgetAnnotation. Its children should be zero or more content items or child inline items, and its annotation attribute should be set to the WidgetAnnotation
        ArtifactArtifact - Used to mark a section of text as a rendering artifact only. Artifacts are not considered part of the logical document structure. They take no attributes.

        Attributes for structural tags are unfortunately somewhat overengineered in the specification. For now we will recognise and handle appropriately the following attributes.

        idThe ID for this node - should be unique across the PDF (sets the "ID" attribute)
        classOne or more class names for this node, separated by spaces (sets the "C" attribute)
        titleThe optional human-readable description for the tag, eg "Chapter 1" (sets the "T" attribute)
        langThe optional language code for the tag and its childen, can be a String or a Locale. An alternative to setting a Locale on the text, it is recommended not to mix the two approaches - if you're using beginTag/endTag, leave the locale in any calls to LayoutBox.addText() as null (sets the "Lang" attribute)
        altThe alternate description for the structure element and its childen in human readable form (sets the "Alt" attribute).
        ActualTextText that is an exact replacement for the structure element and its children. This can be used when the actual PDF text is being added in a font without a correct Unicode mapping, when text is being added as an image, or when text is known to be broken over several lines (for example) (sets the "ActualText" attribute). Note there is rarely any reason to set this manually, it will be done automatically by the API when required. The only time it is useful to set it manually is to prevent text from being read out by a screen reader, which can be done by setting it to a single space character.
        abbrWhen an abbreviation is used, this attribute can be set to the unabbreviated version (sets the "E" attribute)
        phonemeAlong with the phonetic-alphabet attribute, specifies the pronunciation hints for the element (a PDF 2.0 property) Since 2.24.4
        phonetic-alphabetSets the interpretation of the phoneme value. The default is "ipa", but other values include "x-sampa", "x-Latn-pinyin" or "x-Latn-wadegile" (a PDF 2.0 property). Since 2.24.4
        annotationFor Link, Annot or Form tags, the PDFAnnotation they refer to
        metadataSince 2.26, any element may have XMP metadata associated with it by setting this attribute to the metadata, stored as a XMP or String. It may be retrieved as an XMP later by calling Node.getUserData("metadata")
        refSince 2.26.5 the "ref" attribute can be set to a space-separated list of element IDs (which may take the form bfo:uuid:nnn to reference a node with a bfo:uuid. The attribute will be converted to the PDF 2.0 Ref attribute
        filesSince 2.26, any element may have a list of files associated with it by setting this attribute to an EmbeddedFile (or a collection of them). It may be retrieved later by calling Node.getUserData("files")
        bfo:uuidOptional, representing the document-wide unique ID of this node. Sibling nodes with the same bfo:uuid will be merged in the tree (since 2.24) Note that bfo:key is a legacy method of setting this value. This value can be retrieved from any element by calling node.getUserData("uuid") and the values can also be passed in to Document.getElementById()
        bfo:sortOptional. If set to an instanceof Comparable or a Reference to a Comparable, all siblings will be sorted based on this value. When creating tags from an XML source, it would typically be set to an Integer representing the position of the node in document order (since 2.24)
        bfo:locationOptional. If set to a String, any errors relating to this node will be tagged with this location (since 2.24)

        Any attribute not described here will be stored in the document structure. Attributes may optionally be prefixed by an "owner" - the PDF Structure Tree version of an XML Namespace, as described in section 14.8.5.2 of ISO/IEC 32000 (version 1). For instance, to set the "Scope" attribute with the "Table" owner, you can specify the attribute name as "Table:Scope". Unprefixed attributes will be stored with the "UserProperties" Owner.

        For example, to specify a "TH" tag with the recommended "Scope" attribute, you could do as follows:

         Map<String,Object> atts = new HashMap<String,Object>();
         atts.put("Table:Scope", "Both");
         

        New in 2.24 (and new in PDF 2.0) is full support for namespaces. To specify a namespace, separate the namespace URI from the qname with a newline. The prefix is not stored in the PDF structure, so is optional. This approach applies to both the element name and the attribute - for example:

         Map<String,Object> atts = new HashMap<String,Object>();
         atts.put("http://www.w3.org/1999/xhtml\nfor", "myvalue");
         canvas.beginTag("http://www.w3.org/1999/xhtml\nlabel", atts);
         

        Attribute values are specified as Strings, but are not stored that way in PDF - the storage depends on the attribute, and the details of that are in the PDF specification. The types can also be retrieved from the DOM by querying the "type" userdata on an attribute, eg String type = (String)pdf.getDocumentElement().createAttribute("Layout:BorderColor").getUserData("type");

        The rules for serialization are

        TypeHow to format the value
        namethe value is a string, eg Name or Two Words
        stringthe value as a string, eg None
        numberthe value as a number, eg 2.4 or 1
        booleanthe value as true or false
        colorthe value is an array of three RGB values from 0..1, eg [0 1 0]
        rectthe value is an array of four numbers, eg [0 0 50 100]

        Arrays of each of these types are also accepted - these are specified wrapped in square brackets, with the individual values space separated, as shown in the example for "rect" and "color" above. There are three additional complexities with arrays:

        • Strings or names in an array use "backslash escaping"; for example, an array containing the two strings "back\slash" and "two words" would be represented as [back\\slash two\ words]
        • Arrays of colors look like [[1 0 0] [1 0 0] [0 0 0] [0 0 0]]
        • Arrays of colors or numbers also allow null values - this is specified as null, eg [[1 0 0] [1 0 0] [0 0 0] null] or [8 8 null 8]

        Note that as of 2.24, it's possible to modify the Document after creation. Because of this, very little validation is done directly by this method call. It is strongly recommended to use the "bfo:location" attribute to set some sort of useful marker in the attributes, so that any later error reports can be matched to the input element. A useful approach when creating content that originally started as XML, is to set both "bfo:uuid" and "bfo:sort" to an Integer that is the index in document order of the original element, and "bfo:location" to the String value of the Locator. This will allow elements to be added in an order that doesn't necessarily reflect the original ordering of the XML, while ensuring they are reordered to match that order when the PDF is rendered.

        If the sort order of individual content items also needs to be adjusted, passing null as a special value for tag in this method will set the properties for the subsequent items of content (text, graphics etc). There is no need to do this unless you are sorting content, in which case the attributes should include the bfo:sort key. There is no need to call a corresponding endTag() in this case.

        Finally note that 2.24 removed some legacy aliases for attributes, as having two means to set the same attribute is ambiguous. To migrate, change C to class, T to title, text to ActualText, E to abbr, ID to id, and ensure any attributes have theie Owner specified as a prefix if required - for example, prior to 2.24 you could specify "Scope" to set "Table:Scope" - this is no longer the case.

        Specified by:
        beginTag in interface PDFDrawable
        Parameters:
        tag - name of the tag
        atts - user defined attributes for this tag, or null
        Since:
        2.11.9
        See Also:
        PDF.getStructureTree(), PDFPage.beginTag(java.lang.String, java.util.Map<java.lang.String, java.lang.Object>), LayoutBox.beginTag(java.lang.String, java.util.Map<java.lang.String, java.lang.Object>), endTag(), PDFPage.endTag(), LayoutBox.endTag()
      • drawLayoutBox

        public void drawLayoutBox​(LayoutBox box,
                                  float x,
                                  float y)
        Draw a LayoutBox at the specified position on the page
        Specified by:
        drawLayoutBox in interface PDFDrawable
        Parameters:
        box - the LayoutBox to draw
        x - the X co-ordinate of the left hand side of the box
        y - the Y co-ordinate of the top side of the box
        Since:
        2.0
      • setOptionalContentDescriptor

        public void setOptionalContentDescriptor​(OptionalContentDescriptor descriptor)
        Set the OptionalContentDescriptor on this canvas, which can be a OptionalContentLayer or a logical expression containing several layers. See the API docs for those classes for more detail and examples.
        Parameters:
        descriptor - the descriptor, or null to remove any existing descriptor.
        Since:
        2.23.5
        See Also:
        OptionalContentDescriptor, OptionalContentLayer
      • setMetaData

        public void setMetaData​(java.lang.String xmldata)
        Set the XML metadata associated with this object. Since 2.26 this method calls getXMP().read(new StringReader(xmldata == null ? "" : xmldata)). We strongly recommend using the getXMP() method and modifying the XMP directly rather than using this method.
        Specified by:
        setMetaData in interface PDFDrawable
        Parameters:
        xmldata - the XML data to embed into the document, or null to clear any existing metadata. No validation is performed on this input.
        Since:
        2.11.18
        See Also:
        getXMP()
      • getXMP

        public XMP getXMP()
        Return an XMP Metadata object representing any XML metadata associated with this object
        Returns:
        the XMP, which may be empty or invalid but will never be null
        Since:
        2.26
      • createGraphics

        public java.awt.Graphics2D createGraphics​(PDF pdf)

        Return a Graphics2D implementation that renders to this PDFCanvas. This provides a standard Java AWT way to create content on the page, although there are some things to note due to the different rendering models between the PDF and the AWT.

        • Graphics2D.setComposite(java.awt.Composite) will log an AW1 warning and ignore anything other than an AlphaComposite.SRC_OVER composite
        • Graphics2D.setPaint(java.awt.Paint) will log an AW1 warning and ignore any types of Paint other than those defined in Java SE. The reason is the PaintContext interface is raster-based, so can't be used with PDF.
        • Graphics.setXORMode(java.awt.Color) will log an AW1 warning and do nothing
        • Graphics.copyArea(int, int, int, int, int, int) will log an AW1 warning and do nothing
        • Any Fonts can be used, but they will be recreated as OpenType fonts internally. All languages supported by the AWT should work correctly, including RTL languages (Arabic, Hebrew) and complex-shaping languages (Hindi, etc). However by using the Graphics2D you are relying on the Java AWT classes to layout text, rather than using the PDF Libraries own text-layout routines. Initial testing shows both are essentially identical, but that can't be guaranteed.
        • Although this method can be called multiple times on the same PDFCanvas, the Graphics2D objects returned from each call are not entirely independent (unlike, for example, those returned from BufferedImage.createGraphics(). The recommended approach if multiple Graphics2D objects is to call this method once, then call Graphics.create() to duplicate it.
        • Remember to call Graphics.dispose() on this Graphics2D when done, otherwise the PDF will fail to render
        • Do NOT write to this PDFCanvas directly while also writing to one of its Graphics2D objects!

        Otherwise the Graphics2D returned here is complete, although the PDF rendering model is much more powerful than the AWT model - operations like compositing a PDFCanvas onto another PDFCanvas can't be represented in the AWT, which can draw only shapes, text and bitmap images.

        Resources such as AWT images and fonts need to be converted to their PDF equivalents. The pdf parameter must be specified to ensure these are done only once per document.

        Finally, note that passing this Graphics2D as an input to the PagePainter.drawSubImage(java.awt.Graphics2D, double, double, double, double, float) method - round-tripping a PDF by rendering to a Graphics2D which converts it back to a PDF - will not give perfect results. Forcing the PDF rendering model onto the AWT model to generate a bitmap is hard enough - reversing the process is not possible.

        Parameters:
        pdf - the PDF that will eventually "own" this PDFCanvas.
        Since:
        2.26.3
      • toString

        public java.lang.String toString()
      • putLiteral

        public void putLiteral​(java.lang.String key,
                               java.lang.String tokens)
        Put a literal token sequnce. For debugging
        Parameters:
        key - the key
        tokens - the token sequence, eg "true" or "/foo" or "[/Foo/Bar]". No refs, just direct objects.
      • clone

        protected java.lang.Object clone()
        Overrides:
        clone in class java.lang.Object