- iOS 11.0+
- Xcode 9.3+
You can add a custom drawing to a page or annotation by overriding that class’s draw method. Adding drawings to pages can be useful for adding custom layered effects or, as shown in this sample, watermarking a document.
Register the Delegate and Set the Page Class
View class first initializes a
PDFDocument instance and sets its delegate to
The delegate, of type
PDFDocument, implements a
class method. This method returns
Any and declares that all instances of
PDFPage for the document presented through
PDFView should instantiate the subclass
Watermark. This subclass, found in
Watermark, implements custom drawing.
View loads a URL to the
Sample file through the app’s main bundle. This URL is then used to instantiate a
PDFDocument. On success, the document is assigned to the
PDFView, which was set up in Interface Builder.
The delegate is assigned before the document, so
PDFDocument method, is implemented. This method returns the
PDFPage subclass used for custom drawing.
Override the Draw Method
PDFPage so that it can override the
draw(with box: to context:) method. This method is called by
PDFDocument to draw the page in a
PDFView. All custom drawing for a PDF page should be done through this mechanism.
Custom drawing methods should always be thread-safe and call the superclass method, which is required to draw the original
PDFPage content. Custom drawing code can execute before or after this superclass call, although order matters. If your graphics run before the superclass call, they’re drawn below the
PDFPage content. Conversely, if your graphics run after the superclass call, they’re drawn above the