Display and manipulate PDF documents in your applications using PDFKit.

Posts under PDFKit tag

200 Posts

Post

Replies

Boosts

Views

Activity

PDFKit PencilKit annotations sample code
Hello, I was wondering if the sample code shown in Session 10089 of WWDC22 could be made available? To be more specific, I am interested in overlaying a PencilKit PKCanvasView over a PDFKit PDFView. I can't seem to get the PKCanvasView to recognize touch events. This isn't really covered in the session, and I can't get it to work. I managed to overlay PKCanvasViews by copying the code from the session, but I can't draw anything because the touch events are interpreted by the PDFView as scroll gestures. Any help would be appreciated :) Thank you!
4
1
2.5k
Apr ’23
UIMarkupTextPrintFormatter crash at the time of initialisation
while initialising the UIMarkupTextPrintFormatter the app is crashing with the following error. Thread 1: EXC_BAD_ACCESS(code =1, address=0x0) sample code: let formatter = UIMarkupTextPrintFormatter(markupText: content) the parameter content is the HTML string. Tried with passing simple HTML string but still having the same crash. The Occurrence of the crash is 7/10 times and mostly when the device is offline. Issue specifically occurring in iPad OS 16.3 Attaching the screenshot for reference.
0
0
733
Apr ’23
Swift PDFKit generate PDF with opaque background
I'm trying to generate a pdf with a transparent background for vector graphics and I've tried everything google has suggested, but I still keep getting a white background every time. Filling the page with clear color didn't seem to work, and I couldn't figure out how to set the background of the page. Any thoughts? func draw() -> Data { let metadata = [] let format = UIGraphicsPDFRendererFormat() format.documentInfo = metadata as [String: Any] let pageWidth = 3 * 72.0 let pageHeight = 3 * 72.0 let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight) let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format) let data = renderer.pdfData { (context) in context.beginPage() let currentContext = UIGraphicsGetCurrentContext() currentContext?.setFillColor(UIColor.clear.cgColor) currentContext?.fill(pageRect) let circlePath = UIBezierPath(arcCenter: CGPoint(x: pageWidth / 2, y: pageHeight / 2), radius: CGFloat(100), startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true) UIColor.init(cgColor: colors[0].cgColor).setFill(); UIColor.init(cgColor: colors[0].cgColor).setStroke(); circlePath.fill() circlePath.stroke() } let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { try data.write(to: URL(fileURLWithPath: "\(documentsPath)/file.pdf")) } catch { print(error) } return data }
2
0
1.8k
Apr ’23
Save/export PDF file changes page numbers
Hi everyone I have an iOS16 app that is using PDFKit to add annotations to PDFs, and I'm trying to track down an issue with some files getting corrupted when I save the annotations. As part of this testing I am looking at the original PDFs in Preview. These documents are supplied by a third-party, so are not created by us. It turns out, I have a problem simply exporting those PDFs from Preview in Monterey (12.6). When I open a PDF document in Preview and Export it using the Reduce file size Quartz filter, the page numbers are messed up and the table of contents links become incorrect (out by 1 page). The document originally had Roman numerals, I, II, III, IV, 1, 2 pages, and after exporting these page labels changed to 1, 2, 3, 4, 5, 6 This is what I am seeing in my app as well. What can I do to track down the cause, and hopefully find a solution or workaround?
1
0
608
Mar ’23
Word file to PDF with osascript
Why is this giving a super messed up PDF with no images? What am I doing wrong? use AppleScript version "2.8" use scripting additions use framework "Foundation" use framework "AppKit" -- dimensions of print area: property thePaperSize : {height:479, width:516} property theLeft : 0 property theRight : 0 property theTop : 0 property theBottom : 0 on run argv set course to "course1" set theyear to "2023" set semester to "Spring" set exam to item 1 of argv set session to item 2 of argv set chapters to item 3 of argv if semester="Spring" then set sem_num to "1" else if semester="Summer" then set sem_num to "2" else if semester="Fall" then set sem_num to "3" else return "wrong semester" end if set inpath to "/Users/Dropbox/"& course &" - " & "Current/" & theyear & "-"& sem_num &"-"& semester &"/2." & " " & "Chapter" & " " & "Reviews/" & ¬ "Exam" & " " & exam & " " & "Session" & " " & session & "/"& course &" Exam " & exam & " Session " & session & " (Ch "& chapters &").docx" -- choose Word document file, make URL and build destination path set posixPath to inpath set theURL to current application's |NSURL|'s fileURLWithPath:posixPath set destPath to theURL's |path|()'s stringByDeletingPathExtension()'s stringByAppendingPathExtension:"pdf" -- get doc's contents as styled text set {styledText, theError} to current application's NSAttributedString's alloc()'s initWithURL:theURL options:(missing value) documentAttributes:(missing val$ if styledText = missing value then error (theError's localizedDescription() as text) -- set up printing specs set printInf to current application's NSPrintInfo's sharedPrintInfo()'s |copy|() printInf's setJobDisposition:(current application's NSPrintSaveJob) printInf's dictionary()'s setObject:destPath forKey:(current application's NSPrintSavePath) -- make text view and add text set theView to current application's NSTextView's alloc()'s initWithFrame:{{0, 0}, {(width of thePaperSize) - theLeft - theRight, (height of thePaperSize) - $ theView's textStorage()'s setAttributedString:styledText -- set up and run print operation without showing dialog set theOp to current application's NSPrintOperation's printOperationWithView:theView printInfo:printInf theOp's setShowsPrintPanel:false theOp's setShowsProgressPanel:false theOp's runOperation() end run
2
0
941
Mar ’23
Exporting pdf from safari (Mac OS)
Exporting pdf from Safari is the best export tool by far, comparing all the existing ones of other browsers. Great job, Apple!! It is very useful for rendering web pages to pdf for signing documents for legal purposes. But here is the problem: Safari cannot generate page breaks in din A4 format. The pdf resulting from the export is two or three pages with different rare page sizes. If it were possible to preset the page size would be perfect. That way, it could also be printed if needed. Thank you in advance for your help. Pablo
0
0
665
Feb ’23
import pdf from url
If I want create pdf to var dokumnetpdf from picker, var dokumnetpdf is empty. How I do that? myCode:  var dokumnetpdf = PDFDocument() func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {         guard let myURL = urls.first else {             return         }         //print("import result : (myURL)")          let url: URL = myURL         //print("PDF link:(myURL)")         pdfname = url.lastPathComponent        // print("PDF name: (pdfname)")        // textfield.text = pdfname         dokumnetpdf = PDFDocument(url: urls.first!)     } Error LoG: import result : file:///private/var/mobile/Library/Mobile%20Documents/comappleCloudDocs/Desktop/rezervacefo.pdf PDF link:file:///private/var/mobile/Library/Mobile%20Documents/comappleCloudDocs/Desktop/rezervacefo.pdf PDF name: rezervacefo.pdf doc:nil AMC/DocumentUploadViewController.swift:68: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value 2022-01-07 11:11:49.159474+0100 AMC[71388:8043348] AMC/DocumentUploadViewController.swift:68: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
4
0
3.1k
Feb ’23
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.1k
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.3k
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.3k
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
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.3k
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
3.8k
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.3k
Dec ’22
PDFKit PencilKit annotations sample code
Hello, I was wondering if the sample code shown in Session 10089 of WWDC22 could be made available? To be more specific, I am interested in overlaying a PencilKit PKCanvasView over a PDFKit PDFView. I can't seem to get the PKCanvasView to recognize touch events. This isn't really covered in the session, and I can't get it to work. I managed to overlay PKCanvasViews by copying the code from the session, but I can't draw anything because the touch events are interpreted by the PDFView as scroll gestures. Any help would be appreciated :) Thank you!
Replies
4
Boosts
1
Views
2.5k
Activity
Apr ’23
UIMarkupTextPrintFormatter crash at the time of initialisation
while initialising the UIMarkupTextPrintFormatter the app is crashing with the following error. Thread 1: EXC_BAD_ACCESS(code =1, address=0x0) sample code: let formatter = UIMarkupTextPrintFormatter(markupText: content) the parameter content is the HTML string. Tried with passing simple HTML string but still having the same crash. The Occurrence of the crash is 7/10 times and mostly when the device is offline. Issue specifically occurring in iPad OS 16.3 Attaching the screenshot for reference.
Replies
0
Boosts
0
Views
733
Activity
Apr ’23
How to add touch gesture in PDFAnnotation
Anyone Work on PDFKit, I draw a custom Annotation in PDFView, But I want to add action in Custom Annotation and I can't able to add Gesture in PDFAnnotation because it does not inherit from UIView, so is there any way to add Gesture in PDFAnnotation.
Replies
1
Boosts
0
Views
2.1k
Activity
Apr ’23
Swift PDFKit generate PDF with opaque background
I'm trying to generate a pdf with a transparent background for vector graphics and I've tried everything google has suggested, but I still keep getting a white background every time. Filling the page with clear color didn't seem to work, and I couldn't figure out how to set the background of the page. Any thoughts? func draw() -> Data { let metadata = [] let format = UIGraphicsPDFRendererFormat() format.documentInfo = metadata as [String: Any] let pageWidth = 3 * 72.0 let pageHeight = 3 * 72.0 let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight) let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format) let data = renderer.pdfData { (context) in context.beginPage() let currentContext = UIGraphicsGetCurrentContext() currentContext?.setFillColor(UIColor.clear.cgColor) currentContext?.fill(pageRect) let circlePath = UIBezierPath(arcCenter: CGPoint(x: pageWidth / 2, y: pageHeight / 2), radius: CGFloat(100), startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true) UIColor.init(cgColor: colors[0].cgColor).setFill(); UIColor.init(cgColor: colors[0].cgColor).setStroke(); circlePath.fill() circlePath.stroke() } let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { try data.write(to: URL(fileURLWithPath: "\(documentsPath)/file.pdf")) } catch { print(error) } return data }
Replies
2
Boosts
0
Views
1.8k
Activity
Apr ’23
Save/export PDF file changes page numbers
Hi everyone I have an iOS16 app that is using PDFKit to add annotations to PDFs, and I'm trying to track down an issue with some files getting corrupted when I save the annotations. As part of this testing I am looking at the original PDFs in Preview. These documents are supplied by a third-party, so are not created by us. It turns out, I have a problem simply exporting those PDFs from Preview in Monterey (12.6). When I open a PDF document in Preview and Export it using the Reduce file size Quartz filter, the page numbers are messed up and the table of contents links become incorrect (out by 1 page). The document originally had Roman numerals, I, II, III, IV, 1, 2 pages, and after exporting these page labels changed to 1, 2, 3, 4, 5, 6 This is what I am seeing in my app as well. What can I do to track down the cause, and hopefully find a solution or workaround?
Replies
1
Boosts
0
Views
608
Activity
Mar ’23
Word file to PDF with osascript
Why is this giving a super messed up PDF with no images? What am I doing wrong? use AppleScript version "2.8" use scripting additions use framework "Foundation" use framework "AppKit" -- dimensions of print area: property thePaperSize : {height:479, width:516} property theLeft : 0 property theRight : 0 property theTop : 0 property theBottom : 0 on run argv set course to "course1" set theyear to "2023" set semester to "Spring" set exam to item 1 of argv set session to item 2 of argv set chapters to item 3 of argv if semester="Spring" then set sem_num to "1" else if semester="Summer" then set sem_num to "2" else if semester="Fall" then set sem_num to "3" else return "wrong semester" end if set inpath to "/Users/Dropbox/"& course &" - " & "Current/" & theyear & "-"& sem_num &"-"& semester &"/2." & " " & "Chapter" & " " & "Reviews/" & ¬ "Exam" & " " & exam & " " & "Session" & " " & session & "/"& course &" Exam " & exam & " Session " & session & " (Ch "& chapters &").docx" -- choose Word document file, make URL and build destination path set posixPath to inpath set theURL to current application's |NSURL|'s fileURLWithPath:posixPath set destPath to theURL's |path|()'s stringByDeletingPathExtension()'s stringByAppendingPathExtension:"pdf" -- get doc's contents as styled text set {styledText, theError} to current application's NSAttributedString's alloc()'s initWithURL:theURL options:(missing value) documentAttributes:(missing val$ if styledText = missing value then error (theError's localizedDescription() as text) -- set up printing specs set printInf to current application's NSPrintInfo's sharedPrintInfo()'s |copy|() printInf's setJobDisposition:(current application's NSPrintSaveJob) printInf's dictionary()'s setObject:destPath forKey:(current application's NSPrintSavePath) -- make text view and add text set theView to current application's NSTextView's alloc()'s initWithFrame:{{0, 0}, {(width of thePaperSize) - theLeft - theRight, (height of thePaperSize) - $ theView's textStorage()'s setAttributedString:styledText -- set up and run print operation without showing dialog set theOp to current application's NSPrintOperation's printOperationWithView:theView printInfo:printInf theOp's setShowsPrintPanel:false theOp's setShowsProgressPanel:false theOp's runOperation() end run
Replies
2
Boosts
0
Views
941
Activity
Mar ’23
Exporting pdf from safari (Mac OS)
Exporting pdf from Safari is the best export tool by far, comparing all the existing ones of other browsers. Great job, Apple!! It is very useful for rendering web pages to pdf for signing documents for legal purposes. But here is the problem: Safari cannot generate page breaks in din A4 format. The pdf resulting from the export is two or three pages with different rare page sizes. If it were possible to preset the page size would be perfect. That way, it could also be printed if needed. Thank you in advance for your help. Pablo
Replies
0
Boosts
0
Views
665
Activity
Feb ’23
import pdf from url
If I want create pdf to var dokumnetpdf from picker, var dokumnetpdf is empty. How I do that? myCode:  var dokumnetpdf = PDFDocument() func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {         guard let myURL = urls.first else {             return         }         //print("import result : (myURL)")          let url: URL = myURL         //print("PDF link:(myURL)")         pdfname = url.lastPathComponent        // print("PDF name: (pdfname)")        // textfield.text = pdfname         dokumnetpdf = PDFDocument(url: urls.first!)     } Error LoG: import result : file:///private/var/mobile/Library/Mobile%20Documents/comappleCloudDocs/Desktop/rezervacefo.pdf PDF link:file:///private/var/mobile/Library/Mobile%20Documents/comappleCloudDocs/Desktop/rezervacefo.pdf PDF name: rezervacefo.pdf doc:nil AMC/DocumentUploadViewController.swift:68: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value 2022-01-07 11:11:49.159474+0100 AMC[71388:8043348] AMC/DocumentUploadViewController.swift:68: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Replies
4
Boosts
0
Views
3.1k
Activity
Feb ’23
Is there a way to programmatically extract the sections from a PDF document using Apple developer frameworks?
Is there a way to programmatically extract sections or sections of text from a PDF document using Apple frameworks? Like PDFKit or Core Graphics, CGPDFDocument? I'm able to extract pages of text or all pdf text using PDFKit but I'd like to be able to extract corresponding sections of text.
Replies
0
Boosts
0
Views
732
Activity
Feb ’23
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.1k
Activity
Feb ’23
Unable to add custom menu in PDFKit using "UIEditMenuInteraction"
I'm using PDFKit to render a PDF and I have added custom menus using "UIMenuController". But it is now deprecated from iOS 16 onwards. Any help would be really appreciated. Thanks in Advance.
Replies
1
Boosts
1
Views
1.5k
Activity
Jan ’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.3k
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.3k
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
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.3k
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
3.8k
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.3k
Activity
Dec ’22
High CPU used when zooming UIScrollView that contain PDFView inside
Hi, I have multiple single-page PDFViews attached inside UIScrollView(paging enabled). UIScrollView has a lag when zooming a PDFView. I found that PDFView has a high CPU rate of over 70%. Is that a bug from PDFView?
Replies
0
Boosts
0
Views
848
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.2k
Activity
Nov ’22
PDF Kit: - Drawing an upright stamp annotation on a rotated page
In PDFKit, while adding a stamp annotation to a rotated pdf page, the annotation also getting rotated. How we can add stamp annotation displayed upright regardless of the page rotation?
Replies
0
Boosts
0
Views
1.5k
Activity
Nov ’22