PSPDFDocument


@interface PSPDFDocument
    : NSObject <PSPDFDocumentProviderDelegate, PSPDFOverridable, NSCopying,
                NSSecureCoding, NSFastEnumeration,
                PSPDFFileCoordinationDelegate>

The PSPDFDocument class represents a set of PDF sources that are displayed as one document.

The PDF sources are internally represented as data providers (implementations of the PSPDFDataProviding protocol). The typical use case is to initialize the document with a single fileURL, which creates an implicit PSPDFCoordinatedFileDataProvider by default. You can also opt to use NSData or custom implementations of PSPDFDataProviding as sources during initialization.

This object can be created on any thread. Accessing properties is thread safe but might take some time, as the underlying PDF documents need to be processed to fetch data like pageCount or title. The document builds an internal cache, so subsequent access is faster. For this reason, ensure that document objects are not created/destroyed randomly for maximum efficiency.

Ensure that a PSPDFDocument is only opened by one PSPDFViewController at any time. Also ensure that subclasses do not implement their own equality semantics, and instead use the UID property to check if two documents are equal.

PSPDFDocument supports NSFastEnumeration by enumerating over its documentProviders. The document providers are internal wrappers around the data providers created during initialization.

  • Initialize PSPDFDocument with a single local file.

    This convenience initializer creates either a PSPDFCoordinatedFileDataProvider or a PSPDFFileDataProvider depending on if PSPDFFileCoordinationEnabledKey is set on the PSPDFKit shared object.

    The data providers’s baseURL will be set to URL.URLByDeletingLastPathComponent. If you switch between this and initializing with an explict data provider then be sure to set the baseURL to ensure UIDs are consistent.

    Note

    If you are expecting to encounter symlinks or alias files, you need to resolve those using NSURL APIs before passing the URLs to PSPDFDocument. PSPDFDocument won’t automatically resolve them for performance reasons.

    Declaration

    Objective-C

    - (nonnull instancetype)initWithURL:(nonnull NSURL *)URL;

    Swift

    convenience init(url URL: URL)

    Parameters

    URL

    A local file URL of a PDF document.

    Return Value

    A new document object.

  • Initialize PSPDFDocument with one or multiple dataProviders (id).

    Does not load from a checkpoint even if one exists.

    Declaration

    Objective-C

    - (nonnull instancetype)initWithDataProviders:
        (nonnull NSArray<id<PSPDFDataProviding>> *)dataProviders;

    Swift

    convenience init(dataProviders: [PSPDFDataProviding])

    Parameters

    dataProviders

    An array of data providers that supply the PDF document content.

    Return Value

    A new document object.

  • Initialize PSPDFDocument with one or multiple dataProviders (id), optionally enabling restoring from a checkpoint.

    To load from a local file, use PSPDFCoordinatedFileDataProvider. To load from NSData, use PSPDFDataContainerProvider.

    Data providers conforming to PSPDFCoordinatedFileDataProviding will get their coordinationDelegate automatically assigned to the document.

    Note

    It’s currently not possible to add the same file multiple times. This will fail to display correctly.

    Declaration

    Objective-C

    - (nonnull instancetype)initWithDataProviders:
                                (nonnull NSArray<id<PSPDFDataProviding>> *)
                                    dataProviders
                        loadCheckpointIfAvailable:(BOOL)loadCheckpoint;

    Swift

    init(dataProviders: [PSPDFDataProviding], loadCheckpointIfAvailable loadCheckpoint: Bool)

    Parameters

    dataProviders

    An array of data providers that supply the PDF document content.

    loadCheckpoint

    Specifies whether an available checkpoint should be loaded.

    Return Value

    A new document object.

  • Creates a new document with all the data providers of the receiver plus those in dataProviders.

    Note

    This uses NSCopying to preserve custom settings.

    Declaration

    Objective-C

    - (nonnull instancetype)documentByAppendingDataProviders:
        (nonnull NSArray<id<PSPDFDataProviding>> *)dataProviders;

    Swift

    func appendingDataProviders(_ dataProviders: [PSPDFDataProviding]) -> Self

    Parameters

    dataProviders

    An array containing objects conforming to PSPDFDataProviding to be added to the new document.

    Return Value

    A new document object.

  • The document delegate to control saving and annotation path resolving. - note: This can be freely set and is not directly used inside PSPDFKit.

    Declaration

    Objective-C

    @property (readwrite, nonatomic) id<PSPDFDocumentDelegate> _Nullable delegate;
  • Returns YES if the document data source can be accessed and the PDF has at least one page and is unlocked. Might need file operations to parse the document. - note: Password protected documents will return NO here until the correct password is set. Check for isLocked to see if it’s a protected document.

    Declaration

    Objective-C

    @property (readonly, getter=isValid, nonatomic) BOOL valid;

    Swift

    var isValid: Bool { get }
  • If the document can not be opened and thus is in an error state, the error is propagated through this property.

    Declaration

    Objective-C

    @property (readonly, nonatomic, nullable) NSError *error;

    Swift

    var error: Error? { get }
  • Compare two documents for equality. Will check if the source definitions are the same. This will not detect two different files that are the same - for that better do a custom file comparison.

    Declaration

    Objective-C

    - (BOOL)isEqualToDocument:(nonnull PSPDFDocument *)otherDocument;

    Swift

    func isEqual(to otherDocument: PSPDFDocument) -> Bool
  • Convenience accessor for the first fileURL of the document.

    Declaration

    Objective-C

    @property (readonly, nonatomic, nullable) NSURL *fileURL;

    Swift

    var fileURL: URL? { get }
  • Return all file URLs. Returns an empty array if the documents contains no file data providers (PSPDFFileDataProviding).

    Declaration

    Objective-C

    @property (readonly, nonatomic) NSArray<NSURL *> *_Nonnull fileURLs;

    Swift

    var fileURLs: [URL] { get }
  • The document itself can be comprised out of multiple files, therefore it can’t be a file presenter on its own. Instead, you can use this property to get a list of the data providers’ file presenters. Returns an empty array if the document has no data providers that have file presenters.

    Declaration

    Objective-C

    @property (readonly, nonatomic)
        NSArray<id<NSFilePresenter>> *_Nonnull filePresenters;

    Swift

    var filePresenters: [NSFilePresenter] { get }
  • A combined parent progress object for all registered data providers advertising progress. This can be used to cancel any active progress operations when the document is dimissed. - note: The progress is cancelled when all registered data providers’ progresses are cancelled.

    Declaration

    Objective-C

    @property (readonly, nonatomic) NSProgress *_Nonnull progress;

    Swift

    var progress: Progress { get }
  • In some cases, the PDF document is a converted document from an Word, Excel or other file. If originalFile is set, then some actions such as Open In or Send via Email has the option to use the original file. - note: The Open In feature of iOS needs an NSURL - NSData does not work here.

    Declaration

    Objective-C

    @property (assign, readwrite, nonatomic, nullable) PSPDFFile *originalFile;

    Swift

    var originalFile: PSPDFFile? { get set }
  • Returns path for a single page (in case pages are split up). Page starts at 0. - note: Uses fileIndexForPageAtIndex: and URLForFileIndex: internally. Override those instead of pathForPage.

    Declaration

    Objective-C

    - (nullable NSURL *)pathForPageAtIndex:(NSUInteger)pageIndex;

    Swift

    func pathForPage(at pageIndex: UInt) -> URL?
  • Returns the position inside the internal documentProviders array. Page starts at 0.

    Declaration

    Objective-C

    - (NSInteger)fileIndexForPageAtIndex:(NSUInteger)pageIndex;

    Swift

    func fileIndexForPage(at pageIndex: UInt) -> Int
  • Returns the URL corresponding to the fileIndex.

    Declaration

    Objective-C

    - (nullable NSURL *)URLForFileIndex:(NSUInteger)fileIndex;

    Swift

    func url(forFileIndex fileIndex: UInt) -> URL?
  • Gets the file name for page 0. - see: fileNameForPageAtIndex:

    Declaration

    Objective-C

    @property (readonly, nonatomic, nullable) NSString *fileName;

    Swift

    var fileName: String? { get }
  • Helper that gets a suggested filename for a specific page. Page starts at 0.

    Note

    Guarantees to return a string (even if pageIndex is out of bounds)

    Declaration

    Objective-C

    - (nonnull NSString *)fileNameForPageAtIndex:(NSUInteger)pageIndex;

    Swift

    func fileNameForPage(at pageIndex: UInt) -> String
  • Deletes the underlying files from the disk, including the document itself and all cache and metadata files.

    Warning

    You should make sure that the receiver is no longer accessed after calling this method!

    Declaration

    Objective-C

    - (BOOL)deleteFiles:(NSError *_Nullable *_Nullable)error;

    Swift

    func deleteFiles() throws

    Parameters

    error

    The error, if one occurred.

    Return Value

    YES if the deletion was successful, NO otherwise.

  • PDF data when initialized with PSPDFDataContainerProvider otherwise nil. This is a shortcut to the first entry of dataArray.

    Declaration

    Objective-C

    @property (readonly, nonatomic, nullable) NSData *data;

    Swift

    var data: Data? { get }
  • The data of any PSPDFDataContainerProviders in dataProviders. - note: If writing annotations is enabled, the dataArray‘s content will change after a save. Returns an empty array there are no PSPDFDataContainerProvider-based data providers.

    Declaration

    Objective-C

    @property (readonly, nonatomic) NSArray<NSData *> *_Nonnull dataArray;

    Swift

    var dataArray: [Data] { get }
  • Returns an ordered dictionary with filename : NSData objects. Will memory-map data files. - note: If there is no file name available, this will use the PDF title or Untitled PDF if all fails. Uses PSPDFDocumentProviders dataRepresentationWithError:. Errors are only logged.

    Declaration

    Objective-C

    @property (readonly, nonatomic)
        NSDictionary<NSString *, NSData *> *_Nonnull fileNamesWithDataDictionary;

    Swift

    var fileNamesWithDataDictionary: [String : Data] { get }
  • PDF dataProviders are used to read and write PDF data from various sources. When initializing a document with a file URL, a suitable data provider will be automatically created to read data format the file. - note: Data providers can also be used to dynamically decrypt a document.

    Declaration

    Objective-C

    @property (readonly, nonatomic)
        NSArray<id<PSPDFDataProviding>> *_Nonnull dataProviders;

    Swift

    var dataProviders: [PSPDFDataProviding] { get }
  • Get an array of document providers to easily manage documents with multiple files.

    Declaration

    Objective-C

    @property (readonly, nonatomic)
        NSArray<PSPDFDocumentProvider *> *_Nonnull documentProviders;

    Swift

    var documentProviders: [PSPDFDocumentProvider] { get }
  • Get the document provider for a specific page. Page starts at 0.

    Declaration

    Objective-C

    - (nullable PSPDFDocumentProvider *)documentProviderForPageAtIndex:
        (NSUInteger)pageIndex;

    Swift

    func documentProviderForPage(at pageIndex: UInt) -> PSPDFDocumentProvider?
  • Get the page offset from a specific documentProvider. Can be used to calculate from the document provider page to the PSPDFDocument page.

    Declaration

    Objective-C

    - (NSUInteger)pageOffsetForDocumentProvider:
        (nonnull PSPDFDocumentProvider *)documentProvider;

    Swift

    func pageOffset(for documentProvider: PSPDFDocumentProvider) -> UInt
  • Returns a document identifier (inferred from a document provider if possible). A permanent identifier based on the contents of the file at the time it was originally created. This value will stay persistent, if the document if modified or moved to a different location. If a document identifier is not available, generated UID value is returned.

    Declaration

    Objective-C

    @property (readonly, copy, nonatomic, nullable) NSData *documentId;

    Swift

    var documentId: Data? { get }
  • Returns a string representation of a document identifier.

    Declaration

    Objective-C

    @property (readonly, copy, nonatomic, nullable) NSString *documentIdString;

    Swift

    var documentIdString: String? { get }
  • UID

    The unique UID for the document.

    The UID will be created automatically based on the content sources that are configured. You can manually set an UID here as well. Just make sure to set this before the document is used/cached/displayed. Since the UID is used internally for the page renderer cache, you will either have to set a new UID or clear the cache if you change the PDF contents outside of PSPDFKit. The UID is built based on the first file name and an MD5 hash of the path (or a part of data if the document is used). - note: This value might change, if the document if modified or moved to a different location.

    Declaration

    Objective-C

    @property (readwrite, copy, nonatomic, null_resettable) NSString *UID;

    Swift

    var uid: String! { get set }
  • Return pdf page count. Can be called from any thread. - warning: Might need file operations to parse the document (slow)

    Declaration

    Objective-C

    @property (readonly, nonatomic) NSUInteger pageCount;

    Swift

    var pageCount: UInt { get }
  • Cached rotation and aspect ratio data for specific page. Page starts at 0. Override the methods in PSPDFDocumentProvider instead.

    If multiple PSPDFDocumentProviders are used in one PSPDFDocument the returned PSPDFPageInfo‘s page property can no longer be relied on to always equal to the supplied page argument, since PSPDFPageInfo’s page property is PSPDFDocumentProvider-relative, while the page argument is relative to all PSPDFDocumentProviders in the PSPDFDocument.

    Declaration

    Objective-C

    - (nullable PSPDFPageInfo *)pageInfoForPageAtIndex:(NSUInteger)pageIndex;

    Swift

    func pageInfoForPage(at pageIndex: UInt) -> PSPDFPageInfo?
  • Makes a search beginning from page 0 for the nearest pageInfo. Does not calculate/block the thread.

    Declaration

    Objective-C

    - (nullable PSPDFPageInfo *)nearestPageInfoForPageAtIndex:(NSUInteger)pageIndex;

    Swift

    func nearestPageInfoForPage(at pageIndex: UInt) -> PSPDFPageInfo?
  • Saves the document synchronously.

    Saves the document and all of its linked data, including bookmarks and annotations, synchronously.

    @throws NSInternalInconsistencyException if save options are not valid.

    See

    saveWithOptions:completionHandler:

    Declaration

    Objective-C

    - (BOOL)saveWithOptions:
                (nullable NSDictionary<PSPDFDocumentSaveOption, id> *)options
                      error:(NSError *_Nullable *_Nullable)error;

    Swift

    func save(options: [PSPDFDocumentSaveOption : Any]? = nil) throws

    Parameters

    options

    Passing nil for options is equivalent to passing an empty dictionary @ {}. Available options are PSPDFDocumentSaveOptionForceRewrite and PSPDFDocumentSaveOptionSecurityOptions, see their documentation for more details.

    error

    Pointer to an error object if the document couldn’t be saved, otherwise the pointer remains unassigned.

    Return Value

    YES if the save operation completed successfully, otherwise NO together with the error parameter set to a valid error object.

  • Saves the document asynchronously.

    An asynchronous version for saveWithOptions:error:. Does not block the calling thread.

    @throws NSInternalInconsistencyException if save options are not valid.

    Declaration

    Objective-C

    - (void)saveWithOptions:
                (nullable NSDictionary<PSPDFDocumentSaveOption, id> *)options
          completionHandler:
              (nullable void (^)(NSError *_Nullable,
                                 NSArray<__kindof PSPDFAnnotation *> *_Nonnull))
                  completionHandler;

    Swift

    func save(options: [PSPDFDocumentSaveOption : Any]? = nil, completionHandler: ((Error?, [PSPDFAnnotation]) -> Void)? = nil)

    Parameters

    options

    A dictionary with save options. See saveWithOptions:error: for details on the available options.

    completionHandler

    Called on the main thread after the save operation finishes. If there was an error during the save operation, an error object is passed to the completion handler, otherwise error is nil. All saved annotations are also passed to the completion handler.

  • The object used for handling checkpoints. Change its strategy to get the behaviour you require.

    Declaration

    Objective-C

    @property (readonly, nonatomic) PSPDFDocumentCheckpointer *_Nonnull checkpointer;

    Swift

    var checkpointer: PSPDFDocumentCheckpointer { get }
  • Convenience getter for the documents’ outline. - note: Only evaluates the first file if multiple files are set.

    Declaration

    Objective-C

    @property (readonly, nonatomic, nullable) PSPDFOutlineElement *outline;

    Swift

    var outline: PSPDFOutlineElement? { get }
  • Set this property to allow automatic link detection. Will only add links where no link annotations already exist. Defaults to PSPDFTextCheckingTypeNone for performance reasons.

    Set to PSPDFTextCheckingTypeLink if you are see URLs in your document that are not clickable. PSPDFTextCheckingTypeLink is the default behavior for desktop apps like Adobe Acrobat or Apple Preview.

    Note

    This requires that you keep the PSPDFFileAnnotationProvider in the annotationManager. (Default). Needs to be set before the document is being displayed or annotations are accessed! The exact details how detection works are an implementation detail. Apple’s Data Detectors are currently used internally.

    Warning

    Auto-detecting links is useful but might slow down annotation display.

    Declaration

    Objective-C

    @property (assign, readwrite, nonatomic)
        PSPDFTextCheckingType autodetectTextLinkTypes;

    Swift

    var autodetectTextLinkTypes: PSPDFTextCheckingType { get set }
  • Iterates over all pages at indexes and creates new annotations for linkTypes. Will ignore any text that is already linked with the same URL. It is your responsibility to add the annotations to the document. If an error occurs, this method returns nil while setting the out error parameter to the encountered error.

    Note

    To analyze the whole document, use [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, document.pageCount)]

    options can take a PSPDFObjectsAnnotationsKey of type NSDictionary -> page to prevent auto-fetching for comparison.

    Warning

    Performs text and annotation extraction and analysis. Might be slow. progressBlock might be called from different threads. Ensure you dispatch to the main queue for progress updates.

    Declaration

    Objective-C

    - (nullable NSDictionary<NSNumber *, NSArray<__kindof PSPDFAnnotation *> *> *)
    annotationsByDetectingLinkTypes:(PSPDFTextCheckingType)linkTypes
                  forPagesAtIndexes:(nonnull NSIndexSet *)indexes
                            options:
                                (nullable NSDictionary<
                                    NSString *,
                                    NSDictionary<NSNumber *,
                                                 NSArray<PSPDFAnnotation *> *> *> *)
                                    options
                           progress:
                               (nullable void (^)(
                                   NSArray<__kindof PSPDFAnnotation *> *_Nonnull,
                                   NSUInteger, BOOL *_Nonnull))progressBlock
                              error:(NSError *_Nullable *_Nullable)error;

    Swift

    func annotations(byDetectingLinkTypes linkTypes: PSPDFTextCheckingType, forPagesAt indexes: IndexSet, options: [String : [NSNumber : [PSPDFAnnotation]]]? = nil, progress progressBlock: (([PSPDFAnnotation], UInt, UnsafeMutablePointer
  • Filters out watermarks from text selection and extraction. Defaults to YES. - note: Toggling this will invalidate all current text parsers. - note: Not all watermarks are properly identified by the PDF file. Due to this, PSPDFKit has to try to identify possible watermarks. This might accidentally filter out wanted text. If this is the case, please set isWatermarkFilterEnabled to NO and send a support request (https://pspdfkit.com/support/request) with the misbehaving PDF file.

    Declaration

    Objective-C

    @property (getter=isWatermarkFilterEnabled, assign, readwrite, nonatomic)
        BOOL watermarkFilterEnabled;

    Swift

    var isWatermarkFilterEnabled: Bool { get set }
  • Return a textParser for the specific document page. Thread safe.

    Declaration

    Objective-C

    - (nullable PSPDFTextParser *)textParserForPageAtIndex:(NSUInteger)pageIndex;

    Swift

    func textParserForPage(at pageIndex: UInt) -> PSPDFTextParser?
  • Find objects (glyphs, words, images, annotations) at the specified pdfPoint. If options is nil, we assume PSPDFObjectsText and PSPDFObjectsWordsKey. - note: Unless set otherwise, for points PSPDFObjectsTestIntersectionKey is YES automatically. Returns objects in certain key dictionaries .(PSPDFObjectsGlyphsKey, etc)

    This method is thread safe.

    Declaration

    Objective-C

    - (nonnull NSDictionary<NSString *, id> *)
    objectsAtPDFPoint:(CGPoint)pdfPoint
            pageIndex:(NSUInteger)pageIndex
              options:(nullable NSDictionary<NSString *, NSNumber *> *)options;

    Swift

    func objects(atPDFPoint pdfPoint: CGPoint, pageIndex: UInt, options: [String : NSNumber]? = nil) -> [String : Any]
  • Find objects (glyphs, words, images, annotations) at the specified pdfRect. If options is nil, we assume PSPDFObjectsGlyphsKey only. Returns objects in certain key dictionaries (PSPDFObjectsGlyphsKey, etc)

    This method is thread safe.

    Declaration

    Objective-C

    - (nonnull NSDictionary<NSString *, id> *)
    objectsAtPDFRect:(CGRect)pdfRect
           pageIndex:(NSUInteger)pageIndex
             options:(nullable NSDictionary<NSString *, NSNumber *> *)options;

    Swift

    func objects(atPDFRect pdfRect: CGRect, pageIndex: UInt, options: [String : NSNumber]? = nil) -> [String : Any]
  • Will clear all cached objects (annotations, pageCount, outline, textParser, …)

    This is called implicitly if you change the files array or append a file.

    Important! Unless you disable it, PSPDFKit also has an image cache who is not affected by this. If you replace the PDF document with new content, you also need to clear the image cache: [PSPDFKit.sharedInstance.cache removeCacheForDocument:document deleteDocument:NO error:NULL];

    Warning

    Calling this will also destroy any unsaved annotations. However, this will not automatically reload the PSPDFViewController. As with all document modifying options, call reloadData after calling this.

    Declaration

    Objective-C

    - (void)clearCache;

    Swift

    func clearCache()
  • Creates internal cache for faster display. override to provide custom caching. - note: This is thread safe and usually called on a background thread.

    Declaration

    Objective-C

    - (void)fillCache;

    Swift

    func fillCache()
  • Path where data like bookmarks or annotations (if they can’t be embedded into the PDF) are saved. Defaults to &lt;AppDirectory&gt;/Library/PrivateDocuments/PSPDFKit. Cannot be nil. Will always be appended by UID. Don’t manually append UID.

    Declaration

    Objective-C

    @property (readwrite, copy, nonatomic) NSString *_Nonnull dataDirectory;

    Swift

    var dataDirectory: String { get set }
  • Make sure ‘dataDirectory’ exists. Returns error if creation is not possible.

    Declaration

    Objective-C

    - (BOOL)ensureDataDirectoryExistsWithError:(NSError *_Nullable *_Nullable)error;

    Swift

    func ensureDataDirectoryExists() throws
  • Toggle if the disk cache is used for this document.

    By default this returns YES, unless any data provider disables useDiskCache, or if any document provider is encrypted, in which case this returns NO. Can always be manually set to NO.

    Declaration

    Objective-C

    @property (assign, readwrite, nonatomic) BOOL useDiskCache;

    Swift

    var useDiskCache: Bool { get set }
  • Note

    password is not exposed as a property on purpose. Ideally store the password securely in the keychain and set only when needed.

    Warning

    This will re-create the PSPDFAnnotationManager class, so you need to re-apply settings after unlocking the document.

    Declaration

    Objective-C

    - (BOOL)unlockWithPassword:(nonnull NSString *)password;

    Swift

    func unlock(withPassword password: String) -> Bool
  • Will re-lock a document if it has a password set. - warning: Make sure it is not currently displayed anywhere or call reloadData on the pdfController afterwards.

    Declaration

    Objective-C

    - (void)lock;

    Swift

    func lock()
  • Was the PDF file encrypted at file creation time? - note: Only evaluates the first file if multiple files are set.

    Declaration

    Objective-C

    @property (readonly, atomic) BOOL isEncrypted;

    Swift

    var isEncrypted: Bool { get }
  • Name of the encryption filter used, e.g. Adobe.APS. If this is set, the document can’t be unlocked. See “Adobe LifeCycle DRM, http://www.adobe.com/products/livecycle/rightsmanagement - note: Only evaluates the first file if multiple files are set.

    Declaration

    Objective-C

    @property (readonly, atomic, nullable) NSString *encryptionFilter;

    Swift

    var encryptionFilter: String? { get }
  • Has the PDF file been unlocked? (is it still locked?). - note: Only evaluates the first file if multiple files are set.

    Declaration

    Objective-C

    @property (readonly, atomic) BOOL isLocked;

    Swift

    var isLocked: Bool { get }
  • A PDF flag that indicates whether printing is allowed. - note: This replaces allowsCopying and allowsPrinting from earlier versions of the SDK. - note: Only evaluates the first file if multiple files are set.

    Declaration

    Objective-C

    @property (readonly, atomic) PSPDFDocumentPermissions permissions;

    Swift

    var permissions: PSPDFDocumentPermissions { get }
  • A flag that indicates whether changing existing annotations or creating new annotations are allowed - note: Searches and checks the digital signatures on the first call (caches the result for subsequent calls)

    Declaration

    Objective-C

    @property (readonly, atomic) BOOL allowAnnotationChanges;

    Swift

    var allowAnnotationChanges: Bool { get }
  • Globally enable/disable bookmarks. Defaults to YES.

    Declaration

    Objective-C

    @property (getter=areBookmarksEnabled, assign, readwrite, nonatomic)
        BOOL bookmarksEnabled;

    Swift

    var areBookmarksEnabled: Bool { get set }
  • Accesses the bookmark manager. Bookmarks are handled on document level, not on documentProvider.

    Note

    Bookmarks are loaded from the document by default. The document must be valid for the manager to be loaded - otherwise it’s nil.

    Declaration

    Objective-C

    @property (readonly, atomic, nullable) PSPDFBookmarkManager *bookmarkManager;

    Swift

    var bookmarkManager: PSPDFBookmarkManager? { get }
  • Returns the bookmarks. - note: The PSPDFBookmark objects themselves are not changed, only those who are not visible are filtered out.

    Declaration

    Objective-C

    @property (readonly, atomic) NSArray<PSPDFBookmark *> *_Nonnull bookmarks;

    Swift

    var bookmarks: [PSPDFBookmark] { get }
  • Set to NO to disable the custom PDF page labels and simply use page numbers. Defaults to YES.

    Declaration

    Objective-C

    @property (getter=arePageLabelsEnabled, assign, readwrite, atomic)
        BOOL pageLabelsEnabled;

    Swift

    var arePageLabelsEnabled: Bool { get set }
  • Page labels for the current document. Page starts at 0. Page labels may be used to set a different page number/index than what is inferred from the document by default. Might be nil if the PageLabels dictionary isn’t set in the PDF. If substituteWithPlainLabel is set to YES then this always returns a valid string. - note: If pageLabelsEnabled is set to NO, then this method will either return nil or the plain label if substitute is YES.

    Declaration

    Objective-C

    - (nullable NSString *)pageLabelForPageAtIndex:(NSUInteger)pageIndex
                          substituteWithPlainLabel:(BOOL)substitute;

    Swift

    func pageLabelForPage(at pageIndex: UInt, substituteWithPlainLabel substitute: Bool) -> String?
  • Find page of a page label.

    Declaration

    Objective-C

    - (NSUInteger)pageForPageLabel:(nonnull NSString *)pageLabel
                   partialMatching:(BOOL)partialMatching;

    Swift

    func page(forPageLabel pageLabel: String, partialMatching: Bool) -> UInt
  • Set to NO to disable displaying/editing AcroForms. Defaults to YES. - note: Not all PSPDFKit variants do support AcroForms. - warning: For formsEnabled to work, you need to also set annotationsEnabled to YES, since forms are simply a special sub-type of Widget annotations.

    Declaration

    Objective-C

    @property (getter=areFormsEnabled, assign, readwrite, atomic) BOOL formsEnabled;

    Swift

    var areFormsEnabled: Bool { get set }
  • Control JavaScript processing. Defaults to YES.

    Declaration

    Objective-C

    @property (getter=isJavaScriptEnabled, assign, readwrite, atomic)
        BOOL javaScriptEnabled;

    Swift

    var isJavaScriptEnabled: Bool { get set }
  • AcroForm parser for the document.

    Declaration

    Objective-C

    @property (readonly, atomic, nullable) PSPDFFormParser *formParser;

    Swift

    var formParser: PSPDFFormParser? { get }
  • Master switch to completely disable annotation display/parsing on a document. Defaults to YES. - note: This will disable the creation of the PSPDFAnnotationManager. - warning: This will also disable links and forms. In most cases, this is not what you want. To disable editing features, instead customize editableAnnotationTypes in PSPDFConfiguration.

    Declaration

    Objective-C

    @property (getter=areAnnotationsEnabled, assign, readwrite, nonatomic)
        BOOL annotationsEnabled;

    Swift

    var areAnnotationsEnabled: Bool { get set }
  • Add annotations to the current document (and the backing store PSPDFAnnotationProvider) - parameter: annotations An array of PSPDFAnnotation objects to be inserted. - parameter: options Insertion options (see the PSPDFAnnotationOption... constants in PSPDFAnnotationManager.h). - note: For each, the absolutePage property of the annotation is used. - warning: Might change the page property if multiple documentProviders are set.

    Declaration

    Objective-C

    - (BOOL)addAnnotations:(nonnull NSArray<PSPDFAnnotation *> *)annotations
                   options:(nullable NSDictionary<NSString *, id> *)options;

    Swift

    func add(_ annotations: [PSPDFAnnotation], options: [String : Any]? = nil) -> Bool

    Parameters

    annotations

    An array of PSPDFAnnotation objects to be inserted.

    options

    Insertion options (see the PSPDFAnnotationOption... constants in PSPDFAnnotationManager.h).

  • Remove annotations from the backing PSPDFAnnotationProvider object(s). - parameter: annotations An array of PSPDFAnnotation objects to be removed. - parameter: options Deletion options (see the PSPDFAnnotationOption... constants in PSPDFAnnotationManager.h). - note: Might return NO if one or multiple annotations couldn’t be deleted. This might be the case for form annotations or other objects that return NO for isDeletable.

    Declaration

    Objective-C

    - (BOOL)removeAnnotations:(nonnull NSArray<PSPDFAnnotation *> *)annotations
                      options:(nullable NSDictionary<NSString *, id> *)options;

    Swift

    func remove(_ annotations: [PSPDFAnnotation], options: [String : Any]? = nil) -> Bool

    Parameters

    annotations

    An array of PSPDFAnnotation objects to be removed.

    options

    Deletion options (see the PSPDFAnnotationOption... constants in PSPDFAnnotationManager.h).

  • Returns annotations for a specific page. Page starts at 0.

    Declaration

    Objective-C

    - (nullable NSArray<__kindof PSPDFAnnotation *> *)
    annotationsForPageAtIndex:(NSUInteger)pageIndex
                         type:(PSPDFAnnotationType)type;

    Swift

    func annotationsForPage(at pageIndex: UInt, type: PSPDFAnnotationType) -> [PSPDFAnnotation]?
  • Returns all annotations in this document. Will not add key entries for pages without annotations. - note: To check for all annotations, but not links or forms, you will want to use PSPDFAnnotationTypeAll&~(PSPDFAnnotationTypeLink|PSPDFAnnotationTypeWidget) (Objective-C) or PSPDFAnnotationType.All.subtract([.Link, .Widget]) (Swift). - warning: Parsing annotations can take some time. Can be called from a background thread.

    Declaration

    Objective-C

    - (nonnull NSDictionary<NSNumber *, NSArray<__kindof PSPDFAnnotation *> *> *)
    allAnnotationsOfType:(PSPDFAnnotationType)annotationType;

    Swift

    func allAnnotations(of annotationType: PSPDFAnnotationType) -> [NSNumber : [PSPDFAnnotation]]
  • Returns true if the document contains annotations. This scans the document in an efficient way and exits early as soon as an annotation was found. - note: This call checks for all annotation types except Link and Widget (Forms). Annotations that are soft-deleted will be ignored.

    Declaration

    Objective-C

    @property (readonly, nonatomic) BOOL containsAnnotations;

    Swift

    var containsAnnotations: Bool { get }
  • Tests if we can embed annotations into this PDF. Certain PDFs (e.g. with encryption, or broken xref index) are readonly. - note: Only evaluates the first file if multiple files are set. - warning: This might block for a while, the PDF needs to be parsed to determine this.

    Declaration

    Objective-C

    @property (readonly, atomic) BOOL canEmbedAnnotations;

    Swift

    var canEmbedAnnotations: Bool { get }
  • Returns YES if annotations can be saved, either in the PDF or in an external file. Also returns YES when one of the documentProviders is not using the default annotation provider. - note: This largely depends on canEmbedAnnotations and annotationSaveMode.

    Declaration

    Objective-C

    @property (readonly, atomic) BOOL canSaveAnnotations;

    Swift

    var canSaveAnnotations: Bool { get }
  • Control if and where PSPDFObjectsAnnotationsKey are saved. Possible options are PSPDFAnnotationSaveModeDisabled, PSPDFAnnotationSaveModeExternalFile, PSPDFAnnotationSaveModeEmbedded and PSPDFAnnotationSaveModeEmbeddedWithExternalFileAsFallback. (Default) - note: PSPDFKit automatically saves the document for various events. See autosaveEnabled in PSPDFViewController.

    Declaration

    Objective-C

    @property (assign, readwrite, nonatomic)
        PSPDFAnnotationSaveMode annotationSaveMode;

    Swift

    var annotationSaveMode: PSPDFAnnotationSaveMode { get set }
  • Default annotation username for new annotations. Defaults to the device name. Written as the T (title/user) property of newly created annotations.

    Declaration

    Objective-C

    @property (readwrite, copy, atomic, nullable)
        NSString *defaultAnnotationUsername;

    Swift

    var defaultAnnotationUsername: String? { get set }
  • Allows control over what annotation should get an AP stream. AP (Appearance Stream) generation takes more time but will maximize compatibility with PDF Viewers that don’t implement the complete spec for annotations. The default value for this dict is @{PSPDFAnnotationWriteOptionsGenerateAppearanceStreamForTypeKey: @(PSPDFAnnotationTypeFreeText|PSPDFAnnotationTypeInk|PSPDFAnnotationTypePolygon|PSPDFAnnotationTypePolyLine|PSPDFAnnotationTypeLine|PSPDFAnnotationTypeSquare|PSPDFAnnotationTypeCircle|PSPDFAnnotationTypeStamp|PSPDFAnnotationTypeWidget)}

    Declaration

    Objective-C

    @property (readwrite, copy, atomic, nullable)
        NSDictionary<NSString *, NSNumber *> *annotationWritingOptions;

    Swift

    var annotationWritingOptions: [String : NSNumber]? { get set }
  • Returns YES if there are unsaved annotations. - note: This might not include unsaved open annotation creation operations, like a partial drawing. First set pdfController.annotationStateManager.state = nil to make sure you’re not in an editing mode before evaluating this.

    Declaration

    Objective-C

    @property (readonly, nonatomic) BOOL hasDirtyAnnotations;

    Swift

    var hasDirtyAnnotations: Bool { get }
  • Renders the page or a part of it with default display settings into a new image. - parameter: pageIndex The index of the page that will be rendered. Starts at 0. - parameter: size The size of the page, in pixels, if it was rendered without clipping. - parameter: clipRect A rectangle, relative to size, that specifies the area of the page that should be rendered. CGRectZero = automatic. - parameter: annotations Annotations that should be rendered with the view. - parameter: options Dictionary with options that modify the render process (see PSPDFPageRenderer). Will be merged with renderOptions of the document, with options taking precedence over renderOptions. - parameter: error Returns an error object. (Then image will be nil). - returns: A new UIImage with the rendered page content.

    Declaration

    Objective-C

    - (nullable UIImage *)
    imageForPageAtIndex:(NSUInteger)pageIndex
                   size:(CGSize)size
          clippedToRect:(CGRect)clipRect
            annotations:(nullable NSArray<PSPDFAnnotation *> *)annotations
                options:(nullable NSDictionary<NSString *, id> *)options
                  error:(NSError *_Nullable *_Nullable)error;

    Swift

    func imageForPage(at pageIndex: UInt, size: CGSize, clippedTo clipRect: CGRect, annotations: [PSPDFAnnotation]?, options: [String : Any]? = nil) throws -> NSImage

    Parameters

    pageIndex

    The index of the page that will be rendered. Starts at 0.

    size

    The size of the page, in pixels, if it was rendered without clipping.

    clipRect

    A rectangle, relative to size, that specifies the area of the page that should be rendered. CGRectZero = automatic.

    annotations

    Annotations that should be rendered with the view.

    options

    Dictionary with options that modify the render process (see PSPDFPageRenderer). Will be merged with renderOptions of the document, with options taking precedence over renderOptions.

    error

    Returns an error object. (Then image will be nil).

    Return Value

    A new UIImage with the rendered page content.

  • Draw a page into a specified context. If for some reason renderPage: doesn’t return a Render Receipt, an error occurred. - parameter: pageIndex The index of the page that will be rendered. Starts at 0. - parameter: size The size of the page, in pixels, if it was rendered without clipping. - parameter: clipRect A rectangle, relative to size, that specifies the area of the page that should be rendered. CGRectZero = automatic. - parameter: annotations Annotations that should be rendered with the view. - parameter: options Dictionary with options that modify the render process (see PSPDFPageRenderer). Will be merged with renderOptions of the document, with options taking precedence over renderOptions. - returns: YES if the operation succeeded, NO otherwise. - note: if annotations is nil, they will be auto-fetched. Add an empty array if you don’t want to render annotations.

    Declaration

    Objective-C

    - (BOOL)renderPageAtIndex:(NSUInteger)pageIndex
                      context:(nonnull CGContextRef)context
                         size:(CGSize)size
                clippedToRect:(CGRect)clipRect
                  annotations:(nullable NSArray<PSPDFAnnotation *> *)annotations
                      options:
                          (nullable NSDictionary<PSPDFRenderOption, id> *)options
                        error:(NSError *_Nullable *_Nullable)error;

    Swift

    func renderPage(at pageIndex: UInt, context: CGContext, size: CGSize, clippedTo clipRect: CGRect, annotations: [PSPDFAnnotation]?, options: [PSPDFRenderOption : Any]? = nil) throws

    Parameters

    pageIndex

    The index of the page that will be rendered. Starts at 0.

    size

    The size of the page, in pixels, if it was rendered without clipping.

    clipRect

    A rectangle, relative to size, that specifies the area of the page that should be rendered. CGRectZero = automatic.

    annotations

    Annotations that should be rendered with the view.

    options

    Dictionary with options that modify the render process (see PSPDFPageRenderer). Will be merged with renderOptions of the document, with options taking precedence over renderOptions.

    Return Value

    YES if the operation succeeded, NO otherwise.

  • Set custom render options. See PSPDFRenderManager.h for a list of available keys.

    Note

    There are certain default render options set, such as PSPDFRenderInteractiveFormFillColorKey which you most likely want to preserve.

    The typical access pattern is: 1) get existing render options 2) customize the dictionary, 3) and set the new merged render options.

    If you are working with primarily dark documents, consider setting PSPDFRenderBackgroundFillColorKey to UIColor.blackColor to work around white/gray hairlines at document borders.

    Declaration

    Objective-C

    - (void)setRenderOptions:(nullable NSDictionary<PSPDFRenderOption, id> *)options
                        type:(PSPDFRenderType)type;

    Swift

    func setRenderOptions(_ options: [PSPDFRenderOption : Any]?, type: PSPDFRenderType)

    Parameters

    options

    The render options to set. Will reset to defaults if set to nil.

    type

    The type you want to change. There are different render operation types.

  • Updates render options. Overrides new settings but does not destroy existing settings.

    Declaration

    Objective-C

    - (void)updateRenderOptions:
                (nonnull NSDictionary<PSPDFRenderOption, id> *)options
                           type:(PSPDFRenderType)type;

    Swift

    func updateRenderOptions(_ options: [PSPDFRenderOption : Any] = [:], type: PSPDFRenderType)

    Parameters

    options

    Settings to add/replace in the renderOptions dictionary.

    type

    The type you want to change.

  • Returns the render options for a specific type of operation.

    Declaration

    Objective-C

    - (nonnull NSDictionary<PSPDFRenderOption, id> *)
    renderOptionsForType:(PSPDFRenderType)type
                 context:(nullable id)context;

    Swift

    func renderOptions(for type: PSPDFRenderType, context: Any?) -> [PSPDFRenderOption : Any]

    Parameters

    type

    The specific operation type.

    context

    An optional context matching the operation type. For PSPDFRenderTypePage this is an NSNumber of the page.

    Return Value

    The render dictionary. Guaranteed to always return a dictionary.

  • Set what annotations should be rendered. Defaults to PSPDFAnnotationTypeAll.

    Declaration

    Objective-C

    @property (assign, readwrite, atomic) PSPDFAnnotationType renderAnnotationTypes;

    Swift

    var renderAnnotationTypes: PSPDFAnnotationType { get set }
  • Document title as shown in the controller. If this is not set, the framework tries to extract the title from the PDF metadata. If there’s no metadata, the fileName is used. .pdf endings will be removed either way. - note: Can be set to a custom value, in that case this overrides the PDF metadata. Custom titles don’t get saved into the PDF. Setting the custom title to nil will again use the predefined PDF contents.

    Declaration

    Objective-C

    @property (readwrite, copy, nonatomic, nullable) NSString *title;

    Swift

    var title: String? { get set }
  • Title might need to parse the file and is potentially slow. Use this to check if title is loaded and access title in a thread if not.

    Declaration

    Objective-C

    @property (readonly, getter=isTitleLoaded, atomic) BOOL titleLoaded;

    Swift

    var isTitleLoaded: Bool { get }
  • Returns a pre-set attribute set for easier Spotlight integration. Thumbnail rendering is optional and might take some time.

    Note

    Because this method might take a nontrivial amount of time to render the thumbnail image, you should call it from a background thread.

    Requires CoreSpotlight. - see: PSPDFLibrarySpotlightIndexer.coreSpotlightAvailableAtRuntime

    Declaration

    Objective-C

    - (nullable CSSearchableItemAttributeSet *)
    searchableItemAttributeSetWithThumbnail:(BOOL)renderThumbnail;

    Swift

    func searchableItemAttributeSet(withThumbnail renderThumbnail: Bool) -> CSSearchableItemAttributeSet?

    Parameters

    renderThumbnail

    Specifies whether the thumbnail should be rendered and included in the attribute set.

    Return Value

    An attribute set with properties set to match the PDFs metadata, as available. This does not contain the document’s text content. If the document is not a valid PDF, the method returns nil.

  • Use this to use specific subclasses instead of the default PSPDF* classes. e.g. add an entry of PSPDFAnnotationManager.class / MyCustomAnnotationManager.class to use the custom subclass. (MyCustomAnnotationManager must be a subclass of PSPDFAnnotationManager)

    @throws an exception if the overriding class is not a subclass of the overridden class. - note: Does not get serialized when saved to disk. Only set from the main thread, before you first use the object. Set up your class overrides before calling any other method on the document.

    Declaration

    Objective-C

    - (void)overrideClass:(nonnull Class)builtinClass
                withClass:(nonnull Class)subclass;

    Swift

    func overrideClass(_ builtinClass: AnyClass, with subclass: AnyClass)
  • Hook to modify/return a different document provider. Called each time a documentProvider is created (which is usually on first access, and cached afterwards) During PSPDFDocument lifetime, document providers might be created at any time, lazily, and destroyed when memory is low. This might be used to change the delegate of the PSPDFDocumentProvider.

    Declaration

    Objective-C

    - (nonnull PSPDFDocumentProvider *)didCreateDocumentProvider:
        (nonnull PSPDFDocumentProvider *)documentProvider;

    Swift

    func didCreateDocumentProvider(_ documentProvider: PSPDFDocumentProvider) -> PSPDFDocumentProvider
  • Register a block that is called in didCreateDocumentProvider:

    Warning

    This needs to be set very early, before the document providers have been created (thus, before accessing any properties like pageCount or setting it to the view controller)

    Declaration

    Objective-C

    @property (readwrite, copy, nonatomic, nullable) void (^)
        (PSPDFDocumentProvider *_Nonnull) didCreateDocumentProviderBlock;

    Swift

    var didCreateDocumentProviderBlock: ((PSPDFDocumentProvider) -> Void)? { get set }
  • Override to customize file name for the send via email feature.

    Declaration

    Objective-C

    - (nonnull NSString *)fileNameForIndex:(NSUInteger)fileIndex;

    Swift

    func fileName(for fileIndex: UInt) -> String
  • Enable/Disable undo. Set this before undoController is first accessed! Defaults to YES.

    Declaration

    Objective-C

    @property (getter=isUndoEnabled, assign, readwrite, nonatomic) BOOL undoEnabled;

    Swift

    var isUndoEnabled: Bool { get set }
  • The undo manager attached to the document. Set to nil, when undoEnabled is disabled. - note: Undo/Redo has a small performance impact since all annotation operations are tracked.

    Declaration

    Objective-C

    @property (readonly, atomic, nullable) PSPDFUndoController *undoController;

    Swift

    var undoController: PSPDFUndoController? { get }
  • To calculate pages between multiple document providers.

    Declaration

    Objective-C

    - (NSUInteger)relativePageIndexForPageAtIndex:(NSUInteger)pageIndex;

    Swift

    func relativePageIndexForPage(at pageIndex: UInt) -> UInt
  • Page binding describes the side on which a book would have its binding. It is used to describe the scroll direction and page layout in various views through out the framework.

    A page binding of PSPDFPageBindingRightEdge usually is found on PDFs with right to left writing systems as their main content, such as Arabic, but also in vertical systems such as Chinese, Japanese, and Korean.

    If you are not familiar with the differences between right-to-left (RTL/R2L) and left-to-right (LTR/L2R) writing systems, imagine a stack of paper. If you want to create a book out of this stack, you can add a binding either on the left or on the right side of the stack. If the writing on the pages has a RTL reading direction you would usually add the binding on the right side, if it has a LTR reading direction, you would usually add the binding on the left. This property controls exactly this, as a PDF is just a stack of pages.

    The default value is read from the PDF and is set to PSPDFPageBindingUnknown if the PDF does not provide this value, which will make the UI fall back to a default page layout.

    You can set this property to force a specific page binding on a document.

    Note

    If you set this property, make sure to call reloadData on any PSPDFViewController currently displaying this document.

    Declaration

    Objective-C

    @property (assign, readwrite, nonatomic) PSPDFPageBinding pageBinding;

    Swift

    var pageBinding: PSPDFPageBinding { get set }
  • Attached PSPDFKit instance.

    Declaration

    Objective-C

    @property (readonly, nonatomic) PSPDFKit *_Nonnull pspdfkit;

    Swift

    var pspdfkit: PSPDFKit { get }