Display and manipulate PDF documents in your applications using PDFKit.

Posts under PDFKit tag

200 Posts

Post

Replies

Boosts

Views

Activity

PDFViewVisiblePagesChanged iOS 16
Hi, we have an application that observes PDFViewVisiblePagesChanged and PDFViewPageChanged notifications for detecting the scroll state of a PDFView NotificationCenter.default.addObserver(self,                                                 selector: #selector(handleOnScroll),                                                name: Notification.Name.PDFViewVisiblePagesChanged,                                                 object: nil) NotificationCenter.default.addObserver(self,                                                 selector: #selector(handleOnScroll),                                                name: Notification.Name.PDFViewPageChanged,                                                 object: nil) With iOS14 this worked like a charm, the notification gets triggered immediately when the user starts scrolling the pdf. In iOS16 we have issues, it seems that the notifications get triggered/send only after the scrolling has been completed/stopped. Can anybody confirm this? Has anybody a solution how we can detect a scrolling PDFView using a different method? Background: While the PDF is scrolling other elements of the UI need to be disabled. Thanks Jürgen
0
0
1.2k
Feb ’23
PDFKit Regression ?
What is wrong with this code, on Ventura… it was OK since PDFKit exists, producing a PDF with one page, with a square... but now, a blank page ? import PDFKit let rect = NSRect(x: 0, y: 0, width: 100, height: 100) let newImage = NSImage(size: rect.size, flipped: false) { (_: NSRect) -> Bool in let path = NSBezierPath(rect: NSRect(x: 10, y: 10, width: 80, height: 80)) path.stroke() return true } let outPDF = PDFDocument() guard let pdfPage = PDFPage(image: newImage) else { fatalError("pdfPage") } outPDF.insert(pdfPage, at: 0) let outURL = URL(fileURLWithPath: "out.pdf") outPDF.write(to: outURL) Any help is welcome.
0
0
1.4k
Jan ’23
Strategies for minimizing OOM crashes?
Hello, We are facing many memory related crashes. Right now this is our top crash reason and after reading through many other useful posts in the forums, such as "how Xcode to calculate Memory" where @eskimo provided lots of useful info, and talks such as iOS Memory Deep Dive I figured out it was time to post a new thread to see if anyone can help. Our crashes generally happen when drawing a PDF (using PDFKit's draw(with:to:)), although they also happen in other places where memory is needed such as Array.insert (which ends up calling swift_slowAlloc and swift_slowAlloc.cold), or std::bad_alloc. The exceptions are either EXC_BREAKPOINT on CFRetain, NSMallocException (Failed to grow buffer), or the previously mentioned std:bad_alloc. In addition to this, we have many other OOM that are not tracked by our crash reporting tool. For crashes that are reported, the average free RAM our users have ranges from 30 MB to 120 MB. In other cases the user seems to have 400 MB of free RAM or even more. I have a few questions around this that I hope are also useful for other folks. Besides general recommendations of using less memory in general, what's the recommended approach for minimizing these memory issues? Most of our disposable memory is in held in NSCaches (with reasonable total cost limits and properly calculated cost per object). On this case, is it recommended to handle the NSMallocExceptions, try to free memory, and retry the operation? As mentioned, in many cases we don't even get memory warnings prior to the crashes. I'm wondering if memory fragmentation is also affecting us, but I don't think there's much we can do about this. I noticed PDFKit requesting allocations as large as 30 MB to render a 100x100 thumbnail (when I simulated a situation where I ran out of VM, I caught that with the ASAN, which reports the memory that was attempted to be allocated). Another alternative I could think of is to try to use os_proc_available_memory() and try to free some memory if memory is low. The reasoning behind this is that since we have no way to know how much memory the operation it's going to use, but we have data of free memory of users with crashes, we could try to free up memory to be above that. I'm not sure how effective would that be though. As some of these users seem to have enough RAM, they might be running out of virtual memory. What's the best way to track Virtual Memory, to use it as a hint in our crash reports? Reading the virtual_size from task_vm_info in my iPad returns over 400 GB. I was expecting this to be the virtual used size, like the size that gets reported on the VM Tracker instrument. I mention this because I was able to reproduce these crashes by memory mapping ~50 GB of a 200 MB file in a 2017 iPad Pro, and then doing other unrelated memory operations. For apps that are document based, with arbitrary-sized documents, is it recommended to ask for the extended virtual addressing entitlement and the increased memory limit one? Could these help on lower end devices? Would listening to memory pressure events help at all? There's a .warning and .critical memory pressure events. I'm wondering wether the system wide warnings only are sent when the memory pressure is critical, although it doesn't look like it looking at the names of the constants. If I'm using NSCache, is it safe (memory compression wise) to empty the cache under some circumstances? Put it in a different way: does emptying an NSCache causes the memory compressor to decompress the data? Are there any other recommendations or things that I might have missed? Thanks a lot in advance!
0
1
2.4k
Dec ’22
printtool process sandboxed to oblivion: PDF Services don't work
Since Big Sur, the printtool process has been sandboxed, with the result that it's now so secure, it can't do anything. As a consequence, PDF Services (items in ~/Library/PDF Services) no longer work. An alias to a folder outside the user domain, such as /Users/Shared/, no longer saves the PDF file to that location. Shell scripts, python, and even compiled Swift binaries no long run. Even Automator Print plug-ins no longer function. Adding printtool to Full Disk Access doesn't work either. ("If in doubt, add the process to Full Disk Access.") The ability to process PDFs directly from the print dialog goes back to Tiger (I think) and has been massively useful for years. Yes, I suppose some malware could save a script to the user PDF Services folder, and then some unwitting user could run it from the print dialog, but.... At the very least, some new documentation about how PDF Services are now supposed to work would be crucial.
2
0
2.2k
Dec ’22
PDKKit Sample code
Trying to locate the sample code from the WWDC video on the updated PDKKit for iOS 16+ with overlay functionality. Looks like the only references are pointing to an older 2017 project. Is this sample code available anywhere? Here is the link to the announcement video: https://developer.apple.com/videos/play/wwdc2022/10089/
2
1
1.4k
Dec ’22
Make a pdf document by image using pdfkit in iOS 16
While we make a pdf using an image file at that we add an image into PDFPage. at that time PDFDocument did not show the original image content in PDFView in iOS 16. I checked the same code which worked properly in iOS 15. For both test cases, I used New Xcode 14, and as well as previously uploaded TestFlight build also worked properly with iOS 15 or below but did not work with iOS 16. So I request to the apple developer who worked on PDFkit please check this case. I may be sure that there is an issue with iOS 16 and I hope apple provides a new iOS 16 sub-version release as soon as possible with includes this bug fix. here is the sample code that I used:- //Get Array of UIImages let pdfDocument = PDFDocument() for (index,image) in images.enumerated() { // Create a PDF page instance from your image let pdfPage = PDFPage(image: image) // Insert the PDF page into your document pdfDocument.insert(pdfPage!, at: index) } Original Image: After convert to PDF
4
3
4.0k
Dec ’22
ios 16 PDFView UIEditMenuInteraction bug
In my app I have custom menu for PDFView. It was implemented using UIMenuController but stopped work in ios16. The reason is that is now deprecated in ios16 and we should use UIEditMenuInteraction. Problem is for some reason ios call dismiss on my menu created by UIEditMenuInteraction (see it in willDimissMenu delegate) and shows default menu. I try to workaround it displaying my custom view catching willDismissMenu but cant hide default menu (UIMenuController.shared.hideMenu() deprecated and doesnt work). I think its bug with implementation of UIEditMenuInteraction and PDFView. Any ideas how to workaround this ?
2
1
1.5k
Dec ’22
PDFKit create document version is 1.3 can we create an PDF 1.7 document?
Working with PDFkit on MacOS 12.6 and created a new PDFDocument instance. checking the HEX code of this PDF document and notice this, At the beginning there is "%PDF-1.3%". Is it possible to create a new PDFDocument in PDF Spec 1.7 version instead? if not possible with current version, any plan in the future? is there a plan to have equivalence of PDFKit in SWIFTUI world around the corner? thanks
0
0
1.3k
Oct ’22
redact functionality absent in PDFKit
Prior to macOS 10.12, text markup annotations were configured through the PDFAnnotationMarkup class (see here). An annotation of this type could be configured to use the redact, underline, strikeOut, or highlight enumerations. However, this has since been deprecated in favor of creating a PDFAnnotation with the PDFAnnotationSubtype structure. Subtypes exist for underline, highlight, and strikeOut, but no option for redact exists. What is the proper way to create a redaction annotation in the current API?
1
1
842
Oct ’22
Error exporting a PDF
I am trying to build an app that allows users to share their lists to other. To do this I am trying to capture the list as an image and turn it into a PDF. When I send the PDF it comes with a white screen. Is there a way to fix this? Is there somethings wrong with this code? struct ShareSheet {       static let instance = ShareSheet()       private init() { }       func share(items: [Any]) {     let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)     UIApplication.shared.currentUIWindow()?.rootViewController?.present(controller, animated: true, completion: nil)   }     } public extension UIApplication {   func currentUIWindow() -> UIWindow? {     let connectedScenes = UIApplication.shared.connectedScenes       .filter({         $0.activationState == .foregroundActive})       .compactMap({$0 as? UIWindowScene})           let window = connectedScenes.first?       .windows       .first { $0.isKeyWindow }     return window         } } extension View{       func sharePDF<Content: View> (@ViewBuilder content: @escaping () -> Content, fileName: String) {     exportPDF(content: content, completion: { status , url in       if let url = url, status {         ShareSheet.instance.share(items: [url])       } else {         print("⚠️ Failed to make PDF")       }     }, fileName: fileName)   }       // MARK: Extracting View's Height and width with the Help of Hosting Controller and ScrollView   fileprivate func convertToScrollView<Content: View>(@ViewBuilder content: @escaping ()->Content)->UIScrollView{           let scrollView = UIScrollView()           // MARK: Converting SwiftUI View to UIKit View     let hostingController = UIHostingController(rootView: content()).view!     hostingController.translatesAutoresizingMaskIntoConstraints = false           // MARK: Constraints     let constraints = [             hostingController.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),       hostingController.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),       hostingController.topAnchor.constraint(equalTo: scrollView.topAnchor),       hostingController.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),               // Width Anchor       hostingController.widthAnchor.constraint(equalToConstant: screenBounds().width)     ]     scrollView.addSubview(hostingController)     scrollView.addConstraints(constraints)     scrollView.layoutIfNeeded()           return scrollView   }       // MARK: Export to PDF   // MARK: Completion Handler will Send Status and URL   fileprivate func exportPDF<Content: View>(@ViewBuilder content: @escaping ()->Content,completion: @escaping (Bool,URL?)->(), fileName: String){           // MARK: Temp URL     let documentDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!     // MARK: To Generate New File when ever its generated     let outputFileURL = documentDirectory.appendingPathComponent("\(fileName)\(UUID().uuidString).pdf")           // MARK: PDF View     let pdfView = convertToScrollView {       content()     }     pdfView.tag = 1009     let size = pdfView.contentSize     // Removing Safe Area Top Value     pdfView.frame = CGRect(x: 0, y: getSafeArea().top, width: size.width, height: size.height)           // MARK: Attaching to Root View and rendering the PDF     getRootController().view.insertSubview(pdfView, at: 0)           // MARK: Rendering PDF     let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height))           do{               try renderer.writePDF(to: outputFileURL, withActions: { context in                   context.beginPage()         pdfView.layer.render(in: context.cgContext)       })               completion(true,outputFileURL)     }     catch{       completion(false,nil)       print(error.localizedDescription)     }           // Removing the added View     getRootController().view.subviews.forEach { view in       if view.tag == 1009{         print("Removed")         view.removeFromSuperview()       }     }   }       fileprivate func screenBounds()->CGRect{     return UIScreen.main.bounds   }       fileprivate func getRootController()->UIViewController{     guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{       return .init()     }           guard let root = screen.windows.first?.rootViewController else{       return .init()     }           return root   }       fileprivate func getSafeArea()->UIEdgeInsets{     guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{       return .zero     }           guard let safeArea = screen.windows.first?.safeAreaInsets else{       return .zero     }           return safeArea   } }
1
0
1.1k
Oct ’22
PDF Annotation for file from AWS S3 bucket
We have application where our cloud storage is on AWS S3 bucket and want to use annotation feature on PDF through my iOS application. iOS application is coded in language native language can anyone please provide necessary documents to implement this yeah. Where I can access files from AWS S3 bucket and do annotation on my PDF file through iOS application
0
0
682
Sep ’22
PDFKit setBounds to trimBox doesn't work as expected in iOS16
Hi, I found the setBounds:forBox: function doesn't set the bounds of trimBox as expected in iOS16. On iOS15.6, when the setBounds is called and page is larger than the specified bounds, the page will shrink and resize to fit inside the specified bounds; but on iOS16, it doesn't do anything. From the debugger I can tell that the trimBox bounds is indeed set to the specified size, but I'm not sure what underlying logic is broken. Has anyone seen similar issues in iOS16?
0
0
780
Sep ’22
Accessibility of PDF on Apple platforms in 2022 and beyond
I'm finding it extremely difficult to find accurate and up-to-date information about support for accessibility with PDF on Apple's platforms, in particular Safari and Preview on iOS and Mac. For a long time it seemed that nothing worked (e.g. browsing a PDF with VoiceOver in Preview), but I've started to get some acceptable, but patchy results. Apparently things have changed under the hood since the extensive outcry at High Sierra's implementation of PDFKit but what exactly has changed? Is there a change log anywhere? Did any of the notorious PDFKit bugs from 2017 get fixed? I will mention some important jargon used in the accessibility community: "Accessibility supported". This term has a formal definition in the WCAG spec. Basically it's not enough that a file format (such as PDF) or an app (such as Safari) is hypothetically accessible, if I can't actually browse my PDF in Safari using Voiceover. Legally speaking, this information should be absolutely clear in the VPAT for Mac OS. It isn't. Lawyers with an interest in accessibility suits should take note. My questions: I've studied the latest documentation for PDFKit and can find no mention of semantic tagging, read order or the PDF/UA format in general. How does this work? Did Apple invent new names for these features, or is it simply unsupported? Can I use VoiceOver to browse a well-formed tagged PDF/UA file 'semantically' in Safari? (E.g. 'next heading' keyboard shortcut, or using the rotor). If I save a PDF from Safari or Preview, do I get a well-formed 'accessible PDF' (i.e. a "tagged PDF" file with the PDF/UA flag)? How might HTML semantics be mapped onto PDF/UA output, when saving a web page as PDF from Safari, given that there is not 100% parity between the two semantic systems? Can I browse PDF/UA files in Acrobat Reader with VoiceOver? If not, why aren't Apple and Adobe taking steps to fix this situation? I understand that Pages, Numbers and Keynote all produce tagged PDF. I assume this means some conformance with the PDF/UA 1.7 spec? Are there any omissions in support for the PDF/UA standard by this route? What are those omissions? Regarding the accessibility of the output, is there any difference between "Save as PDF", "Export PDF" and "Print to PDF" in Apple's software? Please advise on any of these points.
0
1
1.6k
Sep ’22
WKWebView: loadHTMLString and createPDF always fails since updating to macOS Monterey
Hello, I had programmed and used a software for a year without problems but after updating to Monterey and updating XCode, the following, simplified Playground example of the process always fails and I cannot figure out why. Please note this project is specifically written for macOS and I cannot use the iOS libraries for PDF generation. import WebKit import PDFKit import SwiftUI import CoreGraphics let webView: WKWebView = WKWebView(frame: CGRect(x: 0, y: 0, width: 595.0, height: 842.0), configuration: WKWebViewConfiguration()) let htmlString = "<html><body><h1>Hello</h1></body></html>" webView.loadHTMLString(htmlString, baseURL: nil) webView.createPDF(completionHandler: compHandler) func compHandler(res: Result<Data, Error>) -> Void { print(res) } This always results in an error: failure(Error Domain=WKErrorDomain Code=1 "An unknown error occurred" UserInfo={NSLocalizedDescription=An unknown error occurred}) I cannot find anything in the documentation regarding this and most examples and questions are old and not applicable (many still using Objective-C). Debugging seems to suggest that the loadHTMLString itself fails, not even necessarily the PDF itself. Any pointers would be appreciated. Thanks
0
0
1.3k
Sep ’22
PDFViewVisiblePagesChanged iOS 16
Hi, we have an application that observes PDFViewVisiblePagesChanged and PDFViewPageChanged notifications for detecting the scroll state of a PDFView NotificationCenter.default.addObserver(self,                                                 selector: #selector(handleOnScroll),                                                name: Notification.Name.PDFViewVisiblePagesChanged,                                                 object: nil) NotificationCenter.default.addObserver(self,                                                 selector: #selector(handleOnScroll),                                                name: Notification.Name.PDFViewPageChanged,                                                 object: nil) With iOS14 this worked like a charm, the notification gets triggered immediately when the user starts scrolling the pdf. In iOS16 we have issues, it seems that the notifications get triggered/send only after the scrolling has been completed/stopped. Can anybody confirm this? Has anybody a solution how we can detect a scrolling PDFView using a different method? Background: While the PDF is scrolling other elements of the UI need to be disabled. Thanks Jürgen
Replies
0
Boosts
0
Views
1.2k
Activity
Feb ’23
PDFKit Regression ?
What is wrong with this code, on Ventura… it was OK since PDFKit exists, producing a PDF with one page, with a square... but now, a blank page ? import PDFKit let rect = NSRect(x: 0, y: 0, width: 100, height: 100) let newImage = NSImage(size: rect.size, flipped: false) { (_: NSRect) -> Bool in let path = NSBezierPath(rect: NSRect(x: 10, y: 10, width: 80, height: 80)) path.stroke() return true } let outPDF = PDFDocument() guard let pdfPage = PDFPage(image: newImage) else { fatalError("pdfPage") } outPDF.insert(pdfPage, at: 0) let outURL = URL(fileURLWithPath: "out.pdf") outPDF.write(to: outURL) Any help is welcome.
Replies
0
Boosts
0
Views
1.4k
Activity
Jan ’23
Strategies for minimizing OOM crashes?
Hello, We are facing many memory related crashes. Right now this is our top crash reason and after reading through many other useful posts in the forums, such as "how Xcode to calculate Memory" where @eskimo provided lots of useful info, and talks such as iOS Memory Deep Dive I figured out it was time to post a new thread to see if anyone can help. Our crashes generally happen when drawing a PDF (using PDFKit's draw(with:to:)), although they also happen in other places where memory is needed such as Array.insert (which ends up calling swift_slowAlloc and swift_slowAlloc.cold), or std::bad_alloc. The exceptions are either EXC_BREAKPOINT on CFRetain, NSMallocException (Failed to grow buffer), or the previously mentioned std:bad_alloc. In addition to this, we have many other OOM that are not tracked by our crash reporting tool. For crashes that are reported, the average free RAM our users have ranges from 30 MB to 120 MB. In other cases the user seems to have 400 MB of free RAM or even more. I have a few questions around this that I hope are also useful for other folks. Besides general recommendations of using less memory in general, what's the recommended approach for minimizing these memory issues? Most of our disposable memory is in held in NSCaches (with reasonable total cost limits and properly calculated cost per object). On this case, is it recommended to handle the NSMallocExceptions, try to free memory, and retry the operation? As mentioned, in many cases we don't even get memory warnings prior to the crashes. I'm wondering if memory fragmentation is also affecting us, but I don't think there's much we can do about this. I noticed PDFKit requesting allocations as large as 30 MB to render a 100x100 thumbnail (when I simulated a situation where I ran out of VM, I caught that with the ASAN, which reports the memory that was attempted to be allocated). Another alternative I could think of is to try to use os_proc_available_memory() and try to free some memory if memory is low. The reasoning behind this is that since we have no way to know how much memory the operation it's going to use, but we have data of free memory of users with crashes, we could try to free up memory to be above that. I'm not sure how effective would that be though. As some of these users seem to have enough RAM, they might be running out of virtual memory. What's the best way to track Virtual Memory, to use it as a hint in our crash reports? Reading the virtual_size from task_vm_info in my iPad returns over 400 GB. I was expecting this to be the virtual used size, like the size that gets reported on the VM Tracker instrument. I mention this because I was able to reproduce these crashes by memory mapping ~50 GB of a 200 MB file in a 2017 iPad Pro, and then doing other unrelated memory operations. For apps that are document based, with arbitrary-sized documents, is it recommended to ask for the extended virtual addressing entitlement and the increased memory limit one? Could these help on lower end devices? Would listening to memory pressure events help at all? There's a .warning and .critical memory pressure events. I'm wondering wether the system wide warnings only are sent when the memory pressure is critical, although it doesn't look like it looking at the names of the constants. If I'm using NSCache, is it safe (memory compression wise) to empty the cache under some circumstances? Put it in a different way: does emptying an NSCache causes the memory compressor to decompress the data? Are there any other recommendations or things that I might have missed? Thanks a lot in advance!
Replies
0
Boosts
1
Views
2.4k
Activity
Dec ’22
printtool process sandboxed to oblivion: PDF Services don't work
Since Big Sur, the printtool process has been sandboxed, with the result that it's now so secure, it can't do anything. As a consequence, PDF Services (items in ~/Library/PDF Services) no longer work. An alias to a folder outside the user domain, such as /Users/Shared/, no longer saves the PDF file to that location. Shell scripts, python, and even compiled Swift binaries no long run. Even Automator Print plug-ins no longer function. Adding printtool to Full Disk Access doesn't work either. ("If in doubt, add the process to Full Disk Access.") The ability to process PDFs directly from the print dialog goes back to Tiger (I think) and has been massively useful for years. Yes, I suppose some malware could save a script to the user PDF Services folder, and then some unwitting user could run it from the print dialog, but.... At the very least, some new documentation about how PDF Services are now supposed to work would be crucial.
Replies
2
Boosts
0
Views
2.2k
Activity
Dec ’22
PDKKit Sample code
Trying to locate the sample code from the WWDC video on the updated PDKKit for iOS 16+ with overlay functionality. Looks like the only references are pointing to an older 2017 project. Is this sample code available anywhere? Here is the link to the announcement video: https://developer.apple.com/videos/play/wwdc2022/10089/
Replies
2
Boosts
1
Views
1.4k
Activity
Dec ’22
Make a pdf document by image using pdfkit in iOS 16
While we make a pdf using an image file at that we add an image into PDFPage. at that time PDFDocument did not show the original image content in PDFView in iOS 16. I checked the same code which worked properly in iOS 15. For both test cases, I used New Xcode 14, and as well as previously uploaded TestFlight build also worked properly with iOS 15 or below but did not work with iOS 16. So I request to the apple developer who worked on PDFkit please check this case. I may be sure that there is an issue with iOS 16 and I hope apple provides a new iOS 16 sub-version release as soon as possible with includes this bug fix. here is the sample code that I used:- //Get Array of UIImages let pdfDocument = PDFDocument() for (index,image) in images.enumerated() { // Create a PDF page instance from your image let pdfPage = PDFPage(image: image) // Insert the PDF page into your document pdfDocument.insert(pdfPage!, at: index) } Original Image: After convert to PDF
Replies
4
Boosts
3
Views
4.0k
Activity
Dec ’22
ios 16 PDFView UIEditMenuInteraction bug
In my app I have custom menu for PDFView. It was implemented using UIMenuController but stopped work in ios16. The reason is that is now deprecated in ios16 and we should use UIEditMenuInteraction. Problem is for some reason ios call dismiss on my menu created by UIEditMenuInteraction (see it in willDimissMenu delegate) and shows default menu. I try to workaround it displaying my custom view catching willDismissMenu but cant hide default menu (UIMenuController.shared.hideMenu() deprecated and doesnt work). I think its bug with implementation of UIEditMenuInteraction and PDFView. Any ideas how to workaround this ?
Replies
2
Boosts
1
Views
1.5k
Activity
Dec ’22
Flatten PDF in PDFKit
I am opening a PDF doc and adding various annotations to it stamp, text etc . Once I fill those annotations I need to flatten the PDF but I don't find a direct way to do it. How can we flatten a PDF with annotations? Thanks
Replies
2
Boosts
0
Views
2.3k
Activity
Nov ’22
PDFKit create document version is 1.3 can we create an PDF 1.7 document?
Working with PDFkit on MacOS 12.6 and created a new PDFDocument instance. checking the HEX code of this PDF document and notice this, At the beginning there is "%PDF-1.3%". Is it possible to create a new PDFDocument in PDF Spec 1.7 version instead? if not possible with current version, any plan in the future? is there a plan to have equivalence of PDFKit in SWIFTUI world around the corner? thanks
Replies
0
Boosts
0
Views
1.3k
Activity
Oct ’22
redact functionality absent in PDFKit
Prior to macOS 10.12, text markup annotations were configured through the PDFAnnotationMarkup class (see here). An annotation of this type could be configured to use the redact, underline, strikeOut, or highlight enumerations. However, this has since been deprecated in favor of creating a PDFAnnotation with the PDFAnnotationSubtype structure. Subtypes exist for underline, highlight, and strikeOut, but no option for redact exists. What is the proper way to create a redaction annotation in the current API?
Replies
1
Boosts
1
Views
842
Activity
Oct ’22
Error exporting a PDF
I am trying to build an app that allows users to share their lists to other. To do this I am trying to capture the list as an image and turn it into a PDF. When I send the PDF it comes with a white screen. Is there a way to fix this? Is there somethings wrong with this code? struct ShareSheet {       static let instance = ShareSheet()       private init() { }       func share(items: [Any]) {     let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)     UIApplication.shared.currentUIWindow()?.rootViewController?.present(controller, animated: true, completion: nil)   }     } public extension UIApplication {   func currentUIWindow() -> UIWindow? {     let connectedScenes = UIApplication.shared.connectedScenes       .filter({         $0.activationState == .foregroundActive})       .compactMap({$0 as? UIWindowScene})           let window = connectedScenes.first?       .windows       .first { $0.isKeyWindow }     return window         } } extension View{       func sharePDF<Content: View> (@ViewBuilder content: @escaping () -> Content, fileName: String) {     exportPDF(content: content, completion: { status , url in       if let url = url, status {         ShareSheet.instance.share(items: [url])       } else {         print("⚠️ Failed to make PDF")       }     }, fileName: fileName)   }       // MARK: Extracting View's Height and width with the Help of Hosting Controller and ScrollView   fileprivate func convertToScrollView<Content: View>(@ViewBuilder content: @escaping ()->Content)->UIScrollView{           let scrollView = UIScrollView()           // MARK: Converting SwiftUI View to UIKit View     let hostingController = UIHostingController(rootView: content()).view!     hostingController.translatesAutoresizingMaskIntoConstraints = false           // MARK: Constraints     let constraints = [             hostingController.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),       hostingController.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),       hostingController.topAnchor.constraint(equalTo: scrollView.topAnchor),       hostingController.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),               // Width Anchor       hostingController.widthAnchor.constraint(equalToConstant: screenBounds().width)     ]     scrollView.addSubview(hostingController)     scrollView.addConstraints(constraints)     scrollView.layoutIfNeeded()           return scrollView   }       // MARK: Export to PDF   // MARK: Completion Handler will Send Status and URL   fileprivate func exportPDF<Content: View>(@ViewBuilder content: @escaping ()->Content,completion: @escaping (Bool,URL?)->(), fileName: String){           // MARK: Temp URL     let documentDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!     // MARK: To Generate New File when ever its generated     let outputFileURL = documentDirectory.appendingPathComponent("\(fileName)\(UUID().uuidString).pdf")           // MARK: PDF View     let pdfView = convertToScrollView {       content()     }     pdfView.tag = 1009     let size = pdfView.contentSize     // Removing Safe Area Top Value     pdfView.frame = CGRect(x: 0, y: getSafeArea().top, width: size.width, height: size.height)           // MARK: Attaching to Root View and rendering the PDF     getRootController().view.insertSubview(pdfView, at: 0)           // MARK: Rendering PDF     let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height))           do{               try renderer.writePDF(to: outputFileURL, withActions: { context in                   context.beginPage()         pdfView.layer.render(in: context.cgContext)       })               completion(true,outputFileURL)     }     catch{       completion(false,nil)       print(error.localizedDescription)     }           // Removing the added View     getRootController().view.subviews.forEach { view in       if view.tag == 1009{         print("Removed")         view.removeFromSuperview()       }     }   }       fileprivate func screenBounds()->CGRect{     return UIScreen.main.bounds   }       fileprivate func getRootController()->UIViewController{     guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{       return .init()     }           guard let root = screen.windows.first?.rootViewController else{       return .init()     }           return root   }       fileprivate func getSafeArea()->UIEdgeInsets{     guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{       return .zero     }           guard let safeArea = screen.windows.first?.safeAreaInsets else{       return .zero     }           return safeArea   } }
Replies
1
Boosts
0
Views
1.1k
Activity
Oct ’22
Exporting a PDF that is White
I am building an app which allows users to share their list to other people. To do that I tried to turn the view into a PDF, but when sharing it, it is a white image. How can I fix this so the PDF shows the view instead of a white screen?
Replies
1
Boosts
0
Views
897
Activity
Oct ’22
PDF Annotation for file from AWS S3 bucket
We have application where our cloud storage is on AWS S3 bucket and want to use annotation feature on PDF through my iOS application. iOS application is coded in language native language can anyone please provide necessary documents to implement this yeah. Where I can access files from AWS S3 bucket and do annotation on my PDF file through iOS application
Replies
0
Boosts
0
Views
682
Activity
Sep ’22
PDFKit setBounds to trimBox doesn't work as expected in iOS16
Hi, I found the setBounds:forBox: function doesn't set the bounds of trimBox as expected in iOS16. On iOS15.6, when the setBounds is called and page is larger than the specified bounds, the page will shrink and resize to fit inside the specified bounds; but on iOS16, it doesn't do anything. From the debugger I can tell that the trimBox bounds is indeed set to the specified size, but I'm not sure what underlying logic is broken. Has anyone seen similar issues in iOS16?
Replies
0
Boosts
0
Views
780
Activity
Sep ’22
Accessibility of PDF on Apple platforms in 2022 and beyond
I'm finding it extremely difficult to find accurate and up-to-date information about support for accessibility with PDF on Apple's platforms, in particular Safari and Preview on iOS and Mac. For a long time it seemed that nothing worked (e.g. browsing a PDF with VoiceOver in Preview), but I've started to get some acceptable, but patchy results. Apparently things have changed under the hood since the extensive outcry at High Sierra's implementation of PDFKit but what exactly has changed? Is there a change log anywhere? Did any of the notorious PDFKit bugs from 2017 get fixed? I will mention some important jargon used in the accessibility community: "Accessibility supported". This term has a formal definition in the WCAG spec. Basically it's not enough that a file format (such as PDF) or an app (such as Safari) is hypothetically accessible, if I can't actually browse my PDF in Safari using Voiceover. Legally speaking, this information should be absolutely clear in the VPAT for Mac OS. It isn't. Lawyers with an interest in accessibility suits should take note. My questions: I've studied the latest documentation for PDFKit and can find no mention of semantic tagging, read order or the PDF/UA format in general. How does this work? Did Apple invent new names for these features, or is it simply unsupported? Can I use VoiceOver to browse a well-formed tagged PDF/UA file 'semantically' in Safari? (E.g. 'next heading' keyboard shortcut, or using the rotor). If I save a PDF from Safari or Preview, do I get a well-formed 'accessible PDF' (i.e. a "tagged PDF" file with the PDF/UA flag)? How might HTML semantics be mapped onto PDF/UA output, when saving a web page as PDF from Safari, given that there is not 100% parity between the two semantic systems? Can I browse PDF/UA files in Acrobat Reader with VoiceOver? If not, why aren't Apple and Adobe taking steps to fix this situation? I understand that Pages, Numbers and Keynote all produce tagged PDF. I assume this means some conformance with the PDF/UA 1.7 spec? Are there any omissions in support for the PDF/UA standard by this route? What are those omissions? Regarding the accessibility of the output, is there any difference between "Save as PDF", "Export PDF" and "Print to PDF" in Apple's software? Please advise on any of these points.
Replies
0
Boosts
1
Views
1.6k
Activity
Sep ’22
WKWebView: loadHTMLString and createPDF always fails since updating to macOS Monterey
Hello, I had programmed and used a software for a year without problems but after updating to Monterey and updating XCode, the following, simplified Playground example of the process always fails and I cannot figure out why. Please note this project is specifically written for macOS and I cannot use the iOS libraries for PDF generation. import WebKit import PDFKit import SwiftUI import CoreGraphics let webView: WKWebView = WKWebView(frame: CGRect(x: 0, y: 0, width: 595.0, height: 842.0), configuration: WKWebViewConfiguration()) let htmlString = "<html><body><h1>Hello</h1></body></html>" webView.loadHTMLString(htmlString, baseURL: nil) webView.createPDF(completionHandler: compHandler) func compHandler(res: Result<Data, Error>) -> Void { print(res) } This always results in an error: failure(Error Domain=WKErrorDomain Code=1 "An unknown error occurred" UserInfo={NSLocalizedDescription=An unknown error occurred}) I cannot find anything in the documentation regarding this and most examples and questions are old and not applicable (many still using Objective-C). Debugging seems to suggest that the loadHTMLString itself fails, not even necessarily the PDF itself. Any pointers would be appreciated. Thanks
Replies
0
Boosts
0
Views
1.3k
Activity
Sep ’22