Display and manipulate PDF documents in your applications using PDFKit.

Posts under PDFKit tag

27 Posts

Post

Replies

Boosts

Views

Activity

PDFKit PdfView Black Boxes sometimes
Hi! I'm using PDFKits PdfView to display a PDF file and after several page changes, the background turns black, suddenly (like a big black rectangle). The error occurs in the Books App on the iPad as well and looks similiar to this issue: https://discussions.apple.com/thread/8627073?sortBy=rank Anyone got a solution for this?
1
0
147
5d
How do I flatten a PDF using Shortcuts or Automator?
Looking for any method to quickly flatten a PDF without opening Preview and without installing 3 party software. Any ideas? Save as PDF in Preview works, but I don't want to have to open Preview each time I need to do this. The Create PDF action which appears in Finder when you select 2 or more PDFs flattens PDFs, but it requires me to select 2 or more files, and I generally don't want to combine PDFs--I simply wish to flatten a PDF. Most Automator and Shortcuts options I am aware of do not flatten PDFs, and in some cases, strip out form field data from PDFs.
6
0
120
1w
Copy file in application document file to user Documents file
I ave an application that makes use of charts. I would like to have a button for the user to save the chart as a PDF. I tried to have the button save the PDF to the user's document directory directly. That attempt failed. But I was able to save the PDF to the application sandboxed documents directory. The question is how to programmatically move that file from the application documents folder to the user's general documents folder. So far I have not been able to find a method that will move the PDF file. Any ideas?
2
0
285
2w
Unexpected lines appear in PDFView on visionOS 26 beta
I’m attempting to display a PDF file in a visionOS application using the PDFView in PDFKit. When running on device with visionOS 26, a horizontal solid line appears on some pages, while on other pages, both a horizontal and vertical solid line appear. These lines do not appear in Xcode preview canvas (macOS, visionOS) on device running visionOS 2.5 on Mac running macOS 15.6 I thought that this could possibly be the page breaks, but setting displaysPageBreaks = false did not appear to be effective. Are there any other settings that could be causing the lines to display? Code Example struct ContentView: View { @State var pdf: PDFDocument? = nil var body: some View { PDFViewWrapper(pdf: pdf) .padding() } } #Preview(windowStyle: .automatic) { ContentView(pdf: PDFDocument(url: Bundle.main.url(forResource: "SampleApple", withExtension: "pdf")!)) .environment(AppModel()) } struct PDFViewWrapper: UIViewRepresentable { let pdf: PDFDocument? func makeUIView(context: Context) -> PDFView { let view = PDFView() view.document = pdf view.displaysPageBreaks = false return view } func updateUIView(_ uiView: PDFView, context: Context) { uiView.document = pdf } } Tested with Xcode Version 16.4 (16F6) Xcode Version 26.0 beta 5 (17A5295f) visionOS 2.5 visionOS 26 Beta 5 I
2
0
68
Aug ’25
The PKCanvasView Created by PDFPageOverlayViewProvider cannot work normally
By setting the PKCanvasView background color to blue, I can tell that the PKCanvasView for each PDFPage is created normally, but it does not respond to touch. Specifically, whether it is finger or applepencil, all the responses of the page occur from PDFView(such as zoom and scroll), and PKCanvasView can not draw, please how to solve? class PDFAnnotatableViewController: UIViewController, PDFViewDelegate { private let pdfView = PDFView() private var pdfDocument: PDFDocument? let file: FileItem private var userSettings: UserSettings @Binding var selectedPage: Int @Binding var currentMode: Mode @Binding var latestPdfChatResponse: LatestPDFChatResponse @State private var pdfPageCoordinator = PDFPageCoordinator() @ObservedObject var userMessage: ChatMessage init(file: FileItem, userSettings: UserSettings, drawDataList: Binding<[DrawDataItem]>, selectedPage: Binding<Int>, currentMode: Binding<Mode>, latestPdfChatResponse: Binding<LatestPDFChatResponse>, userMessage: ChatMessage) { self.file = file self.userSettings = userSettings self._selectedPage = selectedPage self._currentMode = currentMode self._latestPdfChatResponse = latestPdfChatResponse self.userMessage = userMessage super.init(nibName: nil, bundle: nil) DispatchQueue.global(qos: .userInitiated).async { if let document = PDFDocument(url: file.pdfLocalUrl) { DispatchQueue.main.async { self.pdfDocument = document self.pdfView.document = document self.goToPage(selectedPage: selectedPage.wrappedValue - 1) } } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupPDFView() } private func setupPDFView() { pdfView.delegate = self pdfView.autoScales = true pdfView.displayMode = .singlePage pdfView.displayDirection = .vertical pdfView.backgroundColor = .white pdfView.usePageViewController(true) pdfView.displaysPageBreaks = false pdfView.displaysAsBook = false pdfView.minScaleFactor = 0.8 pdfView.maxScaleFactor = 3.5 pdfView.pageOverlayViewProvider = pdfPageCoordinator if let document = pdfDocument { pdfView.document = document goToPage(selectedPage: selectedPage) } pdfView.frame = view.bounds pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(pdfView) NotificationCenter.default.addObserver( self, selector: #selector(handlePageChange), name: .PDFViewPageChanged, object: pdfView ) } // Dealing with page turning @objc private func handlePageChange(notification: Notification) { guard let currentPage = pdfView.currentPage, let document = pdfView.document else { return } let currentPageIndex = document.index(for: currentPage) if currentPageIndex != selectedPage - 1 { DispatchQueue.main.async { self.selectedPage = currentPageIndex + 1 } } } func goToPage(selectedPage: Int) { guard let document = pdfView.document else { return } if let page = document.page(at: selectedPage) { pdfView.go(to: page) } } // Switch function func togglecurrentMode(currentMode: Mode){ DispatchQueue.main.async { if self.currentMode == .none{ self.pdfView.usePageViewController(true) self.pdfView.isUserInteractionEnabled = true } else if self.currentMode == .annotation { if let page = self.pdfView.currentPage { if let canvasView = self.pdfPageCoordinator.getCanvasView(forPage: page) { canvasView.isUserInteractionEnabled = true canvasView.tool = PKInkingTool(.pen, color: .red, width: 20) canvasView.drawingPolicy = .anyInput canvasView.setNeedsDisplay() } } } } } } class MyPDFPage: PDFPage { var drawing: PKDrawing? func setDrawing(_ drawing: PKDrawing) { self.drawing = drawing } func getDrawing() -> PKDrawing? { return self.drawing } } class PDFPageCoordinator: NSObject, PDFPageOverlayViewProvider { var pageToViewMapping = [PDFPage: PKCanvasView]() func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? { var resultView: PKCanvasView? = nil if let overlayView = pageToViewMapping[page] { resultView = overlayView } else { let canvasView = PKCanvasView(frame: view.bounds) canvasView.drawingPolicy = .anyInput canvasView.tool = PKInkingTool(.pen, color: .systemYellow, width: 20) canvasView.backgroundColor = .blue pageToViewMapping[page] = canvasView resultView = canvasView } if let page = page as? MyPDFPage, let drawing = page.drawing { resultView?.drawing = drawing } return resultView } func pdfView(_ pdfView: PDFView, willEndDisplayingOverlayView overlayView: UIView, for page: PDFPage) { guard let overlayView = overlayView as? PKCanvasView, let page = page as? MyPDFPage else { return } page.drawing = overlayView.drawing pageToViewMapping.removeValue(forKey: page) } func savePDFDocument(_ pdfDocument: PDFDocument) -> Data { for i in 0..<pdfDocument.pageCount { if let page = pdfDocument.page(at: i) as? MyPDFPage, let drawing = page.drawing { let newAnnotation = PDFAnnotation(bounds: drawing.bounds, forType: .stamp, withProperties: nil) let codedData = try! NSKeyedArchiver.archivedData(withRootObject: drawing, requiringSecureCoding: true) newAnnotation.setValue(codedData, forAnnotationKey: PDFAnnotationKey(rawValue: "drawingData")) page.addAnnotation(newAnnotation) } } let options = [PDFDocumentWriteOption.burnInAnnotationsOption: true] if let resultData = pdfDocument.dataRepresentation(options: options) { return resultData } return Data() } func getCanvasView(forPage page: PDFPage) -> PKCanvasView? { return pageToViewMapping[page] } } Is there an error in my code? Please tell me how to make PKCanvasView painting normally?
1
0
378
Aug ’25
How to fix the gestureRecognizer over PDFKit breaking the paging in the new ios26 version?
I had project going great, where i needed to do stuff with pdfs, drawing on top them etc. Since apple is all closed sourced i needed to become a bit hacky. Anyways, i have a problem since the new ios 26 update which breaks the behaviour. I simplified the code very much into a demo project, where you can quickly see what's wrong. When swiping left to go to the next page, it does change the page etc in the pdf Document, but visually nothing happens. I am stuck on the first page. I dont know what to do, tried a lot of things, but nothing works. Anyone skilled enough to help me out? import UIKit import PDFKit import SwiftUI class PDFViewController: UIViewController { var pdfView: PDFView! var gestureHandler: GestureHandler! override func viewDidLoad() { super.viewDidLoad() setupPDFView() setupGestureHandler() loadPDF() } private func setupPDFView() { pdfView = PDFView(frame: view.bounds) // Your exact configuration pdfView.autoScales = true pdfView.pageShadowsEnabled = false pdfView.backgroundColor = .white pdfView.displayMode = .singlePage view.addSubview(pdfView) // Setup constraints pdfView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ pdfView.topAnchor.constraint(equalTo: view.topAnchor), pdfView.leadingAnchor.constraint(equalTo: view.leadingAnchor), pdfView.trailingAnchor.constraint(equalTo: view.trailingAnchor), pdfView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } private func setupGestureHandler() { gestureHandler = GestureHandler(pdfView: pdfView) gestureHandler.setupSwipeGestures(on: view) } private func loadPDF() { if let path = Bundle.main.path(forResource: "sonate12", ofType: "pdf"), let document = PDFDocument(url: URL(fileURLWithPath: path)) { pdfView.document = document } else { print("Could not find sonate12.pdf in bundle") } } } class GestureHandler { private weak var pdfView: PDFView? init(pdfView: PDFView) { self.pdfView = pdfView } func setupSwipeGestures(on view: UIView) { // Left swipe - go to next page let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:))) leftSwipe.direction = .left view.addGestureRecognizer(leftSwipe) // Right swipe - go to previous page let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:))) rightSwipe.direction = .right view.addGestureRecognizer(rightSwipe) } @objc private func handleSwipe(_ gesture: UISwipeGestureRecognizer) { guard let pdfView = pdfView, let document = pdfView.document, let currentPage = pdfView.currentPage else { print("🚫 No PDF view, document, or current page available") return } let currentIndex = document.index(for: currentPage) let totalPages = document.pageCount print("📄 Current state: Page \(currentIndex + 1) of \(totalPages)") print("👆 Swipe direction: \(gesture.direction == .left ? "LEFT (next)" : "RIGHT (previous)")") switch gesture.direction { case .left: // Next page guard currentIndex < document.pageCount - 1 else { print("🚫 Already on last page (\(currentIndex + 1)), cannot go forward") return } let nextPage = document.page(at: currentIndex + 1) if let page = nextPage { print("➡️ Going to page \(currentIndex + 2)") pdfView.go(to: page) pdfView.setNeedsDisplay() pdfView.layoutIfNeeded() // Check if navigation actually worked DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { if let newCurrentPage = pdfView.currentPage { let newIndex = document.index(for: newCurrentPage) print("✅ Navigation result: Now on page \(newIndex + 1)") if newIndex == currentIndex { print("⚠️ WARNING: Page didn't change visually!") } } } } else { print("🚫 Could not get next page object") } case .right: // Previous page guard currentIndex > 0 else { print("🚫 Already on first page (1), cannot go back") return } let previousPage = document.page(at: currentIndex - 1) if let page = previousPage { print("⬅️ Going to page \(currentIndex)") pdfView.go(to: page) pdfView.setNeedsDisplay() pdfView.layoutIfNeeded() let bounds = pdfView.bounds pdfView.bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width + 0.01, height: bounds.height) pdfView.bounds = bounds // Check if navigation actually worked DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { if let newCurrentPage = pdfView.currentPage { let newIndex = document.index(for: newCurrentPage) print("✅ Navigation result: Now on page \(newIndex + 1)") if newIndex == currentIndex { print("⚠️ WARNING: Page didn't change visually!") } } } } else { print("🚫 Could not get previous page object") } default: print("🤷‍♂️ Unknown swipe direction") break } } } struct PDFViewerRepresentable: UIViewControllerRepresentable { func makeUIViewController(context: Context) -> PDFViewController { return PDFViewController() } func updateUIViewController(_ uiViewController: PDFViewController, context: Context) { // No updates needed } } You can look at the code here as well: https://github.com/vallezw/swift-bug-ios26
0
1
131
Aug ’25
PDFKit findString selection extend not working
With PDFKit in SwiftUI, I'm using the findString function to search the text of a PDF. That part works correctly, but when I use the extend function to get some of the text on both sides of the found word (ie, its context in the page), it doesn't extend. Am I doing this wrong? There is very little documentation or examples about the extend function; even the Apple page doesn't specify what the units refer to in the extend call (presumably it means characters, but I suppose it could also be pixels, or some other measurement specific to PDFs). Here is the code, and pictures of the app, the output (showing that the code can read all the text on the page), and the Acrobat Reader effect I'm trying to achieve. If the extend function truly is broken, and not just a problem in how I'm going about this, a workaround would be to use the text from the entire page, and extract the surrounding words from there, but that does get complicated, especially if there are multiple instances of the word on the page, or if the result straddles 2 pages. import PDFKit import SwiftUI struct ContentView: View { @StateObject var controller = PDFViewController() @State var searchResults:[PDFSelection] = [] var body: some View { VStack { Button { searchResults = controller.pdfView!.document!.findString("is", withOptions: [.caseInsensitive]) let fullPageText = controller.pdfView!.document!.string print(fullPageText) for result in searchResults { let beforeExtending = result.string ?? "" print("Before: \(beforeExtending)") result.extend(atEnd: 3) result.extend(atStart: 3) let afterExtending = result.string ?? "" print("After: \(afterExtending)") } } label: { Text("Do search") } PDFKitView(url: generateURL(), controller: controller) } .padding() } func generateURL() -> URL { let bundlePathRootAsString = Bundle.main.resourcePath! var pdfPathInBundle = URL(fileURLWithPath: bundlePathRootAsString) pdfPathInBundle.append(path: "TestPDF.pdf") return pdfPathInBundle } } struct PDFKitView: UIViewRepresentable { func updateUIView(_ uiView: PDFView, context: Context) { } let url: URL @ObservedObject var controller: PDFViewController func makeUIView(context: Context) -> PDFView { let pdfView = PDFView() pdfView.document = PDFDocument(url: self.url) pdfView.autoScales = true controller.pdfView = pdfView return pdfView } } class PDFViewController: ObservableObject { var pdfView: PDFView? }
2
0
124
Jul ’25
Does the canvas view on top of the PDFView not re-render?
I added a canvas view using PDFPageOverlayViewProvider. When I zoom the PDFView, the drawing is scaled, but its quality becomes blurry. How can I fix this? import SwiftUI import PDFKit import PencilKit import CoreGraphics struct ContentView: View { var body: some View { if let url = Bundle.main.url(forResource: "sample", withExtension: "pdf"), let data = try? Data(contentsOf: url), let document = PDFDocument(data: data) { PDFRepresentableView(document: document) } else { Text("fail") } } } #Preview { ContentView() } struct PDFRepresentableView: UIViewRepresentable { let document: PDFDocument let pdfView = PDFView() func makeUIView(context: Context) -> PDFView { pdfView.displayMode = .singlePageContinuous pdfView.usePageViewController(false) pdfView.displayDirection = .vertical pdfView.pageOverlayViewProvider = context.coordinator pdfView.document = document pdfView.autoScales = false pdfView.minScaleFactor = 0.7 pdfView.maxScaleFactor = 4 return pdfView } func updateUIView(_ uiView: PDFView, context: Context) { // Optional: update logic if needed } func makeCoordinator() -> CustomCoordinator { return CustomCoordinator(parent: self) } } class CustomCoordinator: NSObject, PDFPageOverlayViewProvider, PKCanvasViewDelegate { let parent: PDFRepresentableView init(parent: PDFRepresentableView) { self.parent = parent } func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? { let result = UIView() let canvasView = PKCanvasView() canvasView.drawingPolicy = .anyInput canvasView.tool = PKInkingTool(.pen, color: .blue, width: 20) canvasView.translatesAutoresizingMaskIntoConstraints = false result.addSubview(canvasView) NSLayoutConstraint.activate([ canvasView.leadingAnchor.constraint(equalTo: result.leadingAnchor), canvasView.trailingAnchor.constraint(equalTo: result.trailingAnchor), canvasView.topAnchor.constraint(equalTo: result.topAnchor), canvasView.bottomAnchor.constraint(equalTo: result.bottomAnchor) ]) for subView in view.documentView?.subviews ?? [] { subView.isUserInteractionEnabled = true } result.layoutIfNeeded() return result } }
1
0
177
Jul ’25
CanvasView overlay on PDFKit loses quality when zoomed – how to preserve drawing resolution?
Hi all, I’m currently building a SwiftUI app that overlays a PKCanvasView onto each page of a PDFView using PDFPageOverlayViewProvider. It works well at the initial scale, but once I zoom into the PDF, the drawings on the PKCanvasView appear blurry or pixelated, even though the PDF itself remains crisp. I’m trying to adjust canvasView.contentScaleFactor relative to pdfView.scaleFactor to preserve the drawing quality. Here’s a simplified version of the relevant code: import SwiftUI import PDFKit import PencilKit struct ContentView: View { var body: some View { if let url = Bundle.main.url(forResource: "sample", withExtension: "pdf"), let data = try? Data(contentsOf: url), let document = PDFDocument(data: data) { PDFRepresentableView(document: document) } else { Text("") } } } #Preview { ContentView() } struct PDFRepresentableView: UIViewRepresentable { let document: PDFDocument let pdfView = PDFView() func makeUIView(context: Context) -> PDFView { pdfView.displayMode = .singlePageContinuous pdfView.usePageViewController(false) pdfView.displayDirection = .vertical pdfView.pageOverlayViewProvider = context.coordinator pdfView.document = document pdfView.autoScales = false pdfView.minScaleFactor = 0.7 pdfView.maxScaleFactor = 4 NotificationCenter.default.addObserver( context.coordinator, selector: #selector(context.coordinator.onPageZoomAndPan), name: .PDFViewScaleChanged, object: pdfView ) return pdfView } func updateUIView(_ uiView: PDFView, context: Context) { // Optional: update logic if needed } func makeCoordinator() -> CustomCoordinator { return CustomCoordinator(parent: self) } } class CustomCoordinator: NSObject, PDFPageOverlayViewProvider, PKCanvasViewDelegate { let parent: PDFRepresentableView init(parent: PDFRepresentableView) { self.parent = parent } func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? { let canvasView = PKCanvasView() let rect = page.bounds(for: .mediaBox) canvasView.drawingPolicy = .anyInput canvasView.tool = PKInkingTool(.pen, color: .black, width: 10) canvasView.translatesAutoresizingMaskIntoConstraints = true canvasView.backgroundColor = .red.withAlphaComponent(0.1) canvasView.frame = rect canvasView.isScrollEnabled = false for subView in view.documentView?.subviews ?? [] { subView.isUserInteractionEnabled = true } return canvasView } @objc func onPageZoomAndPan() { parent.pdfView.documentView?.subviews.forEach { subview in if subview.theClassName == "PDFPageView", let pageViewPrivate = subview.value(forKey: "_private") as? NSObject, let page = pageViewPrivate.value(forKey: "page") as? PDFPage { subview.subviews.forEach { subview in if let canvasView = subview as? PKCanvasView { let zoomScale = parent.pdfView.scaleFactor canvasView.contentScaleFactor = UIScreen.main.scale * zoomScale canvasView.drawing = canvasView.drawing canvasView.setNeedsDisplay() canvasView.layoutIfNeeded() } } } } print("Zoom changed. Current scale: \(parent.pdfView.scaleFactor)") } } extension NSObject { var theClassName: String { return NSStringFromClass(type(of: self)) } } But this doesn’t seem to improve the rendered quality. The lines still appear blurry when zoomed in. What I’ve tried: • Adjusting contentScaleFactor and forcing redraw • Reassigning canvasView.drawing • Calling setNeedsDisplay() and layoutIfNeeded() None of these approaches seem to re-render the canvas at a higher resolution or match the zoomed scale of the PDF. My questions: 1. Is there a correct way to scale PKCanvasView content to match PDF zoom levels? 2. Should I recreate the canvas or drawing when zoom changes? 3. Is PKCanvasView just not intended to handle high zoom fidelity? If anyone has successfully overlaid high-resolution canvas drawing on a zoomable PDFView, I’d love to hear how you managed it. Thanks in advance!
0
0
101
Jul ’25
Files App Share Context with Security scoped resource fails
I'm creating an App that can accepted PDFs from a shared context. I am using iOS, Swift, and UIKit with IOS 17.1+ The logic is: get the context see who is sending in (this is always unknown) see if I can open in place (in case I want to save later) send the URL off to open the (PDF) document and load it into PDFKit's pdfView.document I have no trouble loading PDF docs with the file picker. And everything works as expected for shares from apps like Messages, email, etc... (in which case URLContexts.first.options.openInPlace == False) The problem is with opening (sharing) a PDF that is sent from the Files App. (openInPlace == True) If the PDF is in the App's Document Folder, I need the Security scoped resource, to access the URL from the File's App so that I can copy the PDF's data to the PDFViewer.document. I get Security scoped resource access granted each time I get the File App's context URL. But, when I call fileCoordinator.coordinate and try to access a file outside of the App's document folder using the newUrl, I get an error. FYI - The newUrl (byAccessor) and context url (readingItemAt) paths are always same for the Files App URL share context. I can, however, copy the file to a new location in my apps directory and then open it from there and load in the data. But I really do not want to do that. . . . . . Questions: Am I missing something in my pList or are there other parameters specific to sharing a file from the Files App? I'd appreciate if someone shed some light on this? . . . . . Here are the parts of my code related to this with some print statements... . . . . . SceneDelegate func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { // nothing to see here, move along guard let urlContext = URLContexts.first else { print("No URLContext found") return } // let's get the URL (it will be a PDF) let url = urlContext.url let openInPlace = urlContext.options.openInPlace let bundleID = urlContext.options.sourceApplication print("Triggered with URL: \(url)") print("Can Open In Place?: \(openInPlace)") print("For Bundle ID: \(bundleID ?? "None")") // get my Root ViewController from window if let rootViewController = self.window?.rootViewController { // currently using just the view if let targetViewController = rootViewController as? ViewController { targetViewController.prepareToLoadSharedPDFDocument(at: url) } // I might use a UINavigationController in the future else if let navigationController = rootViewController as? UINavigationController, let targetViewController = navigationController.viewControllers.first as? ViewController { targetViewController.prepareToLoadSharedPDFDocument(at: url) } } } . . . . ViewController function I broke out the if statement for accessingScope just to make it easier for me the debug and play around with the code in accessingScope == True func loadPDF(fromUrl url: URL) { // If using the File Picker / don't use this // If going through a Share.... we pass the URL and have three outcomes (1, 2a, 2b) // 1. Security scoped resource access NOT needed if from a Share Like Messages or EMail // 2. Security scoped resource access granted/needed from 'Files' App // a. success if in the App's doc directory // b. fail if NOT in the App's doc directory // Set the securty scope variable var accessingScope = false // Log the URLs for debugging print("URL String: \(url.absoluteString)") print("URL Path: \(url.path())") // Check if the URL requires security scoped resource access if url.startAccessingSecurityScopedResource() { accessingScope = true print("Security scoped resource access granted.") } else { print("Security scoped resource access denied or not needed.") } // Stop accessing the scope once everything is compeleted defer { if accessingScope { url.stopAccessingSecurityScopedResource() print("Security scoped resource access stopped.") } } // Make sure the file is still there (it should be in this case) guard FileManager.default.fileExists(atPath: url.path) else { print("File does not exist at URL: \(url)") return } // Let's see if we can open it in place if accessingScope { let fileCoordinator = NSFileCoordinator() var error: NSError? fileCoordinator.coordinate(readingItemAt: url, options: [], error: &error) { (newUrl) in DispatchQueue.main.async { print(url.path()) print(newUrl.path()) if let document = PDFDocument(url: newUrl) { self.pdfView.document = document self.documentFileName = newUrl.deletingPathExtension().lastPathComponent self.fileLoadLocation = newUrl.path() self.updateGUI(pdfLoaded: true) self.setPDFScale(to: self.VM.pdfPageScale, asNewPDF: true) } else { print("Could not load PDF directly from url: \(newUrl)") } } } if let error = error { PRINT("File coordination error: \(error)") } } else { DispatchQueue.main.async { if let document = PDFDocument(url: url) { self.pdfView.document = document self.documentFileName = url.deletingPathExtension().lastPathComponent self.fileLoadLocation = url.path() self.updateGUI(pdfLoaded: true) self.setPDFScale(to: self.VM.pdfPageScale, asNewPDF: true) } else { PRINT("Could not load PDF from url: \(url)") } } } } . . . . Other relevant pList settings I've added are: Supports opening documents in place - YES Document types - PDFs (com.adobe.pdf) UIDocumentBrowserRecentDocumentContentTypes - com.adobe.pdf Application supports iTunes file sharing - YES And iCloud is one for Entitlements with iCloud Container Identifiers Ubiquity Container Identifiers . . . . Thank you in advance!. B
2
1
689
Jul ’25
PDF in WebView
Dear all, Is it possible to replace the default PDF background colour the 50% grey to any other colour while using the new WebView? Using the standard .background method on WebView does not appear to have any effect: WebView(pdfWebpage) .background(Color.blue) // no effect on the background of the PDF Thanks!
1
0
75
Jun ’25
PDFKit PDFPage.characterBounds(at:) returns incorrect coordinates iOS 18 beta 4
PDFKit PDFPage.characterBounds(at: Int) is returning incorrect coordinates with iOS 18 beta 4 and later / Xcode 16 beta 4. It worked fine in iOS 17 and earlier (after showing the same issue during the early iOS 17 beta cycle) It breaks critical functionality that my app relies on. I have filed feedback (FB14843671). So far no changes in the latest betas. iOS release date is approaching fast! Anybody having the same issue? Any workaround available?
17
3
1.8k
May ’25
Come forzare la visualizzazione di un font diverso (es. Helvetica su iOS, Arial su Windows) in un PDF non incorporando i caratteri
Sto cercando di creare un PDF che, a seconda del sistema operativo, utilizzi un font diverso. Visto che mi è capitato di scaricare da Internet un PDF che veniva visualizzato con con Arial su Windows e con Helvetica su iOS/macOS (anche su siti di drive, OneDrive ) vorrei creare un PDF che venga visualizzato con Arial su Windows e con Helvetica su iOS/macOS, sfruttando i meccanismi di fallback dei font di sistema (senza incorporare i font nel PDF). Ho provato a: • Scrivere il documento in Arial da Word su Windows; • Scrivere il documento in Helvetica da Word su Windows; • Disattivare l’incorporamento dei font nel salvataggio PDF su “Word”; Tuttavia, su iOS , in app come Onedrive, il PDF continua a visualizzarsi in Arial C’è un modo per: Evitare che iOS usi Arial se presente? Far sì che venga usato Helvetica come fallback? mi interessa anche capire se si può impedire ad iOS di usare Arial in lettura PDF. Qualcuno ha affrontato un caso simile o conosce un modo affidabile per ottenere questo comportamento cross-platform?
1
0
43
Apr ’25
PDF opening from iOS Unity app in landscape mode instead of portrait
In our Unity App for iOS build, when we opened the PDF from the app, it is automatically opening in landspace mode instead of portrait. In the android and windows apps, we are able to open in the portrait mode. We tried to make the changes in the project settings but it did not change. Any way in which we can acheive this would be helpful for us.
0
0
34
Apr ’25
Push Button captions not properly written to PDF document using PDFKit
The Problem Push buttons (created as a PDFAnnotation using PDFKit) do not properly write the associated caption's key-value pair (within the annotation's appearance characteristics dictionary) to a PDF document. What is Happening Push button widget annotations can have a caption that is displayed as the button’s label. In the PDF 1.7 specification (ISO PDF32000-2008, s. 12.5.6.19), a widget annotation can have an ‘appearance characteristics dictionary’ (MK) with properties to construct the appearance of the widget. The caption property (CA) is used to construct a button’s caption/label. PDFKit uses the PDFAnnotation .caption property to set the value of a push button’s caption as a string. Observation 1: In an open PDF document (using PDFView), a push button widget annotation can be created and added to a PDFPage using the following code: let pushButton = PDFAnnotation(bounds: pushButtonBounds, forType: .widget, withProperties: nil) pushButton.widgetFieldType = .button pushButton.widgetControlType = .pushButtonControl pushButton.caption = "My Button" page.addAnnotation(pushButton) The PDFAnnotation .caption property is used to set the caption to the required string. As a result, the push button is correctly displayed on the PDFPage with the correct label being display on the button. While the PDF document remains open, the appearance characteristics dictionary (an PDFAppearanceCharacteristics object) retains a key-value pair for the caption with the correct value as expected. On saving/writing to the PDF file, however, the key-value pair for the caption in the appearance characteristics dictionary is not written to the PDF document’s file. Resulting PDF markup: 6 0 obj << /Rect [ 256 299.8977 356 399.8977 ] /Border [ 0 0 0 ] /T (button23) /F 4 /Subtype /Widget /DA (/.AppleSystemUIFont 13 Tf 0 g) /MK 8 0 R /C [ 0 ] /AP 9 0 R /V /Off /M (D:20250330154918Z00'00') /FT /Btn /Type /Annot /Ff 65536 >> endobj 9 0 obj << /N 10 0 R >> endobj 8 0 obj << /BG [ 0.75 ] >> endobj 10 0 obj << /Filter /FlateDecode /Type /XObject /Subtype /Form /FormType 1 /BBox [0 0 100 100] /Resources 11 0 R /Length 170 >> stream x }ê1 Ç0 Öw~≈ ahÈ KÈ q1q0\‚`ú Ÿ¿ 8¯Ôm% u0óª‰.Ô{yπ åP°H-}ª‡à y3 ¸ %≠¡‰ %› g¨$•µMVXø‡Hé†Ö ”î“¿˜® BI•L ˆ†b A pü‰Ã @ÓpB∫ †æœs ãÙ:d8Éwÿr»/}” €∂I÷Bõ B;'+gm Ô˝„ mÙ~ L*>• endstream endobj On closing the PDF document, the assigned value for the push button’s caption is not written to the file and is lost. Observation 2: On reopening the PDF document, and assigning a new value for the already-created push button’s caption, a key-value pair for the caption is again correctly added to the PDFAnnotation appearance characteristics dictionary. On saving/writing to the PDF file, this time, the caption key-value pair in the appearance characteristics dictionary is correctly written/saved to the PDF document file. Resulting PDF markup: 6 0 obj << /Border [ 0 0 0 ] /Rect [ 256 299.8977 356 399.8977 ] /T (button23) /F 4 /BS 8 0 R /Subtype /Widget /DA (/.AppleSystemUIFont 13 Tf 0 g) /MK 9 0 R /C [ 0 ] /AP 10 0 R /V /Off /M (D:20250330154918Z00'00') /FT /Btn /Type /Annot /Ff 65536 >> endobj 10 0 obj << /N 11 0 R >> endobj 9 0 obj << /BG [ 0.75 ] /CA (My Button) >> endobj 8 0 obj << /W 0 >> endobj 11 0 obj << /Filter /FlateDecode /Type /XObject /Subtype /Form /FormType 1 /BBox [0 0 100 100] /Resources 12 0 R /Length 163 >> stream x uè1 ¬@ Ö˜˛ä7∂√]ì´◊Î≠ ¡A 8à”a∑Vj·ø˜jë™ !ÅÑ|y/=ˆËA1òʺ]pDá|=0¬“Œb ø+Õ gùf2E≤∞Ê≈N` û·Xm©-BãZ†H Ÿ ¿≈ºPÄ= Ø míãp •¡ ÈÓÅ˙>é “kó· Ÿb#—¬ Ûã¶2∂Ñ2fiΠ;óDÌiÓ?ü>LÁûÊy;} endstream endobj Impact on User Experience: Push button captions may not be properly saved to the PDF document’s file. This may result in an application redrawing a push button without a caption/label. More so, an application that uses the caption value to “read” a button’s label (e.g., for accessibility purposes) will not be able to do so.
1
0
45
Apr ’25
Occasional PDFKit crash at PageLayout::getWordRange(unsigned long, long)
At this line of code (SketchTextSelectionManager.swift:449), sometimes there will be crashes based on crashlytics reports. let selection = pdfPage.selectionForWord(at: location) This is directly calling into PDFKit's PDFPage#selection method: https://developer.apple.com/documentation/pdfkit/pdfpage/selectionforword(at:) Attached the full stacktrace: Crashed: com.apple.root.user-initiated-qos.cooperative 0 CoreGraphics 0x30c968 PageLayout::getWordRange(unsigned long, long) const + 908 1 CoreGraphics 0x30bbc0 PageLayout::getTextRangeIndex(CGPoint, CGPDFSelectionType, SelectionPrecision) const + 2292 2 CoreGraphics 0x44a53c CGPDFSelectionCreateBetweenPointsWithOptions + 384 3 PDFKit 0x8d5f8 -[PDFPage selectionFromPoint:toPoint:type:] + 168 4 PDFKit 0x92040 -[PDFPage _rvItemAtPoint:] + 64 5 PDFKit 0x91f4c -[PDFPage rvItemAtPoint:] + 84 6 PDFKit 0x8caa8 -[PDFPage selectionForWordAtPoint:] + 40 7 MyApp 0x8420e0 closure #1 in SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 449 (SketchTextSelectionManager.swift:449) 8 MyApp 0x841a70 SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 205 (CurrentNoteManager.swift:205) 9 libswift_Concurrency.dylib 0x61104 swift::runJobInEstablishedExecutorContext(swift::Job*) + 252 10 libswift_Concurrency.dylib 0x63a28 (anonymous namespace)::ProcessOutOfLineJob::process(swift::Job*) + 480 11 libswift_Concurrency.dylib 0x611c4 swift::runJobInEstablishedExecutorContext(swift::Job*) + 444 12 libswift_Concurrency.dylib 0x62514 swift_job_runImpl(swift::Job*, swift::SerialExecutorRef) + 144 13 libdispatch.dylib 0x15d8c _dispatch_root_queue_drain + 392 14 libdispatch.dylib 0x16590 _dispatch_worker_thread2 + 156 15 libsystem_pthread.dylib 0x4c40 _pthread_wqthread + 228 16 libsystem_pthread.dylib 0x1488 start_wqthread + 8 ```
0
1
261
Feb ’25
Random PDFKit crash on text selection
At this line of code (SketchTextSelectionManager.swift:378), sometimes there will be crashes based on crashlytics reports. In the reports, it seems like this only happens for RTL text range. let selection = pdfPage.selection( from: CGPoint(x: fromStart.x + 1, y: fromStart.y - 1), to: CGPoint(x: toEnd.x - 1, y: toEnd.y + 1) ) This is directly calling into PDFKit's PDFPage#selection method: https://developer.apple.com/documentation/pdfkit/pdfpage/selection(from:to:) Attached the full stacktrace: Crashed: com.apple.root.user-initiated-qos.cooperative 0 CoreGraphics 0x30598c PageLayout::convertRTLTextRangeIndexToStringRangeIndex(long) const + 156 1 CoreGraphics 0x44c3f0 CGPDFSelectionCreateBetweenPointsWithOptions + 224 2 PDFKit 0x91d00 -[PDFPage selectionFromPoint:toPoint:type:] + 168 3 MyApp 0x841044 closure #1 in SketchTextSelectionManager.handleUserTouchMoved(_:) + 378 (SketchTextSelectionManager.swift:378) 4 MyApp 0x840cb0 SketchTextSelectionManager.handleUserTouchMoved(_:) + 205 (CurrentNoteManager.swift:205) 5 libswift_Concurrency.dylib 0x60f5c swift::runJobInEstablishedExecutorContext(swift::Job*) + 252 6 libswift_Concurrency.dylib 0x63a28 (anonymous namespace)::ProcessOutOfLineJob::process(swift::Job*) + 480 7 libswift_Concurrency.dylib 0x6101c swift::runJobInEstablishedExecutorContext(swift::Job*) + 444 8 libswift_Concurrency.dylib 0x62514 swift_job_runImpl(swift::Job*, swift::SerialExecutorRef) + 144 9 libdispatch.dylib 0x15ec0 _dispatch_root_queue_drain + 392 10 libdispatch.dylib 0x166c4 _dispatch_worker_thread2 + 156 11 libsystem_pthread.dylib 0x3644 _pthread_wqthread + 228 12 libsystem_pthread.dylib 0x1474 start_wqthread + 8
0
1
253
Feb ’25
Exact Extract of Text from PDF
The problem is that when I read out the text in a PDF with page.string or page.attributedString, the context of the lines is lost. Instead of TermA....23,45 TermB....2,13 in an index document TermA TermB 23,45 2,13 is issued. The context of the lines (and the sequence of the letters) is lost. Is there a way to read the text from a PDF line by line?
1
1
445
Jan ’25