DrawingContext

public final class DrawingContext

The DrawingContext class represents a PDF drawing destination.

You cannot initialize the context directly. You need to call the PDFDocument.addPage(_:) method; an instance of DrawingContext will be passed to the provided closure. That instance is only valid during the lifetime of that closure.

Each instance of DrawingContext is bound to some PDFPage, hence you can use it to perform drawing operations on only one page.

  • The page this context is bound to.

    Declaration

    Swift

    public let page: PDFPage
  • Puts the drawable visualization onto the page at the specified position.

    Declaration

    Swift

    @inlinable
    public func draw(_ drawable: Drawable, position: Point) throws

    Parameters

    drawable

    The entity to draw.

    position

    The position to put the drawable at. The meaning of this property depends on the drawable‘s implementation.

  • Puts the drawable visualization onto the page at the specified position.

    Declaration

    Swift

    @inlinable
    public func draw(_ drawable: Drawable, x: Float, y: Float) throws

    Parameters

    drawable

    The entity to draw.

    x

    The x coordinate of the position to put the drawable at.

    y

    The y coordinate of the position.

  • The default line width.

    Declaration

    Swift

    public static let defaultLineWidth: Float
  • The current line width for path painting of the page. Must be nonegative. Default value is DrawingContext.defaultLineWidth.

    Declaration

    Swift

    public var lineWidth: Float { get set }
  • The dash pattern for lines in the page. Default value is DashStyle.straightLine.

    Declaration

    Swift

    public var dashStyle: DashStyle { get set }
  • The shape to be used at the ends of lines. Default value is LineCap.butt.

    Declaration

    Swift

    public var lineCap: LineCap { get set }
  • The line join style in the page. Default value is LineJoin.miter.

    Declaration

    Swift

    public var lineJoin: LineJoin { get set }
  • The default miter limit for the joins of connected lines.

    Declaration

    Swift

    public static let defaultMiterLimit: Float
  • The miter limit for the joins of connected lines. Minimum value is 1. Default value is DrawingContext.defaultMiterLimit.

    Declaration

    Swift

    public var miterLimit: Float { get set }
  • The number of the page’s graphics state stack.

    This number is increased whenever you call withNewGState(_:) or clip(to:rule:_:) and decreased as soon as such a function returns.

    The value of this property must not be greater than DrawingContext.maxGraphicsStateDepth.

    Declaration

    Swift

    public var graphicsStateDepth: Int { get }
  • The maximum depth of the graphics state stack.

    Declaration

    Swift

    public static let maxGraphicsStateDepth: Int
  • Saves the page’s current graphics state to the stack, then executes body, then restores the saved graphics state.

    Precondition

    The value of graphicsStateDepth must be less than static DrawingContext.maxGraphicsStateDepth.

    Important

    Inside the provided block the value of graphicsStateDepth is incremented. Check it to prevent the precondition failure.

    The parameters that are saved at the beginning of the call and restored at the end are:

    • Character Spacing
    • Clipping Path
    • Dash Mode
    • Filling Color
    • Flatness
    • Font
    • Font Size
    • Horizontal Scalling
    • Line Width
    • Line Cap Style
    • Line Join Style
    • Miter Limit
    • Rendering Mode
    • Stroking Color
    • Text Leading
    • Text Rise
    • Transformation Matrix
    • Word Spacing

    Example:

    assert(context.fillColor == .red)
    
    try context.withNewGState {
    
       context.fillColor = .blue
       assert(context.fillColor == .blue)
    }
    
    assert(context.fillColor == .red)
    

    Declaration

    Swift

    public func withNewGState(_ body: () throws -> Void) rethrows

    Parameters

    body

    The code to execute using a new graphics state. rethrows errors thrown by body.

  • The transformation matrix for the current graphics state

    Declaration

    Swift

    public var currentTransform: AffineTransform { get }
  • Rotates the coordinate system of the page.

    You can call this method inside the withNewGState(_:) block, thereby being able to use the old coordinate system after withNewGState(_:) returns.

    Declaration

    Swift

    @inlinable
    public func rotate(byAngle angle: Float)

    Parameters

    angle

    The angle, in radians, by which to rotate the coordinate space. Positive values rotate counterclockwise and negative values rotate clockwise.

  • Changes the scale of the coordinate system of the page.

    For example, to change the coordinate system of the page to 300 dpi:

    context.scale(byX: 72.0 / 300.0, y: 72.0 / 300)
    

    You can call this method inside the withNewGState(_:) block, thereby being able to use the old coordinate system after withNewGState(_:) returns.

    Declaration

    Swift

    @inlinable
    public func scale(byX sx: Float, y sy: Float)

    Parameters

    sx

    The factor by which to scale the x-axis of the coordinate space.

    sy

    The factor by which to scale the y-axis of the coordinate space.

  • Changes the origin of the coordinate system of the page.

    You can call this method inside the withNewGState(_:) block, thereby being able to use the old coordinate system after withNewGState(_:) returns.

    Declaration

    Swift

    @inlinable
    public func translate(byX tx: Float, y ty: Float)

    Parameters

    tx

    The amount to displace the x-axis of the coordinate space.

    ty

    The amount to displace the y-axis of the coordinate space.

  • Concatenates the page’s current transformation matrix and the specified matrix.

    When you call this function, it concatenates (that is, it combines) two matrices, by multiplying them together. The order in which matrices are concatenated is important, as the operations are not commutative.

    You can call this method inside the withNewGState(_:) block, thereby being able to use the old coordinate system after withNewGState(_:) returns.

    Declaration

    Swift

    public func concatenate(_ transform: AffineTransform)

    Parameters

    transform

    The transformation to apply to the page’s current transformation.

  • The current value of the page’s stroking color space. Default value is PDFColorSpace.deviceGray

    Declaration

    Swift

    public var strokingColorSpace: PDFColorSpace { get }
  • The current value of the page’s filling color space. Default value is PDFColorSpace.deviceGray

    Declaration

    Swift

    public var fillingColorSpace: PDFColorSpace { get }
  • The current value of the page’s stroking color. Default is black in the deviceGray color space.

    Declaration

    Swift

    public var strokeColor: Color { get set }
  • The current value of the page’s filling color. Default is black in the deviceGray color space.

    Declaration

    Swift

    public var fillColor: Color { get set }
  • Sets the clipping area for drawing.

    Precondition

    The value of graphicsStateDepth must be less than static DrawingContext.maxGraphicsStateDepth.

    Important

    Inside the provided block the value of graphicsStateDepth is incremented. Check it to prevent the precondition failure.

    Important

    Graphics parameters that are set inside the drawInsideClippingArea closure do not persist outside the call of that closure. I. e. if, for example, the context’s fill color had been black and then was set to red inside the drawInsideClippingArea closure, after the closure returns it is black again.

    Declaration

    Swift

    public func clip(to path: Path, rule: Path.FillRule = .winding,
                     _ drawInsideClippingArea: () throws -> Void) rethrows

    Parameters

    path

    The path that constraints the clipping area. Must be closed.

    rule

    The rule for determining which areas to treat as the interior of the path. Default value is .winding.

    drawInsideClippingArea

    All that is drawn inside this closure is clipped to the provided path.

  • Fills the path.

    Declaration

    Swift

    public func fill(_ path: Path, rule: Path.FillRule = .winding, stroke: Bool = false)

    Parameters

    path

    The path to fill.

    rule

    The rule for determining which areas to treat as the interior of the path. Default value is .winding.

    stroke

    If specified true, also paints the path itself. Default value is false.

  • Paints the path.

    Declaration

    Swift

    public func stroke(_ path: Path)

    Parameters

    path

    The path to paint.

  • The current font of the context. Default value is Font.helvetica

    You can only set fonts that has previously been loaded in the document using loadTrueTypeFont(from:embeddingGlyphData:) or loadTrueTypeFontFromCollection(from:index:embeddingGlyphData:) methods, or ones predefined in the Font struct.

    Declaration

    Swift

    public var font: Font { get set }
  • The maximum size of a font that can be set.

    Declaration

    Swift

    public static let maximumFontSize: Float
  • Undocumented

    Declaration

    Swift

    public static let defaultFontSize: Float
  • The size of the current font of the context. Valid values are positive numbers up to DrawingContext.maximumFontSize. Default value is DrawingContext.defaultFontSize.

    Declaration

    Swift

    public var fontSize: Float { get set }
  • The encoding to use for a text. If the encoding cannot be used with the specified font, does nothing.

    Declaration

    Swift

    public var encoding: Encoding { get set }
  • Gets the width of the text in the current fontsize, character spacing and word spacing. If the text is multiline, returns the width of the longest line.

    Declaration

    Swift

    public func textWidth(for text: String) -> Float

    Parameters

    text

    The text to get width of.

    Return Value

    The width of the text in current fontsize, character spacing and word spacing.

  • Gets the bounding box of the text in the current font size and leading. Text can be multiline.

    Declaration

    Swift

    public func boundingBox(for text: String, atPosition position: Point) -> Rectangle

    Parameters

    text

    The text to get the bounding box of.

    position

    The assumed position of the text.

    Return Value

    The bounding box of the text.

  • The vertical ascent of the current font in the current font size.

    Declaration

    Swift

    public var fontAscent: Float { get }
  • The vertical descent of the current font in the current font size. This value is negative.

    Declaration

    Swift

    public var fontDescent: Float { get }
  • The height of lowercase letters reach based on height of lowercase x in the current font and font size; does not include ascenders or descenders.

    Declaration

    Swift

    public var fontXHeight: Float { get }
  • The height of a capital letter in the current font and font size measured from the baseline.

    Declaration

    Swift

    public var fontCapHeight: Float { get }
  • The default text leading.

    Declaration

    Swift

    public static let defaultTextLeading: Float
  • Text leading (line spacing) for text showing. Default value is DrawingContext.defaultTextLeading.

    Declaration

    Swift

    public var textLeading: Float { get set }
  • Prints the text at the specified position on the page. You can use \n to print multiline text.

    Declaration

    Swift

    public func show(text: String, atPosition position: Point) throws

    Parameters

    text

    The text to print.

    position

    The position to show the text at.

  • Prints the text at the specified position on the page. You can use \n to print multiline text.

    Declaration

    Swift

    @inlinable
    public func show(text: String, atX x: Float, y: Float) throws

    Parameters

    text

    The text to print.

    x

    x coordinate of the position to show the text at.

    y

    y coordinate of the position to show the text at.

  • Prints the text inside the specified region.

    Declaration

    Swift

    @discardableResult
    public func show(text: String,
                     in rect: Rectangle,
                     alignment: TextAlignment) throws -> (isSufficientSpace: Bool, charactersPrinted: Int)

    Parameters

    text

    The text to show.

    rect

    The region to output text.

    alignment

    The alignment of the text.

    Return Value


    • isSufficientSpace: false if whole text doesn’t fit into declared space.
    • charactersPrinted: The number of characters printed in the area.