### Getting Started with Nutrient iOS PDF SDK Playground Source: https://www.nutrient.io/guides/ios/samples Explore the getting started guide for the Nutrient iOS SDK, featuring essential code samples in Swift and Objective-C. This playground provides a foundation for enhancing your app development with PDF functionalities. It serves as an entry point for new developers. ```swift // Swift code example for the playground would go here. ``` ```objective-c // Objective-C code example for the playground would go here. ``` -------------------------------- ### Initialize All Document Actions Source: https://www.nutrient.io/guides/ios/pspdfkit-instant/getting-started A main initialization function that calls other setup functions when the DOM is fully loaded. It ensures that all interactive elements and their corresponding event listeners are set up correctly. ```javascript document.addEventListener("DOMContentLoaded",()=>{ I(), A() }) ``` -------------------------------- ### Initialize Carthage for Nutrient Integration Source: https://www.nutrient.io/guides/ios/best-practices/carthage-integration This snippet demonstrates the initial setup for integrating Nutrient using Carthage. It involves creating a Cartfile and defining the dependency. Ensure you have Carthage installed and configured correctly. ```bash # Cartfile github "nutrient-io/nutrient-ios" "~> 1.0.0" ``` -------------------------------- ### Setup PDF E-Reader in Swift Source: https://www.nutrient.io/guides/ios/samples Learn how to set up PSPDFKit as an e-reader with a Swift example. Explore resources on building an e-reader app. ```swift /* Note: The actual code for setting up an e-reader is not provided in the text. This is a placeholder to indicate where such a snippet would go. Example: // let pdfFilePath = Bundle.main.path(forResource: "my_book", ofType: "pdf")! // let document = try! PSPDFDocument(path: pdfFilePath) // let pdfViewController = PSPDFViewController(document: document) // // Configure pdfViewController for e-reader experience (e.g., disable annotations, customize UI) // present(pdfViewController, animated: true, completion: nil) */ ``` -------------------------------- ### Swift Configuration for Nutrient iOS Example App Source: https://www.nutrient.io/guides/ios/pspdfkit-instant/getting-started This Swift code snippet, likely from AppDelegate.swift, configures the server URL and base URL for the Nutrient iOS example app. It's crucial for connecting the iOS app to the backend server, enabling features like document synchronization. Ensure 'localhost' is replaced with the correct network address when running on a physical device. ```swift // Example of serverURL and baseURL configuration in AppDelegate.swift // Replace 'localhost' with your server's IP address when needed. let serverURL = "http://localhost:8080" let baseURL = "http://localhost:8080" ``` -------------------------------- ### Initiate ChatGPT Chat with Documentation Context (JavaScript) Source: https://www.nutrient.io/guides/ios/json/schema/bookmarks Opens a new browser tab with ChatGPT, pre-populated with a prompt that includes the current Nutrient.io documentation URL and a request for assistance with it. This allows users to quickly start a conversation with ChatGPT about the documentation they are viewing. The prompt is designed to guide the AI in providing relevant explanations, examples, or debugging help. ```javascript function v(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; window.open(`https://chatgpt.com/?q=${encodeURIComponent(r)}`,"_blank") } ``` -------------------------------- ### SwiftUI Annotation Toolbar Example Setup Source: https://www.nutrient.io/guides/ios/samples/swiftui-annotationt-toolbar Initializes an example class for the SwiftUI custom annotation toolbar. This class is responsible for setting up the title, description, category, and priority of the example, and for invoking the SwiftUI view when the example is run. ```swift private let logger = Logger(subsystem: "com.pspdfkit.catalog", category: "swiftui-toolbar-example") class SwiftUIAnnotationToolbarExample: Example { override init() { super.init() title = "SwiftUI Custom Annotation Toolbar Example" contentDescription = "Shows how to show a custom annotation toolbar in SwiftUI." category = .swiftUI priority = 11 } override func invoke(with delegate: ExampleRunnerDelegate) -> UIViewController? { let document = AssetLoader.writableDocument(for: .welcome, overrideIfExists: false) let swiftUIView = SwiftUIAnnotationToolbarExampleView(document: document) return UIHostingController(rootView: swiftUIView, largeTitleDisplayMode: .never) } } ``` -------------------------------- ### iOS Office Document Conversion Example Setup (Swift) Source: https://www.nutrient.io/guides/ios/samples/office-to-pdf-conversion This Swift code sets up an example for Office document conversion in an iOS application. It defines the title, description, category, and priority for the example, and specifies the view controller to be used when the example is invoked. ```swift class OfficeDocumentConversionExample: Example { override init() { super.init() title = "Office File Conversion" contentDescription = "Shows how to convert an Office file to PDF using Nutrient Document Engine." category = .documentProcessing priority = 15 } override func invoke(with delegate: ExampleRunnerDelegate) -> UIViewController? { let controller = OfficeDocumentPickerTableViewController(style: .grouped) controller.title = self.title return controller } } ``` -------------------------------- ### Swift Playground Example for Nutrient iOS SDK Source: https://www.nutrient.io/guides/ios/samples/playground This Swift code defines a 'PlaygroundExample' class that inherits from 'Example'. It's used to set up a sample PDF document and present it using 'AdaptivePDFViewController' from the PSPDFKit UI library. It demonstrates initializing the controller with a specific document and a custom configuration, including setting a 'signatureStore' to 'KeychainSignatureStore'. ```swift // // Copyright © 2017-2025 PSPDFKit GmbH. All rights reserved. // // The Nutrient sample applications are licensed with a modified BSD license. // Please see License for details. This notice may not be removed from this file. // // See 'PSCObjectiveCExample.m' for the Objective-C version of this example. // import PSPDFKit import PSPDFKitUI class PlaygroundExample: Example { override init() { super.init() title = "Playground" contentDescription = "Start here!" category = .top targetDevice = [.vision, .phone, .pad] priority = 1 } override func invoke(with delegate: ExampleRunnerDelegate) -> UIViewController { // Playground is convenient for testing let document = AssetLoader.writableDocument(for: .welcome, overrideIfExists: false) let controller = AdaptivePDFViewController(document: document) { // Use the configuration to set main options for the Nutrient UI. $0.signatureStore = KeychainSignatureStore() } return controller } } ``` -------------------------------- ### Initiate Claude.ai Chat with Documentation Context (JavaScript) Source: https://www.nutrient.io/guides/ios/json/schema/bookmarks Opens a new browser tab with Claude.ai, pre-populated with a prompt that includes the current Nutrient.io documentation URL and a request for assistance. This facilitates users starting a focused conversation with Claude about the documentation content, enabling them to seek explanations, examples, or debugging support. ```javascript function x(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; window.open(`https://claude.ai/new?q=${encodeURIComponent(r)}`,"_blank") } ``` -------------------------------- ### SwiftUI Sidebar Example Setup Source: https://www.nutrient.io/guides/ios/samples/swiftui-sidebar This Swift code defines an example class `SwiftUISidebarExample` that conforms to the `Example` protocol. It configures the example's title, description, category, and presentation style, and prepares a SwiftUI view for display within a `UIHostingController`. It also sets up a Combine sink to handle dismissal notifications. ```swift import Combine import PSPDFKit import PSPDFKitUI import SwiftUI private extension NSNotification.Name { static let DismissHostingController = NSNotification.Name("DismissHostingControllerNotification") } class SwiftUISidebarExample: Example { override init() { super.init() title = "SwiftUI Sidebar Example" contentDescription = "Shows how to show a PDFView in SwiftUI with sidebar." category = .swiftUI priority = 10 // We present this modal, as SwiftUI controls the navigation controller here. wantsModalPresentation = true embedModalInNavigationController = false } private var dismissSink: AnyCancellable? override func invoke(with delegate: ExampleRunnerDelegate) -> UIViewController? { let document = AssetLoader.document(for: .welcome) let swiftUIView = SwiftUISidebarExampleView(document: document) let hostingController = DismissableHostingViewController(rootView: swiftUIView) hostingController.modalPresentationStyle = .fullScreen dismissSink = NotificationCenter.default.publisher(for: .DismissHostingController) .sink { _ in hostingController.dismiss(animated: true, completion: nil) } return hostingController } } ``` -------------------------------- ### Nutrient Instant Usage on iOS Source: https://context7_llms Detailed instructions and code examples for using Nutrient Instant on iOS. This guide provides a comprehensive overview of the Nutrient iOS SDK's instant features. ```swift // Example Swift code demonstrating basic usage of Nutrient Instant // Requires Nutrient iOS SDK import NutrientSDK // Initialize Nutrient Instant NutrientInstant.sharedInstance().initialize(apiKey: "YOUR_API_KEY") // Load a document with Instant capabilities NutrientInstant.sharedInstance().loadDocument("document.pdf") { (document, error) in if let document = document { // Document loaded, ready for Instant features print("Document loaded successfully for Instant sync.") } else if let error = error { print("Error loading document: \(error.localizedDescription)") } } ``` -------------------------------- ### Open Claude AI with Context (JavaScript) Source: https://www.nutrient.io/guides/ios/best-practices/transferring-file-edits-to-a-server Opens a new tab with Claude AI, pre-populated with a prompt asking for help understanding the current Nutrient IO documentation page. Dependencies: `window.location`, `encodeURIComponent`, `window.open`. ```javascript function x(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; const s=`https://claude.ai/new?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Implement PDF Analytics Client in Swift Source: https://www.nutrient.io/guides/ios/samples Example implementation of `PDFAnalyticsClient` that logs events to the console in iOS. Get additional resources by visiting our guide on iOS PDF viewer analytics. ```swift import PSPDFKit class ConsoleAnalyticsClient: PSAnalyticsClient { func logEvent(_ event: PSAnalyticsEvent) { print("Analytics Event: \(event.name)") if let metadata = event.metadata { print(" Metadata: \(metadata)") } } } // To use it: // let pdfDocument: PDFDocument // pdfDocument.analyticsClient = ConsoleAnalyticsClient() ``` -------------------------------- ### PSPDFKit Examples Source: https://www.nutrient.io/guides/ios/changelog Updates and additions to example code for PSPDFKit. ```APIDOC ## Examples Updates ### Digital Signature Configuration Example - **Description**: Added `DigitalSignatureConfigurationExample` to demonstrate customization options for digital signing. - **Endpoint**: Not applicable (new example) - **Method**: Not applicable (new example) ### Drawn Signatures Thinness Fix - **Description**: Fixed an issue where drawn signatures appeared very thin in the Sign All Pages Catalog example. - **Endpoint**: Not applicable (example bug fix) - **Method**: Not applicable (example bug fix) ``` -------------------------------- ### Instant API Overview Source: https://www.nutrient.io/guides/ios/open-a-document/from-document-engine This section outlines the general lifecycle of documents when using the Instant API and provides detailed usage instructions. ```APIDOC ## Document Lifecycle When using a PDF file managed by Instant, you might go through these stages: * Obtaining a JSON Web Token (JWT) for a layer from your server. * Obtaining a document descriptor for the layer encoded in the JWT from the [`InstantClient`](/api/ios/documentation/instant/instantclient). * Using the document descriptor to download the layer data with the JWT. * Showing the document descriptor’s [`editableDocument`](/api/ios/documentation/instant/instantdocumentdescriptor/editabledocument) and synchronizing annotations. * Updating the JWT to keep synchronizing annotations. * Losing access to the layer. * Clearing the local storage for the layer or the document identifier. You can read more about the lifecycle of a document descriptor in our guide on [document state](/guides/ios/pspdfkit-instant/instant-document-state/). ## Detailed Use After signing in to your server and getting the JWT for the layer you want to show to the user, obtain a matching document descriptor from Instant. ``` -------------------------------- ### Getting Started with PDFLibrary Source: https://www.nutrient.io/guides/ios/features/indexed-full-text-search This section covers the initial setup for PSPDFKit's full-text search feature, focusing on data sources. ```APIDOC ## PDFLibrary Full-Text Search Guide ### Description PSPDFKit provides a powerful full-text search (FTS) capability for PDF documents through the `PDFLibrary` class. This guide details how to set up and utilize this feature, starting with the data source configuration. ### Method N/A (Configuration Guide) ### Endpoint N/A (Configuration Guide) ### Parameters N/A (Configuration Guide) ### Request Example N/A (Configuration Guide) ### Response N/A (Configuration Guide) ## SWIFT Implementation ### Description This example demonstrates how to initialize and configure the `LibraryFileSystemDataSource` in Swift to index PDF documents from a directory. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example ```swift guard let library = PSPDFKit.SDK.shared.library else { // FTS feature isn't enabled in your license. return } // Assume that you have a directory of PDF documents you want to index. let directoryURL = ... // Replace with your actual directory URL let dataSource = LibraryFileSystemDataSource(library: library, documentsDirectoryURL: directoryURL) { document, stopPointer in // If you want to skip a specific document, return `false` here. // If you want to stop the directory enumeration, set `stopPointer.pointee` to `true`. return true } library.dataSource = dataSource // Note that `PDFLibrary` holds the data source with a strong reference. // Begins the indexing operation. This method performs some initial work synchronously and then starts the indexing, which is asynchronous. // For large amounts of documents, even the initial work could be slow, which is why this should always be called on a background queue. DispatchQueue.global(qos: .background).async { library.updateIndex() } ``` ### Response N/A (Code Example) ## OBJECTIVE-C Implementation ### Description This example shows how to set up the `PSPDFLibraryFileSystemDataSource` in Objective-C for indexing PDF documents from a specified directory. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example ```objectivec PSPDFLibrary *library = PSPDFKitGlobal.sharedInstance.library; if (!library) { // FTS feature isn't enabled in your license. return; } // Assume that you have a directory of PDF documents you want to index. NSURL *directoryURL = ...; // Replace with your actual directory URL PSPDFLibraryFileSystemDataSource *fileDataSource = [[PSPDFLibraryFileSystemDataSource alloc] initWithLibrary:library documentsDirectoryURL:directoryURL documentHandler:^(PSPDFDocument *document, BOOL *stop) { // If you want to skip a specific document, return `NO` here. // If you want to stop the directory enumeration, set `*stop` to `YES`. return YES; }]; library.dataSource = fileDataSource; // Note that `PSPDFLibrary` holds the data source with a strong reference. ``` ### Response N/A (Code Example) ``` -------------------------------- ### Open Grok AI with Context (JavaScript) Source: https://www.nutrient.io/guides/ios/best-practices/transferring-file-edits-to-a-server Opens a new tab with Grok AI, pre-populated with a prompt asking for help understanding the current Nutrient IO documentation page. Dependencies: `window.location`, `encodeURIComponent`, `window.open`. ```javascript function C(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; const s=`https://grok.com/c?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Objective-C Playground Example for Nutrient iOS SDK Source: https://www.nutrient.io/guides/ios/samples/playground This Objective-C code defines a 'PSCObjectiveCExample' class that inherits from 'PSCExample'. It mirrors the Swift 'PlaygroundExample' by setting up a sample PDF document and presenting it using 'PSCAdaptivePDFViewController'. The example demonstrates initializing the controller with a document and a PSPDFKit configuration, specifically configuring the 'signatureStore' to use 'PSPDFKeychainSignatureStore'. ```objectivec // // Copyright © 2015-2025 PSPDFKit GmbH. All rights reserved. // // The Nutrient sample applications are licensed with a modified BSD license. // Please see License for details. This notice may not be removed from this file. // // See 'PlaygroundExample.swift' for the Swift version of this example. // @import PSPDFKit; @import PSPDFKitUI; #import "Catalog-Swift.h" #import "PSCExample.h" @interface PSCObjectiveCExample : PSCExample @end @implementation PSCObjectiveCExample - (instancetype)init { if ((self = [super init])) { self.title = @"Objective-C Playground"; self.contentDescription = @"Alternatively, start here."; self.category = PSCExampleCategoryTop; self.targetDevice = PSCExampleTargetDeviceMaskVision | PSCExampleTargetDeviceMaskPhone | PSCExampleTargetDeviceMaskPad; self.priority = 2; } return self; } - (nullable UIViewController *)invokeWithDelegate:(id)delegate { // Playground is convenient for testing. PSPDFDocument *document = [PSCAssetLoader writableDocumentWithName:PSCAssetNameWelcome overrideIfExists:NO]; PSPDFConfiguration *configuration = [PSPDFConfiguration configurationWithBuilder:^(PSPDFConfigurationBuilder *builder) { // Use the configuration to set main options for the Nutrient UI. builder.signatureStore = [[PSPDFKeychainSignatureStore alloc] init]; }]; PSPDFViewController *controller = [[PSCAdaptivePDFViewController alloc] initWithDocument:document configuration:configuration]; return controller; } @end ``` -------------------------------- ### iOS Swift: Initialize Nutrient Instant Example Source: https://www.nutrient.io/guides/ios/samples/pdf-collaboration Initializes the Nutrient Instant example class, setting properties like title, description, category, target device, and priority. This is the entry point for the example's configuration. ```swift class InstantExample: Example { override init() { super.init() title = "Nutrient Instant" contentDescription = "Downloads a document for collaborative editing." category = .collaboration targetDevice = [.vision, .phone, .pad] priority = 1 } weak var presentingViewController: UIViewController? override func invoke(with delegate: ExampleRunnerDelegate) -> UIViewController? { let presentingViewController = delegate.currentViewController! if let docInfoDict = UserDefaults.standard.object(forKey: InstantExampleLastViewedDocumentInfoKey) as? [String: String], let lastViewDocumentInfo = InstantDocumentInfo(from: docInfoDict) { presentInstantViewController(for: lastViewDocumentInfo, on: presentingViewController) } else { presentNewSession(on: presentingViewController) } self.presentingViewController = presentingViewController return nil } } ``` -------------------------------- ### Open ChatGPT with Context Source: https://www.nutrient.io/guides/ios/customizing-the-interface/customizing-the-annotation-table-view-controller Opens a new tab with ChatGPT, pre-filled with a prompt that includes the current Nutrient IO documentation URL and a request for assistance. The prompt asks the AI to be ready to explain concepts, give examples, or help debug based on the provided documentation. ```javascript function v(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; s=`https://chatgpt.com/?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Open ChatGPT with Context (JavaScript) Source: https://www.nutrient.io/guides/ios/best-practices/transferring-file-edits-to-a-server Opens a new tab with ChatGPT, pre-populated with a prompt asking for help understanding the current Nutrient IO documentation page. Dependencies: `window.location`, `encodeURIComponent`, `window.open`. ```javascript function v(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; const s=`https://chatgpt.com/?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Open Claude AI with Context Source: https://www.nutrient.io/guides/ios/customizing-the-interface/customizing-the-annotation-table-view-controller Opens a new tab with Claude AI, pre-filled with a prompt that includes the current Nutrient IO documentation URL and a request for assistance. The prompt asks the AI to be ready to explain concepts, give examples, or help debug based on the provided documentation. ```javascript function x(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; s=`https://claude.ai/new?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Objective-C License Key Setup for PSPDFKit Source: https://www.nutrient.io/guides/ios/migration-guides/pspdfkit-3-migration-guide This Objective-C code snippet demonstrates how to set the PSPDFKit license key. It should be called in the app delegate before any PSPDFKit classes are used, as required by the new licensing model starting with PSPDFKit 3.0. ```objectivec PSPDFSetLicenseKey(@"YOUR_SERIAL_NUMBER"); ``` -------------------------------- ### SwiftUI PreviewProvider for Settings Example Source: https://www.nutrient.io/guides/ios/samples/swiftui-settings This `PreviewProvider` struct, `SwiftUISettinsExamplePreviews`, is used to generate a preview of the `SwiftUISettingsExampleView`. It loads a document using `AssetLoader` and instantiates the example view with a corresponding view model. This allows developers to visualize the UI in Xcode's canvas without running the application. ```swift struct SwiftUISettinsExamplePreviews: PreviewProvider { static var previews: some View { let document = AssetLoader.document(for: .welcome) SwiftUISettingsExampleView(store: SwiftUISettingsExampleViewModel(document: document)) } } ``` -------------------------------- ### Open Claude with Pre-filled Prompt Source: https://www.nutrient.io/guides/ios/knowledge-base/disabling-directional-lock Opens a new browser tab with Claude, pre-populated with a query about the current Nutrient IO documentation page. Similar to the ChatGPT function, it prompts Claude to help understand the documentation, provide examples, or assist with debugging, making it easy to get AI-powered help. ```javascript function x(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${\`${t}${o}\`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; s=`https://claude.ai/new?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Open Grok with Pre-filled Prompt Source: https://www.nutrient.io/guides/ios/knowledge-base/disabling-directional-lock Opens a new browser tab with Grok, pre-filled with a query about the current Nutrient IO documentation page. This function allows users to quickly engage Grok for help with understanding the documentation, seeking examples, or resolving issues, streamlining the process of getting AI assistance. ```javascript function C(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${\`${t}${o}\`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; s=`https://grok.com/c?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Search Started Source: https://www.nutrient.io/guides/ios/events-and-notifications/events This event signifies that the user started a search in the document, for example, by pressing the search icon. ```APIDOC ## Search Started ### Description This signifies that the user started a search in the document e.g. by pressing the search icon. ### Method Not applicable (Event Triggered) ### Endpoint Not applicable (Event Triggered) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Initialize Comparison Example Class (Swift) Source: https://www.nutrient.io/guides/ios/samples/pdf-document-comparison Initializes the ComparisonExample class, setting its title, description, URL, category, and priority. This class serves as a blueprint for running the document comparison example. ```swift class ComparisonExample: IndustryExample { override init() { super.init() title = "Document Comparison" contentDescription = "Shows how Nutrient can be used to compare PDF documents and highlight changes." extendedDescription = "Quickly compare, highlight, and identify PDF changes. Use manual document alignment to get a precise comparison." url = URL(string: "https://www.nutrient.io/guides/ios/compare-documents/")! category = .componentsExamples priority = 3 } override func invoke(with delegate: ExampleRunnerDelegate) -> UIViewController { ComparisonViewController(example: self) } } ``` -------------------------------- ### Open ChatGPT with Prompt (JavaScript) Source: https://www.nutrient.io/guides/ios/migration-guides/pspdfkit-11-4-migration-guide Opens a new browser tab directed to ChatGPT, pre-populated with a specific prompt. The prompt includes a reference to the current Nutrient documentation page and asks for assistance in understanding or debugging it. This leverages `encodeURIComponent` to ensure the URL is properly formatted. ```javascript function v(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`,s=`https://chatgpt.com/?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Initialize Nutrient SDK Source: https://www.nutrient.io/guides/ios/best-practices/carthage-integration This Swift code snippet shows how to initialize the Nutrient SDK. You'll typically do this early in your application's lifecycle, providing necessary configuration details like your API key. ```swift NutrientSDK.initialize(apiKey: "YOUR_API_KEY") ``` -------------------------------- ### PDFViewController Controller State (Swift) Source: https://www.nutrient.io/guides/ios/samples Explore the different states of PDFViewController with Swift examples. Visit our API guide for more resources on customizing your PDF viewer. ```swift import UIKit import PDFKit // Assuming you have an instance of PDFViewController named 'pdfViewController' // The 'state' of a PDFViewController typically refers to its configuration and current display properties. // Example: Accessing and modifying the PDF document // var currentDocument: PDFDocument? { return pdfViewController.document } // Example: Setting the currently displayed page // func goToPage(pageNumber: Int) { // if let page = pdfViewController.document?.page(at: pageNumber - 1) { // pdfViewController.go(to: page) // } // } // Example: Controlling annotation visibility // func toggleAnnotationsVisibility(visible: Bool) { // pdfViewController.displayAnnotations = visible // pdfViewController.setNeedsDisplay() // Refresh the view // } // Example: Handling user interaction modes // enum InteractionMode { // case pan, select, annotate // } // // func setInteractionMode(mode: InteractionMode) { // switch mode { // case .pan: // pdfViewController.interactionMode = .pan // case .select: // pdfViewController.interactionMode = .annotationSelection // case .annotate: // // You might need to specify the annotation type here // pdfViewController.interactionMode = .annotationCreation // } // } // Example: Responding to state changes (if the controller provides delegate methods or notifications) // You would typically implement delegate methods of the PDFViewController (if available) or observe relevant KVO keys. // For instance, if there's a delegate method like 'didChangePage': // func pdfViewController(_ controller: PDFViewController, didChangePage page: Int) { // print("User navigated to page \(page)") // } // Example: Checking if the document is editable // var isEditable: Bool { return !pdfViewController.isReadOnly } // Example: Accessing zoom level // var currentZoomLevel: CGFloat { return pdfViewController.zoomScale } // Note: The specific properties and methods available for 'PDFViewController' state management // depend on the implementation provided by the Nutrient SDK. Refer to their documentation // for the exact API details. ``` -------------------------------- ### Open Grok AI with Context Source: https://www.nutrient.io/guides/ios/customizing-the-interface/customizing-the-annotation-table-view-controller Opens a new tab with Grok AI, pre-filled with a prompt that includes the current Nutrient IO documentation URL and a request for assistance. The prompt asks the AI to be ready to explain concepts, give examples, or help debug based on the provided documentation. ```javascript function C(i){ const t="https://www.nutrient.io", o=window.location.pathname, r=`I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`; s=`https://grok.com/c?q=${encodeURIComponent(r)}`; window.open(s,"_blank") } ``` -------------------------------- ### Configure Nutrient AI Chatbot Widget Source: https://www.nutrient.io/guides/ios/pspdfkit-instant/getting-started This JavaScript function dynamically configures and injects the Nutrient AI chatbot widget into the webpage. It determines the appropriate disclaimer and example questions based on the current URL path, allowing for tailored user interactions. The widget's appearance and behavior are extensively customized through data attributes. ```javascript function u() { const a = d(), t = document.createElement("script"); t.async = !0, t.src = "https://widget.kapa.ai/kapa-widget.bundle.js", t.setAttribute("data-website-id", "ec76a086-c5ce-409a-91bb-bee358fdb208"), t.setAttribute("data-project-color", "#1A1414"), t.setAttribute("data-text-color", "#1A1414"), t.setAttribute("data-modal-override-open-id", "nutrient-sdk-docs-ai"), t.setAttribute("data-button-hide", "false"), t.setAttribute("data-modal-open-by-default", "true"), t.setAttribute("data-user-analytics-fingerprint-enabled", "true"), t.setAttribute("data-project-name", "Nutrient"), t.setAttribute("data-modal-title", "Nutrient AI"), t.setAttribute("data-modal-disclaimer", a.modalDisclaimer), t.setAttribute("data-modal-example-questions", a.exampleQuestions), t.setAttribute("data-modal-disclaimer-bg-color", "#EFEBE7"), t.setAttribute("data-modal-disclaimer-text-color", "#67594B"), t.setAttribute("data-modal-disclaimer-font-size", "14px"), t.setAttribute("data-modal-disclaimer-padding", "0.875rem"), t.setAttribute("data-query-input-font-size", "1rem"), t.setAttribute("data-query-input-text-color", "#1A1414"), t.setAttribute("data-query-input-placeholder-text-color", "#67594B"), t.setAttribute("data-query-input-border-color", "#1A1414"), t.setAttribute("data-query-input-focus-border-color", "#DE9DCC"), t.setAttribute("data-submit-query-button-bg-color", "#1A1414"), t.setAttribute("data-example-question-button-height", "40px"), t.setAttribute("data-example-question-button-padding-x", "1.5rem"), t.setAttribute("data-example-question-button-padding-y", "0.75rem"), t.setAttribute("data-example-question-button-border", "1px solid #C2B8AE !important"), t.setAttribute("data-example-question-button-border-radius", "8px"), t.setAttribute("data-example-question-button-text-color", "#1A1414"), t.setAttribute("data-example-question-button-box-shadow", "none"), t.setAttribute("data-example-question-button-font-size", "0.875rem"), t.setAttribute("data-example-question-button-hover-bg-color", "#EFEBE7"), t.setAttribute("data-modal-z-index", "999999"), t.setAttribute("data-modal-border-radius", "1.5rem"), t.setAttribute("data-modal-header-bg-color", "#DE9DCC"), t.setAttribute("data-modal-header-border-bottom", "none"), t.setAttribute("data-modal-header-padding", "1.5rem"), t.setAttribute("data-modal-title-font-weight", "400"), t.setAttribute("data-modal-title-font-size", "1.5rem"), t.setAttribute("data-modal-title-color", "#1A1414"), t.setAttribute("data-button-text", "ASK AI"), t.setAttribute("data-button-height", "5rem"), t.setAttribute("data-button-width", "5rem"), t.setAttribute("data-button-bg-color", "#1A1414"), t.setAttribute("data-button-border-radius", "1rem"), t.setAttribute("data-button-text-shadow", "none"), t.setAttribute("data-button-text-font-weight", "400"), t.setAttribute("data-button-text-font-size", "0.75rem"), t.setAttribute("data-button-image-height", "1.5rem"), t.setAttribute("data-button-image-width", "1.5rem"), t.setAttribute("data-thread-clear-button-height", "40px"), t.setAttribute("data-thread-clear-button-padding-x", "16px"), t.setAttribute("data-thread-clear-button-padding-y", "8px"), t.setAttribute("data-thread-clear-button-border", "none"), t.setAttribute("data-thread-clear-button-border-radius", "8px"), t.setAttribute("data-thread-clear-button-bg-color", "#EFEBE7"), t.setAttribute("data-thread-clear-button-hover-bg-color", "#E2DBD9"), t.setAttribute("data-thread-clear-button-text-color", "#1A1414"), t.setAttribute("data-thread-clear-button-font-size", "12px"), t.setAttribute("data-thread-clear-button-icon-size", "24px"), document.body.appendChild(t) } ``` -------------------------------- ### VWO Initialization and Script Loading (JavaScript) Source: https://www.nutrient.io/guides/ios/migration-guides/pspdfkit-13-migration-guide This snippet initializes the Visual Website Optimizer (VWO). It retrieves settings, constructs a VWO API URL, and either loads the script via a GET request or adds it as a script tag based on the URL parameters. Initialization is deferred to improve page load performance. ```javascript var o=window._vis_opt_url||d.URL, s='https://dev.visualwebsiteoptimizer.com/j.php?a='+account_id+'&u='+encodeURIComponent(o)+'&vn='+version; if(w.location.search.indexOf('_vwo_xhr')!==-1){ this.addScript({src:s}) }else{ this.load(s+'&x=true') } ``` -------------------------------- ### Create Fixed-Size Stamp Annotations in iOS Source: https://www.nutrient.io/guides/ios/samples Learn to create a fixed-size stamp annotation for iOS that remains unchanged during zoom. Access a complete guide for more resources and examples. ```swift /* Note: The actual code for creating fixed-size stamp annotations is not provided in the text. This is a placeholder to indicate where such a snippet would go. Example: // Custom annotation subclass that enforces fixed size during rendering. // This might involve overriding the `draw(in: context:)` method and ignoring zoom level. */ ``` -------------------------------- ### Setup AI Assistant View Controller - Swift Source: https://www.nutrient.io/guides/ios/ai/multiple-document-support-uikit This Swift function sets up an AIAssistantViewController by creating the necessary configuration and session with the provided documents. It configures the view controller and sets its delegate. ```swift func setupAIAssistant(with documents: [Document]) -> AIAssistantViewController { let configuration = createAIAssistantConfiguration(for: documents) let session = AIAssistantSession(documents: documents, configuration: configuration) let aiAssistantViewController = AIAssistantViewController(session: session) aiAssistantViewController.delegate = self return aiAssistantViewController } ``` -------------------------------- ### Customize PDF Form Appearance in Swift Source: https://www.nutrient.io/guides/ios/samples Customize the appearance of PDF forms in iOS using Swift. This guide provides examples for supported PDF form fields. ```swift let formField = PSPDFTextField() formField.borderColor = .blue ``` -------------------------------- ### Enable Auto-Save with PDF Checkpointing (Swift) Source: https://www.nutrient.io/guides/ios/samples Discover how to auto-save documents using the checkpointing API. This iOS guide offers additional resources and Swift code examples. ```swift import UIKit import PDFKit // Assuming you have a PDFView instance named 'pdfView' let pdfView: PDFView = // ... your PDFView instance // To enable auto-saving with checkpointing, you typically need to configure: // 1. A mechanism to periodically save the PDF document's state. // 2. A way to restore the document from the last saved state. // The exact implementation depends on how you manage your PDF documents and their state. // Here's a conceptual outline using a timer for periodic saving: var saveTimer: Timer? = nil let saveInterval: TimeInterval = 60.0 // Save every 60 seconds func startAutoSaveTimer() { saveTimer = Timer.scheduledTimer(withTimeInterval: saveInterval, repeats: true) { [weak self] timer in self?.saveCurrentDocumentState() // Call your saving function } } func stopAutoSaveTimer() { saveTimer?.invalidate() saveTimer = nil } func saveCurrentDocumentState() { // Implement your logic to save the current state of the PDF document. // This might involve: // - Getting the PDF document data: pdfView.document?.dataRepresentation() // - Saving this data to a file or persistent storage. // - Storing metadata about the save point (e.g., timestamp, current page). print("Saving document state...") // Example: Save to a temporary file if let pdfData = pdfView.document?.dataRepresentation() { let temporaryDirectoryURL = FileManager.default.temporaryDirectory let saveURL = temporaryDirectoryURL.appendingPathComponent("autosaved_document.pdf") do { try pdfData.write(to: saveURL) print("Document state saved to \(saveURL.path)") } catch { print("Error saving document state: \(error)") } } } func loadLastDocumentState() -> PDFDocument? { // Implement logic to load the last saved document state from persistent storage. // This would be called when your application or view controller launches. print("Attempting to load last document state...") let temporaryDirectoryURL = FileManager.default.temporaryDirectory let saveURL = temporaryDirectoryURL.appendingPathComponent("autosaved_document.pdf") if FileManager.default.fileExists(atPath: saveURL.path) { do { let pdfData = try Data(contentsOf: saveURL) return PDFDocument(data: pdfData) } catch { print("Error loading document state: \(error)") return nil } } else { print("No autosaved document found.") return nil } } // Call startAutoSaveTimer() when your PDF view controller becomes active // Call stopAutoSaveTimer() when it's deallocated or no longer needed // Call loadLastDocumentState() to restore the document on app launch or view load ``` -------------------------------- ### Initialize Visual Website Optimizer (VWO) Tool Source: https://www.nutrient.io/guides/ios/best-practices/carthage-integration This JavaScript snippet initializes the Visual Website Optimizer (VWO) tool. It defines account ID, version, and settings tolerance. It attempts to retrieve existing settings from local storage. The `code` object provides methods to access configuration, manage scripts, and handle the VWO loading process. It includes logic to prevent the flash of unstyled content by not hiding the body. Dependencies include `window` and `document` objects, and potentially browser's `localStorage`. Inputs are account ID and version. Outputs include the setup of VWO configurations and potentially loading of VWO scripts. ```javascript window._vwo_code || (function() { var account_id=892495, version=2.1, settings_tolerance=2000, hide_element='', // Don't hide body to prevent flash hide_element_style = '', /* DO NOT EDIT BELOW THIS LINE */ f=false, w=window, d=document, v=d.querySelector('#vwoCode'), cK='_vwo_'+account_id+'_settings', cc={}; try{ var c=JSON.parse(localStorage.getItem('_vwo_'+account_id+'_config')); cc=c&&typeof c==='object'?c:{} }catch(e){} var stT=cc.stT==='session'?w.sessionStorage:w.localStorage; code={ nonce:v&&v.nonce, library_tolerance:function(){ return typeof library_tolerance!=='undefined'?library_tolerance:undefined }, settings_tolerance:function(){ return cc.sT||settings_tolerance }, hide_element_style:function(){ return'{'+(cc.hES||hide_element_style)+'}' }, hide_element:function(){ // Always return empty to prevent hiding return ''; }, getVersion:function(){ return version }, finish:function(e){ if(!f){ f=true; var t=d.getElementById('_vis_opt_path_hides'); if(t)t.parentNode.removeChild(t); if(e)(new Image).src='https://dev.visualwebsiteoptimizer.com/ee.gif?a='+account_id+e } }, finished:function(){ return f }, addScript:function(e){ var t=d.createElement('script'); t.type='text/javascript'; if(e.src){ t.src=e.src; t.async=true; // Make async }else{ t.text=e.text } v&&t.setAttribute('nonce',v.nonce); d.getElementsByTagName('head')[0].appendChild(t) }, load:function(e,t){ var n=this.getSettings(),i=d.createElement('script'),r=this; t=t||{}; if(n){ i.textContent=n; d.getElementsByTagName('head')[0].appendChild(i); if(!w.VWO||VWO.caE){ stT.removeI ``` -------------------------------- ### VWO Initialization and Script Loading (JavaScript) Source: https://www.nutrient.io/guides/ios/security/signed-disk-image This snippet demonstrates the core VWO initialization logic. It includes functions for loading settings from local storage, fetching the VWO JavaScript file dynamically using `XMLHttpRequest` or by directly creating a script tag, and handling asynchronous loading with callbacks for success and error events. Initialization is deferred to ensure non-blocking rendering. ```javascript var code = { settings_tolerance: function() { var e = window._vis_opt_settings_timer || 1500; return e; }, load: function(e, t) { if (window._vwo_xhr && t) { var r = new XMLHttpRequest(); r.open('GET', e, true); r.withCredentials = !t.dSC; r.responseType = t.responseType || 'text'; r.onload = function() { if (t.onloadCb) { return t.onloadCb(r, e); } if (r.status === 200 || r.status === 304) { _vwo_code.addScript({ text: r.responseText }); } else { _vwo_code.finish('&e=loading_failure:' + e); } }; r.onerror = function() { if (t.onerrorCb) { return t.onerrorCb(e); } _vwo_code.finish('&e=loading_failure:' + e); }; r.send(); } else { var o = new XMLHttpRequest(); o.open('GET', e, true); o.withCredentials = !t.dSC; o.responseType = t.responseType || 'text'; o.onload = function() { if (t.onloadCb) { return t.onloadCb(o, e); } if (o.status === 200 || o.status === 304) { _vwo_code.addScript({ text: o.responseText }); } else { _vwo_code.finish('&e=loading_failure:' + e); } }; o.onerror = function() { if (t.onerrorCb) { return t.onerrorCb(e); } _vwo_code.finish('&e=loading_failure:' + e); }; o.send(); } }, getSettings: function() { try { var e = stT.getItem(cK); if (!e) { return; } e = JSON.parse(e); if (Date.now() > e.e) { stT.removeItem(cK); return; } return e.s; } catch (e) { return; } }, init: function() { if (d.URL.indexOf('__vwo_disable__') > -1) return; var e = this.settings_tolerance(); w._vwo_settings_timer = setTimeout(function() { _vwo_code.finish(); stT.removeItem(cK); }, e); var o = window._vis_opt_url || d.URL, s = 'https://dev.visualwebsiteoptimizer.com/j.php?a=' + account_id + '&u=' + encodeURIComponent(o) + '&vn=' + version; if (w.location.search.indexOf('_vwo_xhr') !== -1) { this.addScript({ src: s }); } else { this.load(s + '&x=true'); } } }; w._vwo_code = code; if (d.readyState === 'loading') { d.addEventListener('DOMContentLoaded', function() { code.init(); }); } else { if ('requestIdleCallback' in w) { requestIdleCallback(function() { code.init(); }, { timeout: 1000 }); } else { setTimeout(function() { code.init(); }, 0); } } ``` ``` -------------------------------- ### PDF Library Integration for visionOS Source: https://context7_llms Guides and code examples for integrating the PDF library for visionOS using the Nutrient SDK. Enables document functionality on visionOS devices. ```swift // Example Swift code for integrating PDF library on visionOS // Requires Nutrient SDK for visionOS import NutrientSDKVisionOS // Initialize the PDF library NutrientPDF.initialize(apiKey: "YOUR_API_KEY") // Present a PDF viewer let pdfViewer = NutrientPDF.viewerController() // Present pdfViewer in your visionOS app ``` -------------------------------- ### Get PSPDFKit Version (Swift) Source: https://www.nutrient.io/guides/ios/license-issues/getting-the-currently-used-version Retrieves the version string of the PSPDFKit SDK in Swift. This is a direct property access to get the SDK's version information. ```swift let pspdfVersionString = PSPDFKit.SDK.versionString ``` -------------------------------- ### Customize PDF View Margins in iOS Source: https://www.nutrient.io/guides/ios/samples Learn how to adjust document view margins in iOS to fit your custom UI. This guide offers resources and examples for PDF customization. ```swift /* Note: The actual code for customizing PDF view margins is not provided in the text. This is a placeholder to indicate where such a snippet would go. Example: // Assuming pdfView is an instance of PSPDFView: // pdfView.contentInsets = UIEdgeInsets(top: 20, left: 10, bottom: 20, right: 10) */ ```