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.

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

Note

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.
  • 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.

    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.

    Warning

    Using a large amount of data providers (50+) can negatively impact performance. The exact amount of well-performing data providers varies: It is dependant on the complexity of the used PDFs, and on the device. Such configurations should be tested, and the PDFs should be combined, if performance issues arise.

    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
  • The features this document allows and enables.

    Features are a set of functionality that are enabled or disabled based on the document’s permissions, the file path, the PSPDFKit license in use or other technical limitations.

    This object can be used to check these conditions at a central point and enable or disable buttons or other UI elements accordingly or change the behavior of certain functions in an app based on these conditions.

    Declaration

    Objective-C

    @property (readonly, nonatomic) PSPDFDocumentFeatures *_Nonnull features;

    Swift

    var features: PSPDFDocumentFeatures { get }
  • 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

    Subclassing Note: Uses fileIndexForPageAtIndex: and URLForFileIndex: internally.

    Declaration

    Objective-C

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

    Swift

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

    Declaration

    Objective-C

    - (PSPDFFileIndex)fileIndexForPageAtIndex:(PSPDFPageIndex)pageIndex;

    Swift

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

    Declaration

    Objective-C

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

    Swift

    func urlForFile(at fileIndex: FileIndex) -> 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

    - (nullable NSString *)fileNameForPageAtIndex:(PSPDFPageIndex)pageIndex;

    Swift

    func fileName(forPageAtIndex pageIndex: PageIndex) -> String?
  • Deletes the underlying files from the disk, including the document itself and all cache and metadata files.

    1) [self.pspdfkit.cache removeCacheForDocument:self]; 2) All files for set file URLs 3) The dataDirectory

    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 from the file.

    A data provider is the object that handles reading and writing actual data from and to a source such as a file or a remote location. It is always availabe even when the document is not loaded.

    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.

    A document provider is a representation of an actual PDF file. It uses a data provider to access the file’s data and gives access to a file’s model, such as pages, annotations, text, etc.

    Accessing this property will load the document if it is not loaded yet. It will then create the document providers representing the receiver.

    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:
        (PSPDFPageIndex)pageIndex;

    Swift

    func documentProviderForPage(at pageIndex: PageIndex) -> 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 }
  • 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.

    Learn More: https://pspdfkit.com/guides/ios/current/features/document-checkpointing/

    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<ObjCBool>) -> Void)? = nil) throws -> [NSNumber : [PSPDFAnnotation]]
  • 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:
        (PSPDFPageIndex)pageIndex;

    Swift

    func textParserForPage(at pageIndex: PageIndex) -> 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:(PSPDFPageIndex)pageIndex
              options:(nullable NSDictionary<NSString *, NSNumber *> *)options;

    Swift

    func objects(atPDFPoint pdfPoint: CGPoint, pageIndex: PageIndex, 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:(PSPDFPageIndex)pageIndex
             options:(nullable NSDictionary<NSString *, NSNumber *> *)options;

    Swift

    func objects(atPDFRect pdfRect: CGRect, pageIndex: PageIndex, 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 metadata like annotations are saved, if they cannot be stored in the PDF document. Defaults to &lt;AppDirectory&gt;/Library/PrivateDocuments/PSPDFKit. Cannot be nil.

    Note

    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
  • Controls if the disk cache should be used for this document.

    https://pspdfkit.com/guides/ios/current/customizing-the-interface/using-the-render-queue/

    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 }
  • Unlock documents with a password.

    If the password is correct, this method returns YES. Once unlocked, you cannot use this function to re-lock the document.

    If you attempt to unlock an already unlocked document, one of the following occurs: If the document is unlocked with full owner permissions, unlockWithPassword: does nothing and returns YES. The password string is ignored. If the document is unlocked with only user permissions, unlockWithPassword: attempts to obtain full owner permissions with the password string. If the string fails, the document maintains its user permissions. In either case, this method returns YES.

    After unlocking a document, you need to call reloadData on the PSPDFViewController.

    If you’re using multiple files or appendFile:, all new files will be unlocked with the password. This doesn’t harm if the document is already unlocked.

    If you have a mixture of files with multiple different passwords, you need to subclass didCreateDocumentProvider: and unlock the documentProvider directly there.

    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 document providers.

    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()
  • Indicates if the PDF document is encrypted. (= password protected)

    Note

    Only evaluates the first file if multiple files are set. Some documents can be encrypted but have an empty password set, which PSPDFKit will automatically unlock.

    Declaration

    Objective-C

    @property (readonly, atomic) BOOL isEncrypted;

    Swift

    var isEncrypted: Bool { 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 or disable bookmarks.

    This value controls whether bookmarks should be enabled. There might be other things preventing bookmarks from being enabled. Check the document’s features to see if bookmarks can be modified.

    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:(PSPDFPageIndex)pageIndex
                          substituteWithPlainLabel:(BOOL)substitute;

    Swift

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

    Declaration

    Objective-C

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

    Swift

    func page(forPageLabel pageLabel: String, partialMatching: Bool) -> PageIndex
  • 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.

    https://pspdfkit.com/guides/ios/current/features/javascript/

    Note

    Processing JavaScript can be slow for documents with a large number of document providers or scripts. Disabling in most cases will not have any negative effects.

    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)

    Note

    Uses each annotation’s absolutePage property to determine which page it should be added to. As a result, the page property of any added annotation will change when multiple documentProviders are set, and the annotation’s absolutePage falls outside the page-range managed by the first document provider.

    Declaration

    Objective-C

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

    Swift

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

    Parameters

    annotations

    An array of PSPDFAnnotation objects to be inserted.

    options

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

    Return Value

    When all annotations could be added to the document, this method returns YES and all objects in the array are guaranteed to be contained in the value returned by -allAnnotationsOfType: when passing PSPDFAnnotationTypeAll, until they are removed from the document. (Either by programmatically calling removeAnnotations:options: or by deleting the annotation through UI.)

  • Remove annotations from the backing PSPDFAnnotationProvider object(s).

    If the annotations have replies, those will be removed too. If you don’t want this copy the annotations you want to keep and add them back.

    Declaration

    Objective-C

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

    Swift

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

    Parameters

    annotations

    An array of PSPDFAnnotation objects to be removed.

    options

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

    Return Value

    When all annotations could be removed, this method returns YES and they will no longer be contained in the value returned by -allAnnotationsOfType: when passing PSPDFAnnotationTypeAll. If one or more annotations could not be deleted, this method will return NO. This might be the case for form annotations or other objects that return NO for isDeletable.

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

    Declaration

    Objective-C

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

    Swift

    func annotationsForPage(at pageIndex: PageIndex, type: AnnotationType) -> [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<PSPDFDocumentPageNumber,
                            NSArray<__kindof PSPDFAnnotation *> *> *)
    allAnnotationsOfType:(PSPDFAnnotationType)annotationType;

    Swift

    func allAnnotations(of annotationType: AnnotationType) -> [PSPDFDocumentPageNumber : [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.

    Internally, this method simply calls annotationsForPageAtIndex:type: and stops as soon as annotations within the filter critera are found.

    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, atomic) 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.

    Used by PSPDFNoteAnnotationViewController to determine if comments and reviews were left by the current user.

    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<PSPDFAnnotationWriteOptions, NSNumber *>
            *annotationWritingOptions;

    Swift

    var annotationWritingOptions: [PSPDFAnnotationWriteOptions : 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.

    Declaration

    Objective-C

    - (nullable UIImage *)
    imageForPageAtIndex:(PSPDFPageIndex)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: PageIndex, 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.

    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:(PSPDFPageIndex)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: PageIndex, 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: AnnotationType { get set }
  • Generates Instant JSON representing current changes in the documentProvider.

    Declaration

    Objective-C

    - (nullable NSData *)
    generateInstantJSONFromDocumentProvider:
        (nonnull PSPDFDocumentProvider *)documentProvider
                                      error:(NSError *_Nullable *_Nullable)error;

    Swift

    func generateInstantJSON(from documentProvider: PSPDFDocumentProvider) throws -> Data

    Parameters

    documentProvider

    The document provider from which the JSON should be generated.

    error

    A pointer to an NSError object that is set if an error occurred when generating the JSON.

    Return Value

    The generated JSON as an NSData object, or nil if there are no changes in the document currently, or on error occurred.

  • Applies the JSON received from the dataProvider.

    Declaration

    Objective-C

    - (BOOL)applyInstantJSONFromDataProvider:
                (nonnull id<PSPDFDataProviding>)dataProvider
                          toDocumentProvider:
                              (nonnull PSPDFDocumentProvider *)documentProvider
                                       error:(NSError *_Nullable *_Nullable)error;

    Swift

    func applyInstantJSON(fromDataProvider dataProvider: PSPDFDataProviding, to documentProvider: PSPDFDocumentProvider) throws

    Parameters

    dataProvider

    The data provider from which to extract the JSON data. See PSPDFFileDataProvider or PSPDFDataContainerProvider for common use cases.

    documentProvider

    The document provider (from the receiver’s documentProviders array to which the JSON needs to be applied.

    Return Value

    YES if application succeeded, else NO.

  • 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

    - (nullable NSString *)fileNameForIndex:(PSPDFFileIndex)fileIndex;

    Swift

    func fileName(for fileIndex: FileIndex) -> String?
  • Enable/Disable undo for annotations. Defaults to YES.

    Note

    Set this before undoController is first accessed.

    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

    - (PSPDFPageIndex)relativePageIndexForPageAtIndex:(PSPDFPageIndex)pageIndex;

    Swift

    func relativePageIndexForPage(at pageIndex: PageIndex) -> PageIndex
  • 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 singleton instance.

    Declaration

    Objective-C

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

    Swift

    var pspdfkit: PSPDFKit { get }