Display and manipulate PDF documents in your applications using PDFKit.

Posts under PDFKit tag

200 Posts

Post

Replies

Boosts

Views

Activity

How to modify default context menu of PDFKit with SwiftUI
I am creating an app for iOS and iPadOS using PDFKit based on SwiftUI and have a problem that I cannot solve. In the current app, when viewing a PDF, I select a sentence by dragging it, press and hold, and a context menu with several processing commands is displayed. This context menu is not prepared by me, but it is the default context menu that comes with PDFKit. Some of them are not suitable for my application and I want to hide them. I have searched a lot about the settings and it seems to use UIContextMenuInteraction, UIEditMenuInteraction and their delegate, canperformaction and so on. However, there is no official information on how to use them in swiftui, and when I try to implement them myself, they don't work as expected. If anyone knows how to modify the context menu provided by default when using PDFKit with SwiftUI, please let me know.
0
0
955
Jun ’23
PDFKit + SwiftUI
Hello and thanks for reading my post. I have been trying hard to generate a PDF from a SwiftUI view on a button press. Looked at the PDFKit documentation, understood that PDFView, PDFDocument and PDFPage are important classes. However, I couldn't find any examples of how to use them in SwiftUI or Swift. Basically, given a SwiftUI view (or a Swift struct), how to create a new SwiftUI view that displays the generated PDF? The pdf can contain charts, layouts, etc.
1
0
1.8k
Jun ’23
How to export a View in multiple A4 PDF pages?
I have been trying to find a way to export a View in SWIFTUI in A4 size pages PDF. The view cannot fit in one single page. So far I have managed to edit (with the help of ChatGPT) the code found in PDF Creator GitHub (See below) But although I get multiple page PDF as a result only the first page is populated, the rest are just blank. Does anyone faced something similar before, if yes how did you manage to export to PDF in A4 pages... Thanks for any tips and help! 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 whenever it's generated let outputFileURL = documentDirectory.appendingPathComponent("\(fileName)\(UUID().uuidString).pdf") // MARK: PDF View let scrollView = convertToScrollView { content() } scrollView.tag = 1009 scrollView.frame = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4 size in points (72 points per inch) let pageSize = scrollView.frame.size let contentSize = scrollView.contentSize let pageCount = Int(ceil(contentSize.height / pageSize.height)) // Create PDF Context UIGraphicsBeginPDFContextToFile(outputFileURL.path, .zero, nil) // CHATGPT: for index in 0..<pageCount { // Begin new PDF page UIGraphicsBeginPDFPageWithInfo(CGRect(origin: .zero, size: pageSize), nil) // Calculate the visible frame for each page let visibleFrame = CGRect(x: 0, y: -pageSize.height * CGFloat(index), width: pageSize.width, height: pageSize.height) // Capture the screenshot of the visible content synchronously scrollView.clipToRect(visibleFrame) { // Take a screenshot of the visible content let screenshot = scrollView.takeScreenshot() // Draw the screenshot into the PDF context screenshot.draw(at: .zero) } } completion(true, outputFileURL) // End PDF Context UIGraphicsEndPDFContext() completion(true, outputFileURL) // 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 } } extension UIView { func takeScreenshot() -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale) drawHierarchy(in: bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image ?? UIImage() } func clipToRect(_ rect: CGRect, perform: () -> Void) { guard let context = UIGraphicsGetCurrentContext() else { return } context.saveGState() context.clip(to: rect) perform() context.restoreGState() } }
1
1
1.4k
Jun ’23
PDF Page external links ( hyperlink) are not working after rendering PDF content to UIView in Swift iOS
The pdf that has external weblink on the first page for accessing they youtube. When i open it pdf of reader or other apps it will be asked open the youtube. I want to support that functionality in UIView level. I copied PDF content to UIView successfully and but cannot see any action, once i click the external web link. Here is the my code steps: Storing pdf file in project level (Doc.pdf) Take the first page and convert that page to Data. (During the practical scenario, i need to store that value as Data first, it will be needed reuse later, So cannot use PDFPage object for processing directly.). Binding Data object with CanvasView and override the CanvasView draw method for copying pdf data to UIView. (During practical scenario, I can't use PDFView object, I have to use custom UIView and it will be needed support other customize operation (ex: erasing, cut, copy etc) Finally, even though all contents are copied successfully, i cannot see any action, once i clicked the external web link. Here is the code example: ViewController.Swift import PDFKit class ViewController: UIViewController { var pdfDocument: PDFDocument? override func loadView() { super.loadView() } func getData(pdfPage: PDFPage) -> Data { let cropBox = pdfPage.bounds(for: .cropBox) var adjustedCropBox = cropBox if ((pdfPage.rotation == 90) || (pdfPage.rotation == 270) || (pdfPage.rotation == -90)) { adjustedCropBox.size = CGSize(width: cropBox.height, height: cropBox.width) } let renderer = UIGraphicsPDFRenderer(bounds: adjustedCropBox) return renderer.pdfData { (ctx) in ctx.beginPage() ctx.cgContext.setFillColor(UIColor.white.cgColor) ctx.fill(adjustedCropBox) pdfPage.transform(ctx.cgContext, for: .cropBox) switch pdfPage.rotation { case 0: ctx.cgContext.translateBy(x: 0, y: adjustedCropBox.height) ctx.cgContext.scaleBy(x: 1, y: -1) case 90: ctx.cgContext.scaleBy(x: 1, y: -1) ctx.cgContext.rotate(by: -.pi / 2) case 180, -180: ctx.cgContext.scaleBy(x: 1, y: -1) ctx.cgContext.translateBy(x: adjustedCropBox.width, y: 0) ctx.cgContext.rotate(by: .pi) case 270, -90: ctx.cgContext.translateBy(x: adjustedCropBox.height, y: adjustedCropBox.width) ctx.cgContext.rotate(by: .pi / 2) ctx.cgContext.scaleBy(x: -1, y: 1) default: break } pdfPage.draw(with: .cropBox, to: ctx.cgContext) } } override func viewDidLoad() { super.viewDidLoad() let fileUrl = Bundle.main.url(forResource: "Doc", withExtension: "pdf") guard let fileUrl else { return } pdfDocument = PDFDocument(url: fileUrl) let firstPage: PDFPage? = pdfDocument?.page(at: 0) print("first page annotation count \(firstPage?.annotations.count)") guard let firstPage else { return } let pdfData = getData(pdfPage: firstPage) let canvasView = CanvasView(data: pdfData) self.view.addSubview(canvasView) NSLayoutConstraint.activate([ canvasView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor), canvasView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 0), canvasView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor), canvasView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: 0) ]) } } CanvasView.Swift import PDFKit class CanvasView: UIView { var page: PDFPage? init(data: Data) { super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false page = loadPDFPage(pdfData: data) } init(pdfPage: PDFPage){ super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false page = pdfPage } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func loadPDFPage(pdfData: Data) -> PDFPage? { guard let document = PDFDocument(data: pdfData) else { return nil } return document.page(at: 0) } override func draw(_ layer: CALayer, in ctx: CGContext) { guard let page else { return } print("num of annotations - \(page.annotations.count)") if let cgPDFPage = page.pageRef { let cropBoxBounds = page.bounds(for: .cropBox) print(page.displaysAnnotations) let scaleX = layer.bounds.width / cropBoxBounds.width let scaleY = layer.bounds.height / cropBoxBounds.height ctx.saveGState() ctx.scaleBy(x: scaleX, y: scaleY) ctx.translateBy(x: -cropBoxBounds.origin.x, y: cropBoxBounds.height + cropBoxBounds.origin.y ) ctx.scaleBy(x: 1, y: -1) ctx.setFillColor(UIColor.white.cgColor) ctx.fill(cropBoxBounds) ctx.drawPDFPage(cgPDFPage) ctx.restoreGState() } } override func draw(_ rect: CGRect) {} } Here the project Special Note: Once i loaded PDFPage from url, it has two link annotations. Once i created PDFPage from Data in CavansView, i cannot see any PDF annotations and it is empty. So I assume, during data conversion process, annotations will not be considered. even though i pass original PDFPage object directly instead of Data, link click actions are not worked. So i need to someone help from how we send PDFAnnotation object data to Data object and How we can support web link behaviour as we expected. Please, help me to resolve this case and i really appreciate your feedback and help.
0
1
1.1k
Jun ’23
Using swift or other tool to tell if printer is connected and ready for prints
I am using SwiftUI to build a macOS app. I have to print papers and I'm trying to see if I'm actively connected to a printer. I have a default printer set as you can see in the below image but it's currently offline. My issue is the code I have returns true that I am connected to a printer because I have a saved printer device. Is there a way to check if the printer is offline even when I'm connected? In the image it says the printer is offline and I need to know how to get that. Code I'm currently using that returns true: func isConnectedToPrinter() -> Bool { let printers = NSPrinter.printerNames return !printers.isEmpty } This returns true because the printer is still remembered by my mac even though its Offline(powered down). Any idea on how mac OS can determine the printer is "Offline"? Also here is my current code to print the pdfDocument, Is there anything I can add here to help? private func printPDFDocument(forDoc document: PDFDocument) { let printInfo = NSPrintInfo.shared printInfo.horizontalPagination = .fit printInfo.verticalPagination = .fit printInfo.orientation = .portrait printInfo.topMargin = 0 printInfo.bottomMargin = 0 printInfo.leftMargin = 0 printInfo.rightMargin = 0 printInfo.isHorizontallyCentered = true printInfo.isVerticallyCentered = true let scale: PDFPrintScalingMode = .pageScaleDownToFit let printOp = document.printOperation(for: printInfo, scalingMode: scale, autoRotate: true) DispatchQueue.main.async { let result = printOp?.run() self.showLoadingText = false } }
1
1
1.4k
May ’23
iOS 16 PDF form jump to top
We build an iOS App that uses PDFView to show PDF's with annotations so the user can enter information in textfields or select checkboxes and fill out the PDF form that is than send by email. The PDF is bigger than the screen size so we need to scroll in the PDF to select the textfields. In iOS 15 and before we didn't had any problems but since we updated to iOS 16 we have the problem that the when a textfield is selected for editing or when the user stops editing by hitting the enter key the PDFViewer jumps to the top of the PDF. I also noticed that when we open the PDF everything looks fine and the PDF fits inside the PDFView. When this jumping to top has occurred we get a white section under the PDF inside the PDFView. It is as if the size from the PDF inside the PDFView is broken. Does any of you have the same Problem or is it a known problem? Is there a workaround to fix this? I couldn't find the issue tracker for PDFKit to check it myself.
0
0
835
May ’23
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.6k
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
803
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.9k
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
701
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
1.1k
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
733
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.2k
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.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.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
2.1k
Dec ’22
How to modify default context menu of PDFKit with SwiftUI
I am creating an app for iOS and iPadOS using PDFKit based on SwiftUI and have a problem that I cannot solve. In the current app, when viewing a PDF, I select a sentence by dragging it, press and hold, and a context menu with several processing commands is displayed. This context menu is not prepared by me, but it is the default context menu that comes with PDFKit. Some of them are not suitable for my application and I want to hide them. I have searched a lot about the settings and it seems to use UIContextMenuInteraction, UIEditMenuInteraction and their delegate, canperformaction and so on. However, there is no official information on how to use them in swiftui, and when I try to implement them myself, they don't work as expected. If anyone knows how to modify the context menu provided by default when using PDFKit with SwiftUI, please let me know.
Replies
0
Boosts
0
Views
955
Activity
Jun ’23
PDFKit + SwiftUI
Hello and thanks for reading my post. I have been trying hard to generate a PDF from a SwiftUI view on a button press. Looked at the PDFKit documentation, understood that PDFView, PDFDocument and PDFPage are important classes. However, I couldn't find any examples of how to use them in SwiftUI or Swift. Basically, given a SwiftUI view (or a Swift struct), how to create a new SwiftUI view that displays the generated PDF? The pdf can contain charts, layouts, etc.
Replies
1
Boosts
0
Views
1.8k
Activity
Jun ’23
How to export a View in multiple A4 PDF pages?
I have been trying to find a way to export a View in SWIFTUI in A4 size pages PDF. The view cannot fit in one single page. So far I have managed to edit (with the help of ChatGPT) the code found in PDF Creator GitHub (See below) But although I get multiple page PDF as a result only the first page is populated, the rest are just blank. Does anyone faced something similar before, if yes how did you manage to export to PDF in A4 pages... Thanks for any tips and help! 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 whenever it's generated let outputFileURL = documentDirectory.appendingPathComponent("\(fileName)\(UUID().uuidString).pdf") // MARK: PDF View let scrollView = convertToScrollView { content() } scrollView.tag = 1009 scrollView.frame = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4 size in points (72 points per inch) let pageSize = scrollView.frame.size let contentSize = scrollView.contentSize let pageCount = Int(ceil(contentSize.height / pageSize.height)) // Create PDF Context UIGraphicsBeginPDFContextToFile(outputFileURL.path, .zero, nil) // CHATGPT: for index in 0..<pageCount { // Begin new PDF page UIGraphicsBeginPDFPageWithInfo(CGRect(origin: .zero, size: pageSize), nil) // Calculate the visible frame for each page let visibleFrame = CGRect(x: 0, y: -pageSize.height * CGFloat(index), width: pageSize.width, height: pageSize.height) // Capture the screenshot of the visible content synchronously scrollView.clipToRect(visibleFrame) { // Take a screenshot of the visible content let screenshot = scrollView.takeScreenshot() // Draw the screenshot into the PDF context screenshot.draw(at: .zero) } } completion(true, outputFileURL) // End PDF Context UIGraphicsEndPDFContext() completion(true, outputFileURL) // 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 } } extension UIView { func takeScreenshot() -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale) drawHierarchy(in: bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image ?? UIImage() } func clipToRect(_ rect: CGRect, perform: () -> Void) { guard let context = UIGraphicsGetCurrentContext() else { return } context.saveGState() context.clip(to: rect) perform() context.restoreGState() } }
Replies
1
Boosts
1
Views
1.4k
Activity
Jun ’23
PDF Page external links ( hyperlink) are not working after rendering PDF content to UIView in Swift iOS
The pdf that has external weblink on the first page for accessing they youtube. When i open it pdf of reader or other apps it will be asked open the youtube. I want to support that functionality in UIView level. I copied PDF content to UIView successfully and but cannot see any action, once i click the external web link. Here is the my code steps: Storing pdf file in project level (Doc.pdf) Take the first page and convert that page to Data. (During the practical scenario, i need to store that value as Data first, it will be needed reuse later, So cannot use PDFPage object for processing directly.). Binding Data object with CanvasView and override the CanvasView draw method for copying pdf data to UIView. (During practical scenario, I can't use PDFView object, I have to use custom UIView and it will be needed support other customize operation (ex: erasing, cut, copy etc) Finally, even though all contents are copied successfully, i cannot see any action, once i clicked the external web link. Here is the code example: ViewController.Swift import PDFKit class ViewController: UIViewController { var pdfDocument: PDFDocument? override func loadView() { super.loadView() } func getData(pdfPage: PDFPage) -> Data { let cropBox = pdfPage.bounds(for: .cropBox) var adjustedCropBox = cropBox if ((pdfPage.rotation == 90) || (pdfPage.rotation == 270) || (pdfPage.rotation == -90)) { adjustedCropBox.size = CGSize(width: cropBox.height, height: cropBox.width) } let renderer = UIGraphicsPDFRenderer(bounds: adjustedCropBox) return renderer.pdfData { (ctx) in ctx.beginPage() ctx.cgContext.setFillColor(UIColor.white.cgColor) ctx.fill(adjustedCropBox) pdfPage.transform(ctx.cgContext, for: .cropBox) switch pdfPage.rotation { case 0: ctx.cgContext.translateBy(x: 0, y: adjustedCropBox.height) ctx.cgContext.scaleBy(x: 1, y: -1) case 90: ctx.cgContext.scaleBy(x: 1, y: -1) ctx.cgContext.rotate(by: -.pi / 2) case 180, -180: ctx.cgContext.scaleBy(x: 1, y: -1) ctx.cgContext.translateBy(x: adjustedCropBox.width, y: 0) ctx.cgContext.rotate(by: .pi) case 270, -90: ctx.cgContext.translateBy(x: adjustedCropBox.height, y: adjustedCropBox.width) ctx.cgContext.rotate(by: .pi / 2) ctx.cgContext.scaleBy(x: -1, y: 1) default: break } pdfPage.draw(with: .cropBox, to: ctx.cgContext) } } override func viewDidLoad() { super.viewDidLoad() let fileUrl = Bundle.main.url(forResource: "Doc", withExtension: "pdf") guard let fileUrl else { return } pdfDocument = PDFDocument(url: fileUrl) let firstPage: PDFPage? = pdfDocument?.page(at: 0) print("first page annotation count \(firstPage?.annotations.count)") guard let firstPage else { return } let pdfData = getData(pdfPage: firstPage) let canvasView = CanvasView(data: pdfData) self.view.addSubview(canvasView) NSLayoutConstraint.activate([ canvasView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor), canvasView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 0), canvasView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor), canvasView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: 0) ]) } } CanvasView.Swift import PDFKit class CanvasView: UIView { var page: PDFPage? init(data: Data) { super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false page = loadPDFPage(pdfData: data) } init(pdfPage: PDFPage){ super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false page = pdfPage } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func loadPDFPage(pdfData: Data) -> PDFPage? { guard let document = PDFDocument(data: pdfData) else { return nil } return document.page(at: 0) } override func draw(_ layer: CALayer, in ctx: CGContext) { guard let page else { return } print("num of annotations - \(page.annotations.count)") if let cgPDFPage = page.pageRef { let cropBoxBounds = page.bounds(for: .cropBox) print(page.displaysAnnotations) let scaleX = layer.bounds.width / cropBoxBounds.width let scaleY = layer.bounds.height / cropBoxBounds.height ctx.saveGState() ctx.scaleBy(x: scaleX, y: scaleY) ctx.translateBy(x: -cropBoxBounds.origin.x, y: cropBoxBounds.height + cropBoxBounds.origin.y ) ctx.scaleBy(x: 1, y: -1) ctx.setFillColor(UIColor.white.cgColor) ctx.fill(cropBoxBounds) ctx.drawPDFPage(cgPDFPage) ctx.restoreGState() } } override func draw(_ rect: CGRect) {} } Here the project Special Note: Once i loaded PDFPage from url, it has two link annotations. Once i created PDFPage from Data in CavansView, i cannot see any PDF annotations and it is empty. So I assume, during data conversion process, annotations will not be considered. even though i pass original PDFPage object directly instead of Data, link click actions are not worked. So i need to someone help from how we send PDFAnnotation object data to Data object and How we can support web link behaviour as we expected. Please, help me to resolve this case and i really appreciate your feedback and help.
Replies
0
Boosts
1
Views
1.1k
Activity
Jun ’23
Using swift or other tool to tell if printer is connected and ready for prints
I am using SwiftUI to build a macOS app. I have to print papers and I'm trying to see if I'm actively connected to a printer. I have a default printer set as you can see in the below image but it's currently offline. My issue is the code I have returns true that I am connected to a printer because I have a saved printer device. Is there a way to check if the printer is offline even when I'm connected? In the image it says the printer is offline and I need to know how to get that. Code I'm currently using that returns true: func isConnectedToPrinter() -> Bool { let printers = NSPrinter.printerNames return !printers.isEmpty } This returns true because the printer is still remembered by my mac even though its Offline(powered down). Any idea on how mac OS can determine the printer is "Offline"? Also here is my current code to print the pdfDocument, Is there anything I can add here to help? private func printPDFDocument(forDoc document: PDFDocument) { let printInfo = NSPrintInfo.shared printInfo.horizontalPagination = .fit printInfo.verticalPagination = .fit printInfo.orientation = .portrait printInfo.topMargin = 0 printInfo.bottomMargin = 0 printInfo.leftMargin = 0 printInfo.rightMargin = 0 printInfo.isHorizontallyCentered = true printInfo.isVerticallyCentered = true let scale: PDFPrintScalingMode = .pageScaleDownToFit let printOp = document.printOperation(for: printInfo, scalingMode: scale, autoRotate: true) DispatchQueue.main.async { let result = printOp?.run() self.showLoadingText = false } }
Replies
1
Boosts
1
Views
1.4k
Activity
May ’23
iOS 16 PDF form jump to top
We build an iOS App that uses PDFView to show PDF's with annotations so the user can enter information in textfields or select checkboxes and fill out the PDF form that is than send by email. The PDF is bigger than the screen size so we need to scroll in the PDF to select the textfields. In iOS 15 and before we didn't had any problems but since we updated to iOS 16 we have the problem that the when a textfield is selected for editing or when the user stops editing by hitting the enter key the PDFViewer jumps to the top of the PDF. I also noticed that when we open the PDF everything looks fine and the PDF fits inside the PDFView. When this jumping to top has occurred we get a white section under the PDF inside the PDFView. It is as if the size from the PDF inside the PDFView is broken. Does any of you have the same Problem or is it a known problem? Is there a workaround to fix this? I couldn't find the issue tracker for PDFKit to check it myself.
Replies
0
Boosts
0
Views
835
Activity
May ’23
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.6k
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
803
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.2k
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.9k
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
701
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
1.1k
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
733
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.2k
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
851
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.2k
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.6k
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.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.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
2.1k
Activity
Dec ’22