A graphics renderer for creating PDFs.
- iOS 10.0+
- Mac Catalyst 13.0+
- tvOS 10.0+
You can use PDF renderers to create PDF files, without having to manage Core Graphics contexts.
To render a PDF:
Optionally create a
UIGraphicsobject to specify nondefault parameters the renderer should use to create its context.
UIGraphicsobject, providing the dimensions of the output image and a format object. The renderer uses sensible defaults for the current device if you don't provide format object, as demonstrated in Creating a Graphics PDF Renderer.
Choose one of the rendering methods depending on your desired output:
writesaves the PDF as a file directly to disk.
PDF(to: with Actions:)
Provide Core Graphics drawing instructions within the closure associated with your chosen method, as shown in Creating a PDF with a PDF Renderer.
Optionally, you can create a multi-page PDF, using the approach shown in Adding Pages.
Optionally, add links to your PDF to make navigation easy, as shown in Creating Internal Links.
Once a PDF renderer is initialized, you can use it to draw multiple PDFs with the same configuration.
Creating a Graphics PDF Renderer
Create a PDF renderer, providing the bounds of the PDF page.
You can instead use one of the other
UIGraphics initializers to specify a renderer format (
UIGraphics) in addition to the bounds. This allows you to configure the underlying Core Graphics context with custom PDF document info. If you don't provide a format, the
default() format is used, which creates a context best suited for the current device.
Creating a PDF with a PDF Renderer
The drawing actions closure takes a single argument of type
UIGraphics. This provides access to some high-level drawing functions, such as
fill(_:) via the
The above code creates the image shown in Figure 1.
The code in Listing 3 creates a PDF with three pages, each of which contains the current page number as large text, as shown in Figure 2.
Creating Internal Links
You can create internal links, known as destinations, in PDFs. A complete link is made up of two components:
A link region. This is a rectangle on a PDF page, which when tapped, instructs the PDF viewing app to jump to a specific named destination. You create these with the
Destination With Name(_: for:)
UIGraphics, providing the name of the destination to jump to, and the bounds of the active link region.
The code in Listing 4 demonstrates how to use destinations with a PDF renderer by showing how to create links that jump to the next page.
The code in Listing 4 adds large red labels that when clicked will jump from the current page to the next page. Each page has a destination with names of the form
page-1, positioned at the origin. The bounding box for the next-page label is used as the link to the destination on the following page.
Figure 3 shows the PDF that results from the code in Listing 4.