PSPDFDocument

Objective-C


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

Swift

class Document : NSObject, DocumentProviderDelegate, Overridable, NSCopying, NSSecureCoding, NSFastEnumeration, FileCoordinationDelegate

The Document 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.

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

Note

Not all state is archived with NSCoder.

Note

Ensure that a Document is only opened by one PDFViewController 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 Document with a single local file.

    This convenience initializer creates either a PSPDFCoordinatedFileDataProvider or a PSPDFFileDataProvider depending on if PSPDFSettingKeyFileCoordinationEnabled 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 Document. Document 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 Document 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: [DataProviding])

    Parameters

    dataProviders

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

    Return Value

    A new document object.

  • Initialize Document 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 number of data providers (50+) can negatively impact performance. The exact number of well-performing data providers varies: It is dependent 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: [DataProviding], 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: [DataProviding]) -> 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 (nonatomic, weak) 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 (nonatomic, readonly, getter=isValid) 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 (nonatomic, readonly, 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: Document) -> 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 (nonatomic, readonly) PSPDFDocumentFeatures *_Nonnull features;

    Swift

    var features: PSPDFDocumentFeatures { get }
  • Convenience accessor for the first fileURL of the document.

    Declaration

    Objective-C

    @property (nonatomic, readonly, 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 (nonatomic, readonly) 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 (nonatomic, readonly) NSArray<id<NSFilePresenter>> *_Nonnull filePresenters;

    Swift

    var filePresenters: [NSFilePresenter] { get }
  • A combined parent progress object for all registered data providers. This can be used to cancel any active progress operations when the document is dismissed.

    Note

    The progress is cancelled when all registered data providers’ progresses are cancelled.

    Warning

    Do not override this property. It returns a private NSProgress subclass with added functionality. Both this and other PSPDFKit classes rely on that behavior.

    Declaration

    Objective-C

    @property (nonatomic, readonly) 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 (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 (nonatomic, readonly, 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 (nonatomic, readonly, 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 (nonatomic, readonly) 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 (nonatomic, readonly) 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 available even when the document is not loaded.

    Note

    Data providers can also be used to dynamically decrypt a document.

    Declaration

    Objective-C

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

    Swift

    var dataProviders: [DataProviding] { 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 (nonatomic, readonly) NSArray<PSPDFDocumentProvider *> *_Nonnull documentProviders;

    Swift

    var documentProviders: [PDFDocumentProvider] { 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) -> PDFDocumentProvider?
  • Get the page offset from a specific documentProvider. Can be used to calculate from the document provider page to the Document page.

    Declaration

    Objective-C

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

    Swift

    func pageOffset(for documentProvider: PDFDocumentProvider) -> UInt
  • Reloads document providers from this document.

    All document providers that are reloaded will be replaced with a new instance.

    Declaration

    Objective-C

    - (void)reloadDocumentProviders:
                (nonnull NSArray<PSPDFDocumentProvider *> *)documentProviders
               dataProviderOverride:
                   (nullable id<PSPDFDataProviding> _Nonnull (^)(
                       PSPDFDocumentProvider *_Nonnull))dataProviderOverride;

    Swift

    func reload(documentProviders: [PDFDocumentProvider], dataProviderOverride: ((PDFDocumentProvider) -> DataProviding)? = nil)

    Parameters

    documentProviders

    The document providers to be replaced. They must be part of the current document. The document providers will be replaced with new during the reload.

    dataProviderOverride

    A block that offers a chance to replace the data provider during the document provider reload.

  • 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. If a document identifier is not available, generated UID value is returned.

    Note

    This value will stay persistent, if the document is modified, moved to a different location or duplicated. Therefore, it’s not guaranteed to be unique among multiple documents.

    Declaration

    Objective-C

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

    Swift

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

    Declaration

    Objective-C

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

    Swift

    var documentIdString: String? { get }
  • UID

    The unique UID for the document.

    By default, the UID is created automatically based on the content sources that are configured. If you already have unique identifiers for your documents, from a cloud storage provider, or other content management system, you can set a custom value here as well.

    When using custom UIDs, however, you should set them before the document is used/cached/displayed and have to make sure that the values are actually unique:
    Since the UID is used internally for the page renderer cache, and defines the filename for external annotation storage, UID collisions will cause problems down the line. And even when your custom UIDs are collision-free, you will either have to set a new UID or clear the cache if you change the PDF contents outside of PSPDFKit.

    Note

    This value might change, if the document is modified or moved to a different location.

    Warning

    Using the same UID for two or more documents that are backed by different PDF files is unsupported, and leads to undefined behavior. Modifying documents that suffer from a UID collision will likely result in data corruption!

    Declaration

    Objective-C

    @property (nonatomic, copy, 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

    PDFDocumentSaveOptionForceSaving

    See

    PDFDocumentSaveOptionStrategy

    See

    PDFDocumentSaveOptionSecurityOptions

    See

    PDFDocumentSaveOptionApplyRedactions

    See

    saveWithOptions:completionHandler:

    Declaration

    Objective-C

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

    Parameters

    options

    Passing nil for options is equivalent to passing an empty dictionary @{}. Available options are PDFDocumentSaveOptionForceSaving, PDFDocumentSaveOptionStrategy and PDFDocumentSaveOptionSecurityOptions, 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

    true if the save operation completed successfully, otherwise false 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;

    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 behavior you require.

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

    Declaration

    Objective-C

    @property (nonatomic, readonly) 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 (nonatomic, readonly, nullable) PSPDFOutlineElement *outline;

    Swift

    var outline: PSPDFOutlineElement? { get }
  • User activity that is associated with the document. Needs to be set externally.

    Note

    This activity will be attached to drag sessions originating from a tab containing this document in PSPDFTabbedViewController.

    Declaration

    Objective-C

    @property (nonatomic, nullable) NSUserActivity *userActivity;

    Swift

    var userActivity: NSUserActivity? { get set }
  • 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 (nonatomic) PSPDFTextCheckingType autodetectTextLinkTypes;

    Swift

    var autodetectTextLinkTypes: TextCheckingType { get set }
  • Iterates over all pages at indexes and creates new annotations for linkTypes. Will ignore any text that is intersecting with an already existing link annotation. 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 PSPDFObjectFinderTypeAnnotations 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<
                                        PSPDFObjectFinderType,
                                        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: TextCheckingType, forPagesAt indexes: IndexSet, options: [Document.ObjectFinderType : [NSNumber : [Annotation]]]? = nil, progress progressBlock: (([Annotation], UInt, UnsafeMutablePointer<ObjCBool>) -> Void)? = nil) throws -> [NSNumber : [Annotation]]
  • 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 false and send a support request (https://pspdfkit.com/support/request) with the misbehaving PDF file.

    Declaration

    Objective-C

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

    Swift

    var isWatermarkFilterEnabled: Bool { get set }
  • Fetches the text parser for the requested page index.

    Declaration

    Objective-C

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

    Swift

    func textParserForPage(at pageIndex: PageIndex) -> PSPDFTextParser?

    Parameters

    pageIndex

    The page index for which the text parser is required.

    Return Value

    An instance of PSPDFTextParser, if one could be created, else nil.

  • Find objects (glyphs, words, images, annotations) at the specified pdfPoint.

    Note

    Unless set otherwise, for points PSPDFObjectFinderOptionTestIntersection is YES automatically. If options is nil, we assume PSPDFObjectFinderOptionExtractText and PSPDFObjectFinderOptionExtractWords. Annotations with the Hidden or NoView flag are ignored. This method is thread safe.

    Declaration

    Objective-C

    - (nonnull NSDictionary<PSPDFObjectFinderType, id> *)
        objectsAtPDFPoint:(CGPoint)pdfPoint
                pageIndex:(PSPDFPageIndex)pageIndex
                  options:
                      (nullable NSDictionary<PSPDFObjectFinderOption, NSValue *> *)
                          options;

    Swift

    func objects(atPDFPoint pdfPoint: CGPoint, pageIndex: PageIndex, options: [Document.ObjectFinderOption : NSValue]? = nil) -> [Document.ObjectFinderType : Any]

    Parameters

    pdfPoint

    The point in PDF coordinates where we want to find the objects.

    pageIndex

    The page index where we want to find the objects.

    options

    Options dictionary. The PSPDFObjectFinderOption enum lists all the available options.

    Return Value

    A dictionary containing the matched objects. The exact return type for each PSPDFObjectFinderType is given below: PSPDFObjectFinderTypeGlyphs -> NSArray * PSPDFObjectFinderTypeText -> NSString * PSPDFObjectFinderTypeWords -> NSArray * PSPDFObjectFinderTypeTextBlocks -> NSArray * PSPDFObjectFinderTypeImages -> NSArray * PSPDFObjectFinderTypeAnnotations -> NSArray *

  • Find objects (glyphs, words, images, annotations) at the specified pdfRect.

    Note

    Unless set otherwise, for points PSPDFObjectFinderOptionTestIntersection is YES automatically. If options is nil, we assume PSPDFObjectFinderTypeExtractGlyphs only. Annotations with the Hidden or NoView flag are ignored. This method is thread safe.

    Declaration

    Objective-C

    - (nonnull NSDictionary<PSPDFObjectFinderType, id> *)
        objectsAtPDFRect:(CGRect)pdfRect
               pageIndex:(PSPDFPageIndex)pageIndex
                 options:
                     (nullable NSDictionary<PSPDFObjectFinderOption, NSValue *> *)
                         options;

    Swift

    func objects(atPDFRect pdfRect: CGRect, pageIndex: PageIndex, options: [Document.ObjectFinderOption : NSValue]? = nil) -> [Document.ObjectFinderType : Any]

    Parameters

    pdfRect

    The rect in PDF coordinates where we want to find the objects.

    pageIndex

    The page index where we want to find the objects.

    options

    Options dictionary. The PSPDFObjectFinderOption enum lists all the available options.

    Return Value

    A dictionary containing the matched objects. The exact return type for each PSPDFObjectFinderType is given below: PSPDFObjectFinderTypeGlyphs -> NSArray * PSPDFObjectFinderTypeText -> NSString * PSPDFObjectFinderTypeWords -> NSArray * PSPDFObjectFinderTypeTextBlocks -> NSArray * PSPDFObjectFinderTypeImages -> NSArray * PSPDFObjectFinderTypeAnnotations -> NSArray *

  • Will clear all cached objects (documentProviders, annotations, pageCount, outline, textParser, …)

    Warning

    Calling this method will also destroy any unsaved annotations. It will, however, not automatically reload the PDFViewController. For that, manually call reloadData afterwards.

    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 (nonatomic, copy) 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 (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 PDFViewController.

    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) 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) BOOL isLocked;

    Swift

    var isLocked: Bool { get }
  • Specifies if the document has been unlocked with full access.

    Declaration

    Objective-C

    @property (readonly) BOOL isUnlockedWithFullAccess;

    Swift

    var isUnlockedWithFullAccess: Bool { get }
  • Specifies what functions are allowed for a PDF document.

    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) PSPDFDocumentPermissions permissions;

    Swift

    var permissions: DocumentPermissions { 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) 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 (nonatomic, assign, unsafe_unretained, readwrite,
              getter=areBookmarksEnabled) 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, nullable) PSPDFBookmarkManager *bookmarkManager;

    Swift

    var bookmarkManager: PSPDFBookmarkManager? { get }
  • Returns the bookmarks.

    Note

    The Bookmark objects themselves are not changed, only those who are not visible are filtered out.

    Declaration

    Objective-C

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

    Swift

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

    Declaration

    Objective-C

    @property (atomic, assign, unsafe_unretained, readwrite,
              getter=arePageLabelsEnabled) 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) BOOL formsEnabled;

    Swift

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

    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 PSPDFJavaScriptStatus javaScriptStatus;

    Swift

    var javaScriptStatus: Document.JavaScriptStatus { get set }
  • Returns if JavaScript is enabled on this document.

    Declaration

    Objective-C

    @property (nonatomic, readonly) BOOL isJavaScriptStatusEnabled;

    Swift

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

    Declaration

    Objective-C

    @property (readonly, 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 PDFConfiguration.

    Declaration

    Objective-C

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

    Swift

    var areAnnotationsEnabled: Bool { get set }
  • Add annotations to the current document (and the backing store PSPDFAnnotationProvider)

    Note

    Uses each annotation’s absolutePageIndex property to determine which page it should be added to. As a result, the pageIndex property of any added annotation will change when multiple documentProviders are set, and the annotation’s absolutePageIndex 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: [Annotation], options: [AnnotationManager.ChangeBehaviorKey : 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 true 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.)

  • Insert annotation to the current document (and the backing store PSPDFAnnotationProvider) at the specified z-index.

    Note

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

    Declaration

    Objective-C

    - (BOOL)insertAnnotation:(nonnull PSPDFAnnotation *)annotation
                    atZIndex:(NSUInteger)destinationIndex
                     options:
                         (nullable NSDictionary<PSPDFAnnotationOption, id> *)options
                       error:(NSError *_Nullable *_Nullable)error;

    Swift

    func insert(_ annotation: Annotation, atZIndex destinationIndex: UInt, options: [AnnotationManager.ChangeBehaviorKey : Any]? = nil) throws

    Parameters

    annotation

    An PSPDFAnnotation object to be inserted.

    destinationIndex

    The z-index the annotation should be inserted at.

    options

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

    Return Value

    When all annotations could be added to the document, this method returns true 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: [Annotation], options: [AnnotationManager.ChangeBehaviorKey : 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 true 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 false. This might be the case for form annotations or other objects that return false for isDeletable.

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

    Returns an empty array if there are no matching annotations on the given pageIndex, or if pageIndex is invalid.

    Declaration

    Objective-C

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

    Swift

    func annotationsForPage(at pageIndex: PageIndex, type: Annotation.Kind) -> [Annotation]
  • 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: Annotation.Kind) -> [PSPDFDocumentPageNumber : [Annotation]]
  • 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 criteria are found.

    Declaration

    Objective-C

    @property (nonatomic, readonly) 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) 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) BOOL canSaveAnnotations;

    Swift

    var canSaveAnnotations: Bool { get }
  • Controls if and where annotations will be saved. The default is PSPDFAnnotationSaveModeEmbeddedWithExternalFileAsFallback. To prevent data loss, annotation editing will be disabled in the UI if this is set to PSPDFAnnotationSaveModeDisabled.

    Note

    PSPDFKit automatically saves the document for various events. See autosaveEnabled in PDFConfiguration.

    Declaration

    Objective-C

    @property PSPDFAnnotationSaveMode annotationSaveMode;

    Swift

    var annotationSaveMode: Document.AnnotationSaveMode { get set }
  • Default annotation username for new annotations.

    This property is initialized to the value stored in NSUserDefaults.standardUserDefaults under the PDFDocumentDefaultAnnotationUsernameKey. If unset, a guess is made based on the device name.

    Written as the “T” (title/user) property of newly created annotations.

    This value is also used by PSPDFNoteAnnotationViewController to determine if comments and reviews were left by the current user.

    Declaration

    Objective-C

    @property (copy, 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 @{PSPDFAnnotationWriteOptionGenerateAppearanceStreamForType: @(PSPDFAnnotationTypeFreeText|PSPDFAnnotationTypeInk|PSPDFAnnotationTypePolygon|PSPDFAnnotationTypePolyLine|PSPDFAnnotationTypeLine|PSPDFAnnotationTypeSquare|PSPDFAnnotationTypeCircle|PSPDFAnnotationTypeStamp|PSPDFAnnotationTypeWidget)}

    Declaration

    Objective-C

    @property (copy, nullable) NSDictionary<PSPDFAnnotationWriteOption, NSNumber *> *annotationWritingOptions;

    Swift

    var annotationWritingOptions: [Document.AnnotationWriteOption : 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 (nonatomic, readonly) 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 NSImage *)
        imageForPageAtIndex:(PSPDFPageIndex)pageIndex
                       size:(CGSize)size
              clippedToRect:(CGRect)clipRect
                annotations:(nullable NSArray<PSPDFAnnotation *> *)annotations
                    options:(nullable PSPDFRenderOptions *)options
                      error:(NSError *_Nullable *_Nullable)error;

    Swift

    func imageForPage(at pageIndex: PageIndex, size: CGSize, clippedTo clipRect: CGRect, annotations: [Annotation]?, options: RenderOptions?) 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 PSPDFRenderOption). 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 PSPDFRenderOptions *)options
                        error:(NSError *_Nullable *_Nullable)error;

    Swift

    func renderPage(at pageIndex: PageIndex, context: CGContext, size: CGSize, clippedTo clipRect: CGRect, annotations: [Annotation]?, options: RenderOptions?) 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 PSPDFRenderOption). 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.

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

    Declaration

    Objective-C

    - (void)setRenderOptions:(nullable PSPDFRenderOptions *)options
                        type:(PSPDFRenderType)type;

    Swift

    func setRenderOptions(_ options: RenderOptions?, type: RenderType)

    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 the render options with the instance returned from block. The PSPDFRenderOptions passed to block is a copy, and modifying it does not affect the options in the document.

    Declaration

    Objective-C

    - (void)updateRenderOptionsForType:(PSPDFRenderType)type
                             withBlock:(nonnull void (^)(
                                           PSPDFRenderOptions *_Nonnull))block;

    Swift

    func updateRenderOptions(for type: RenderType, with block: @escaping (RenderOptions) -> Void)

    Parameters

    type

    The type you want to change.

    block

    Returns the options to apply to the given type.

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

    Declaration

    Objective-C

    - (nonnull PSPDFRenderOptions *)renderOptionsForType:(PSPDFRenderType)type;

    Swift

    func renderOptions(forType type: RenderType) -> RenderOptions

    Parameters

    type

    The specific operation type.

    Return Value

    The render options object. Guaranteed to always return a valid instance.

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

    Non-rendered annotations will not be shown on pages and will not be exposed to accessibility (e.g. VoiceOver) but will still be included in the annotation list (AnnotationTableViewController) and may be shown on pages if selected using the annotation list.

    Declaration

    Objective-C

    @property PSPDFAnnotationType renderAnnotationTypes;

    Swift

    var renderAnnotationTypes: Annotation.Kind { 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: PDFDocumentProvider) 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.

  • Attempts to update the document provider applying the JSON received from the data provider.

    The lenient parameter controls the behavior when the JSON contains (partially) invalid entries:

    If false is passed, applying the JSON fails, and the document provider remains unmodified. The error will contain a detailed report of all the inconsistencies that have been found in the JSON. In general, this is the behavior you want to use in your production environment.

    If true is passed as the lenient parameter, all data from the JSON that could still be used is applied to the document provider. Inconsistencies that are encountered are merely logged as warnings, and the call will “succeed” as long as the JSON has more or less the expected structure. This behavior is mostly useful during development, and should only be used in production with great caution. It is meant as a “use at your own risk” last resort in data recovery scenarios after a call that passed false has failed, in order to preserve as much information from the JSON as possible.

    Note

    A call where lenient is true can still fail! One such occasion would be if the data provider does not contain a JSON object.

    Declaration

    Objective-C

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

    Swift

    func applyInstantJSON(fromDataProvider dataProvider: DataProviding, to documentProvider: PDFDocumentProvider, lenient: Bool) throws

    Parameters

    dataProvider

    The data provider from which to extract the JSON data. For common use cases, see PSPDFFileDataProvider or PSPDFDataContainerProvider.

    documentProvider

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

    lenient

    Whether (partially) invalid JSON should still be applied. When in doubt, pass false!

    Return Value

    true if application succeeded, else false.

  • The document’s user-facing title.

    If the PDFConfiguration property allowToolbarTitleChange is enabled, then a PDFViewController will sets its title to the title of the current document. The title will then be shown in the navigation bar.

    If this is not set programmatically, PSPDFKit looks for a title in the PDF metadata. If there’s no metadata, the file name 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 (nonatomic, copy, nullable) NSString *title;

    Swift

    var title: String? { get set }
  • Whether the title has been parsed from the PDF file.

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

    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<PSPDFOverridable>)builtinClass
                withClass:(nullable Class)subclass;

    Swift

    func overrideClass(_ builtinClass: Overridable.Type, 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 Document 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.

    @warning: If reloadDocumentProvider:dataProvider: is used, this must return the same document provider as passed in. Modifying properties is allowed.

    Declaration

    Objective-C

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

    Swift

    func didCreateDocumentProvider(_ documentProvider: PDFDocumentProvider) -> PDFDocumentProvider
  • 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 (nonatomic, copy, nullable) void (^) (PSPDFDocumentProvider *_Nonnull) didCreateDocumentProviderBlock;

    Swift

    var didCreateDocumentProviderBlock: ((PDFDocumentProvider) -> 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 (nonatomic, getter=isUndoEnabled) 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, 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 PDFViewController currently displaying this document.

    Declaration

    Objective-C

    @property (nonatomic) PSPDFPageBinding pageBinding;

    Swift

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

    Declaration

    Objective-C

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

    Swift

    var pspdfkit: PSPDFKitGlobal { get }
  • Load document-level JavaScript actions.

    Declaration

    Objective-C

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

    Swift

    func loadLevelJavaScriptActions() throws
  • Performs conflict resolution on the provided data provider and updates internal document state and caches.

    Note

    Passing PSPDFFileConflictResolutionSave does nothing if a file copy is not currently available on the data provider (isConflictResolutionAvailable == NO).

    Declaration

    Objective-C

    - (BOOL)resolveFileConflictForDataProvider:
                (nonnull id<PSPDFCoordinatedFileDataProviding>)dataProvider
                                withResolution:
                                    (PSPDFFileConflictResolution)resolution
                                         error:(NSError *_Nullable *_Nullable)error;

    Swift

    func resolveFileConflict(forDataProvider dataProvider: CoordinatedFileDataProviding, with resolution: FileConflictResolution) throws

    Parameters

    dataProvider

    The document’s data provider that detected the file change.

    resolution

    The conflict resolution option that should be performed.

    error

    An optional error describing the failure.

    Return Value

    YES, if the resolution was successful and no otherwise.

  • Initialize Document with a single local file.

    This convenience initializer creates either a CoordinatedFileDataProvider or a FileDataProvider depending on if SDK.Setting.fileCoordinationEnabled is set on the SDK shared object.

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

    Declaration

    Swift

    public convenience init(url: URL, loadCheckpointIfAvailable loadCheckpoint: Bool = false)

    Parameters

    url

    A local file URL of a PDF document.

    loadCheckpoint

    Specifies whether an available checkpoint should be loaded.

    Return Value

    A new document object.

  • Save option convenience enum. See PDFDocumentSaveOption for additional details.

    See more

    Declaration

    Swift

    public enum SaveOption : Hashable
  • Saves the document synchronously.

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

    Throws

    If a save error occurs.

    @throws NSInternalInconsistencyException if save options are not valid.

    Declaration

    Swift

    public func save(options: Set<SaveOption> = []) throws

    Parameters

    options

    See SaveOption documentation for more details.

  • Saves the document asynchronously.

    An asynchronous version for save(options:). Does not block the calling thread.

    Saves the document and all of its linked data, including bookmarks and annotations, asynchronously. Does not block the calling thread.

    Declaration

    Swift

    public func save(options: Set<SaveOption> = [], completion: @escaping (Result<[Annotation], Error>) -> Void)

    Parameters

    options

    See SaveOption documentation for more details.

    completion

    Called on the main thread after the save operation finishes.

  • Declaration

    Swift

    public var objectWillChange: ObservableObjectPublisher { get }
  • This publisher fires whenever the document is saved either to disk or to the attached data providers, or if saving fails. Saving can happen multiple times. An error doesn’t end the stream.

    Declaration

    Swift

    var savePublisher: AnyPublisher<Result<Void, Error>, Never> { get }
  • Change event to indicate addition, removal or change events.

    See more

    Declaration

    Swift

    enum AnnotationChangeEvent
  • Fires with an AnnotationChangeEvent whenever an annotation is added, removed or changed.

    Declaration

    Swift

    var annotationChangePublisher: AnyPublisher<AnnotationChangeEvent, Never> { get }