Display and manipulate PDF documents in your applications using PDFKit.

Posts under PDFKit tag

200 Posts

Post

Replies

Boosts

Views

Activity

PDFKit create document version is 1.3 can we create an PDF 1.7 document?
Working with PDFkit on MacOS 12.6 and created a new PDFDocument instance. checking the HEX code of this PDF document and notice this, At the beginning there is "%PDF-1.3%". Is it possible to create a new PDFDocument in PDF Spec 1.7 version instead? if not possible with current version, any plan in the future? is there a plan to have equivalence of PDFKit in SWIFTUI world around the corner? thanks
0
0
1.2k
Oct ’22
redact functionality absent in PDFKit
Prior to macOS 10.12, text markup annotations were configured through the PDFAnnotationMarkup class (see here). An annotation of this type could be configured to use the redact, underline, strikeOut, or highlight enumerations. However, this has since been deprecated in favor of creating a PDFAnnotation with the PDFAnnotationSubtype structure. Subtypes exist for underline, highlight, and strikeOut, but no option for redact exists. What is the proper way to create a redaction annotation in the current API?
1
1
743
Oct ’22
Error exporting a PDF
I am trying to build an app that allows users to share their lists to other. To do this I am trying to capture the list as an image and turn it into a PDF. When I send the PDF it comes with a white screen. Is there a way to fix this? Is there somethings wrong with this code? struct ShareSheet {       static let instance = ShareSheet()       private init() { }       func share(items: [Any]) {     let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)     UIApplication.shared.currentUIWindow()?.rootViewController?.present(controller, animated: true, completion: nil)   }     } public extension UIApplication {   func currentUIWindow() -> UIWindow? {     let connectedScenes = UIApplication.shared.connectedScenes       .filter({         $0.activationState == .foregroundActive})       .compactMap({$0 as? UIWindowScene})           let window = connectedScenes.first?       .windows       .first { $0.isKeyWindow }     return window         } } extension View{       func sharePDF<Content: View> (@ViewBuilder content: @escaping () -> Content, fileName: String) {     exportPDF(content: content, completion: { status , url in       if let url = url, status {         ShareSheet.instance.share(items: [url])       } else {         print("⚠️ Failed to make PDF")       }     }, fileName: fileName)   }       // MARK: Extracting View's Height and width with the Help of Hosting Controller and ScrollView   fileprivate func convertToScrollView<Content: View>(@ViewBuilder content: @escaping ()->Content)->UIScrollView{           let scrollView = UIScrollView()           // MARK: Converting SwiftUI View to UIKit View     let hostingController = UIHostingController(rootView: content()).view!     hostingController.translatesAutoresizingMaskIntoConstraints = false           // MARK: Constraints     let constraints = [             hostingController.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),       hostingController.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),       hostingController.topAnchor.constraint(equalTo: scrollView.topAnchor),       hostingController.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),               // Width Anchor       hostingController.widthAnchor.constraint(equalToConstant: screenBounds().width)     ]     scrollView.addSubview(hostingController)     scrollView.addConstraints(constraints)     scrollView.layoutIfNeeded()           return scrollView   }       // MARK: Export to PDF   // MARK: Completion Handler will Send Status and URL   fileprivate func exportPDF<Content: View>(@ViewBuilder content: @escaping ()->Content,completion: @escaping (Bool,URL?)->(), fileName: String){           // MARK: Temp URL     let documentDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!     // MARK: To Generate New File when ever its generated     let outputFileURL = documentDirectory.appendingPathComponent("\(fileName)\(UUID().uuidString).pdf")           // MARK: PDF View     let pdfView = convertToScrollView {       content()     }     pdfView.tag = 1009     let size = pdfView.contentSize     // Removing Safe Area Top Value     pdfView.frame = CGRect(x: 0, y: getSafeArea().top, width: size.width, height: size.height)           // MARK: Attaching to Root View and rendering the PDF     getRootController().view.insertSubview(pdfView, at: 0)           // MARK: Rendering PDF     let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height))           do{               try renderer.writePDF(to: outputFileURL, withActions: { context in                   context.beginPage()         pdfView.layer.render(in: context.cgContext)       })               completion(true,outputFileURL)     }     catch{       completion(false,nil)       print(error.localizedDescription)     }           // Removing the added View     getRootController().view.subviews.forEach { view in       if view.tag == 1009{         print("Removed")         view.removeFromSuperview()       }     }   }       fileprivate func screenBounds()->CGRect{     return UIScreen.main.bounds   }       fileprivate func getRootController()->UIViewController{     guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{       return .init()     }           guard let root = screen.windows.first?.rootViewController else{       return .init()     }           return root   }       fileprivate func getSafeArea()->UIEdgeInsets{     guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{       return .zero     }           guard let safeArea = screen.windows.first?.safeAreaInsets else{       return .zero     }           return safeArea   } }
1
0
1k
Oct ’22
PDF Annotation for file from AWS S3 bucket
We have application where our cloud storage is on AWS S3 bucket and want to use annotation feature on PDF through my iOS application. iOS application is coded in language native language can anyone please provide necessary documents to implement this yeah. Where I can access files from AWS S3 bucket and do annotation on my PDF file through iOS application
0
0
612
Sep ’22
PDFKit setBounds to trimBox doesn't work as expected in iOS16
Hi, I found the setBounds:forBox: function doesn't set the bounds of trimBox as expected in iOS16. On iOS15.6, when the setBounds is called and page is larger than the specified bounds, the page will shrink and resize to fit inside the specified bounds; but on iOS16, it doesn't do anything. From the debugger I can tell that the trimBox bounds is indeed set to the specified size, but I'm not sure what underlying logic is broken. Has anyone seen similar issues in iOS16?
0
0
713
Sep ’22
Accessibility of PDF on Apple platforms in 2022 and beyond
I'm finding it extremely difficult to find accurate and up-to-date information about support for accessibility with PDF on Apple's platforms, in particular Safari and Preview on iOS and Mac. For a long time it seemed that nothing worked (e.g. browsing a PDF with VoiceOver in Preview), but I've started to get some acceptable, but patchy results. Apparently things have changed under the hood since the extensive outcry at High Sierra's implementation of PDFKit but what exactly has changed? Is there a change log anywhere? Did any of the notorious PDFKit bugs from 2017 get fixed? I will mention some important jargon used in the accessibility community: "Accessibility supported". This term has a formal definition in the WCAG spec. Basically it's not enough that a file format (such as PDF) or an app (such as Safari) is hypothetically accessible, if I can't actually browse my PDF in Safari using Voiceover. Legally speaking, this information should be absolutely clear in the VPAT for Mac OS. It isn't. Lawyers with an interest in accessibility suits should take note. My questions: I've studied the latest documentation for PDFKit and can find no mention of semantic tagging, read order or the PDF/UA format in general. How does this work? Did Apple invent new names for these features, or is it simply unsupported? Can I use VoiceOver to browse a well-formed tagged PDF/UA file 'semantically' in Safari? (E.g. 'next heading' keyboard shortcut, or using the rotor). If I save a PDF from Safari or Preview, do I get a well-formed 'accessible PDF' (i.e. a "tagged PDF" file with the PDF/UA flag)? How might HTML semantics be mapped onto PDF/UA output, when saving a web page as PDF from Safari, given that there is not 100% parity between the two semantic systems? Can I browse PDF/UA files in Acrobat Reader with VoiceOver? If not, why aren't Apple and Adobe taking steps to fix this situation? I understand that Pages, Numbers and Keynote all produce tagged PDF. I assume this means some conformance with the PDF/UA 1.7 spec? Are there any omissions in support for the PDF/UA standard by this route? What are those omissions? Regarding the accessibility of the output, is there any difference between "Save as PDF", "Export PDF" and "Print to PDF" in Apple's software? Please advise on any of these points.
0
1
1.5k
Sep ’22
WKWebView: loadHTMLString and createPDF always fails since updating to macOS Monterey
Hello, I had programmed and used a software for a year without problems but after updating to Monterey and updating XCode, the following, simplified Playground example of the process always fails and I cannot figure out why. Please note this project is specifically written for macOS and I cannot use the iOS libraries for PDF generation. import WebKit import PDFKit import SwiftUI import CoreGraphics let webView: WKWebView = WKWebView(frame: CGRect(x: 0, y: 0, width: 595.0, height: 842.0), configuration: WKWebViewConfiguration()) let htmlString = "<html><body><h1>Hello</h1></body></html>" webView.loadHTMLString(htmlString, baseURL: nil) webView.createPDF(completionHandler: compHandler) func compHandler(res: Result<Data, Error>) -> Void { print(res) } This always results in an error: failure(Error Domain=WKErrorDomain Code=1 "An unknown error occurred" UserInfo={NSLocalizedDescription=An unknown error occurred}) I cannot find anything in the documentation regarding this and most examples and questions are old and not applicable (many still using Objective-C). Debugging seems to suggest that the loadHTMLString itself fails, not even necessarily the PDF itself. Any pointers would be appreciated. Thanks
0
0
1.2k
Sep ’22
Highlighter Annotation Large Frame
I am using PDFKit to draw annotation over PDF view. While performing multiple highlighter annotation most of the time long pressing on the highlighter annotation is getting proper frame but in one PDF when long pressing on the highlighter annotation is getting large frame and it is selecting all the nearest highlighter. This method is giving the wrong location and this is the default method of PDFKit. let tapPageLocation = pdfView.convert(location, to: page)
0
0
1.5k
Aug ’22
How to create and store the pdf file
I'm using CGContext.init(withUrl) to create a pdf context and doing some rendering inside that context. I was able to save the pdf in the location which will be available in the url. But in my case i will not have a location while creating the CGContext. So in my case i need a create a CGPDFContext without the location. I tried using the CGDataConsumer, but that also not working. My Requirements 1. Have to create PDF file without the save location. 2. In certain time interval i have to save that pdf to the particular location
3
0
3.6k
Aug ’22
Enable Live Text on PDFKit
Hi! I watched WWDC2022's 10089 session "What's New in PDFKit?" where it's said that Live Text is now compatible with PDFKit. However, I can't seem to find anything related to it in documentation or code. ImageAnalyzer needs an UIImage to work. But that would mean retrieve the current PDFPage and then convert it to UIImage which is a performance hog. How can I enable Live Text in PDFKit? thanks.
1
0
1.7k
Aug ’22
Multipage PDF with PDFKit on macOS with swift
Hello everybody, After weeks and months of searching for a solution (with interruptions) I finally have to ask the question: is there a tutorial to generate PDF with multiple pages from a macOS app with swift / swiftui? I am programming a macOS app and want (must) save and print letters and other documents as PDFs at the touch of a button. All the examples that I have been able to find so far are only for iOS and simply turning "UIGraphicsPDFRenderer" into "NSGraphicsPDFRenderer" is not possible. It can't be that no PDF can be created under macOS. It has to work somehow, doesn't it? Alternatively, it would be enough for me if you could print a view from SwiftUI. But that doesn't seem to work that easily, too. I would be very grateful for your help.
1
0
1.9k
Aug ’22
Error loading a file from Firebase
Hi all, I have been facing a problem while loading a file from the firebase storage. Basically in my code i have a data model which is the file/document (pdf in this case), a manager which goes into the database of Firebase to fetch the object and finally two views, one to list the files fetched and another one to show the document. I can fetch all the documents with their specific data, pass them to my view and then show the document pdf in another view. Everything seems correct but the problem comes when opening one of this docs. First, the doc doesn't open at first so you need to close the view and try to open the doc again. Then when i want to open another doc from my list, when i click on it the previous document is shown and not the correct one, so i need to do the same, close the view and click again on the doc to open the correct one. So at the end what i'm looking for is to open the doc just clicking once but i don't know where is my problem. List of docs: 1st time: 2nd time: 2nd doc but 1st time: 2nd doc and 2nd time clicking on it: Here is my code Model: struct DocumentoPdf {     let titulo: String     let docUrl: URL?     let id: String     let storageUrl: String } Manager which fetches the documents from firebase: final class DatabaseManager { [...]     public func getNovedades(completion: @escaping ([DocumentoPdf]) -> Void) {         database.collection("novedades").getDocuments { snapshot, error in             guard let documents = snapshot?.documents.compactMap ({ $0.data() }), error == nil else {                 return             }             let novedades: [DocumentoPdf] = documents.compactMap({ dictionary in                 guard let id = dictionary["id"] as? String,                       let titulo = dictionary["titulo"] as? String,                       let docUrlString = dictionary["docUrl"] as? String,                       let storageUrl = dictionary["storageUrl"] as? String else {                           return nil                       }                 let novedad = DocumentoPdf(titulo: titulo,                                            docUrl: URL(string: docUrlString),                                            id: id,                                            storageUrl: storageUrl)                 return novedad             })             completion(novedades)         }     } } First View: class NovedadesViewControllerViewModel {     let docUrl: URL?     var docData: Data?     init(docUrl: URL?) {         self.docUrl = docUrl     } } class NovedadesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PDFViewDelegate {     private var tableView =  UITableView()    private var doc = PDFDocument()     public func configureDocPdf(with viewModel: NovedadesViewControllerViewModel) {         if let data = viewModel.docData {             doc = PDFDocument(data: data)!         }         else if let url = viewModel.docUrl {             // fetch doc & cache             let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in                 guard let data = data else {                     return                 }                 viewModel.docData = data                 DispatchQueue.main.async {                     self?.doc = PDFDocument(data: data)!                 }             }             task.resume()         }     }     private var novedades: [DocumentoPdf] = []     private func obtenerNovedades() {         DatabaseManager.shared.getNovedades() { [weak self] novedades in             self?.novedades = novedades             DispatchQueue.main.async {                 self?.tableView.reloadData()             }         }     }     override func viewDidLoad() { [...]         obtenerNovedades() [...]     } [... sections, rows in section...]     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {         let novedad = novedades[indexPath.row]         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)         cell.textLabel?.text = novedad.titulo         return cell     }     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {         let novedad = novedades[indexPath.row]         switch indexPath.section {         case 0:             configureDocPdf(with: .init(docUrl: novedad.docUrl))             let lectorPdfView = LectorPdfViewController(doc: self.doc, nameDoc: novedad.titulo)             self.present(lectorPdfView, animated: true, completion: nil)         default:             break         }     } } Second View to load the pdf: class LectorPdfViewController: UIViewController, PDFViewDelegate {     private let navBar = UINavigationBar()     private let pdf = PDFView()     let nameDoc: String     let doc: PDFDocument     init(doc: PDFDocument, nameDoc: String) {         self.doc = doc         self.nameDoc = nameDoc         super.init(nibName: nil, bundle: nil)     }     required init?(coder: NSCoder) {         fatalError()     }     override func viewDidLoad() {         super.viewDidLoad()         view.backgroundColor = .systemBackground         view.addSubview(navBar)         view.addSubview(pdf)         pdf.document = self.doc         pdf.delegate = self         let item = UINavigationItem(title: self.nameDoc)         navBar.setItems([item], animated: false)         navBar.barTintColor = .systemBackground     }     override func viewDidLayoutSubviews() {         navBar.frame = CGRect(x: 0,                               y: 0,                               width: view.frame.size.width,                               height: 50)         pdf.frame = CGRect(x: 0,                            y: navBar.frame.height,                            width: view.frame.size.width,                            height: view.frame.size.height - navBar.frame.height)     } } Please if someone can help me with this will be fantastic. I hope you understood my code and my problem. Sorry for my bad english Thank you so much in advance
4
1
1.9k
Aug ’22
PDFKit Link Annotations gets stripped off when saving
I'm using the following code to draw a text over PDF page.Everything works fine, but if you process a PDF with internal links eg: a Book with Content links to pages, the resultant PDF file seems to have the links stripped off.Why does this happen? let data = NSMutableData() let consumer = CGDataConsumer(data: data as CFMutableData)! let context = CGContext(consumer: consumer, mediaBox: nil, nil)! let pdffile=PDFDocument(url: input) for y in stride(from: 0, to: pagecount, by: 1) { let page: PDFPage = pdffile!.page(at: y)! var mediaBox = page.bounds(for: PDFDisplayBox.mediaBox) NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false) let bounds = page.bounds(for: PDFDisplayBox.mediaBox) let size = bounds.size page.draw(with: .mediaBox, to: context) text.draw(in:drawrect,withAttributes:textFontAttributes); context.endPDFPage() } context.closePDF() try! data!.write(to: GetOutputFileName(inputfile: x), options[.atomicWrite]) What I have tried is saving the annotation of each page applying it before ending the page for annotation in pageannottaions                 {                     page.addAnnotation(annotation)                 } This also does not work.Please advice
0
0
676
Aug ’22
Export MacOS SwiftUI form to pdf
I am building a MacOS dedicated app where I want to build a document template using a form. Inside the form there are multiple data types: text, pickers, images, links to other pdfs and signatures. I want to be able to export the data in the form to pdf, retaining the formatting of the form. I have searched high and low for some sort of solution, where PDFKit and Quartz seem to come up but no viable solution. This really should not be a complex process... And I do not want to use storyboard but only use SwiftUI.
1
0
710
Aug ’22
Upside down drawings on iOS 16 preview
We are currently testing our mobile application on the iOS 16 preview. Our application allows you to draw and sign using the UIKit/PDFKit which results in an image that we store. When the image is opened it is displayed upside down. Is this an expected change caused by the new OS or is this a bug that will be fixed when the stable version is released? Is there any guide/advice on this if this is an expected change?
2
0
987
Jul ’22
PDFKit & WebKit problem with JPEG2000 in PDF
We have some PDFs that were created with JPEG2000 images in them (*.jp2 files). Using PDFKit, and also WebKit, the images in these PDFs in some cases don't display at all, and in others cases appear badly warped. You can view the PDF using either Adobe Reader, or the Chrome app, and the images appear fine, so it's clearly not an issue of a corrupt PDF. Also, 3rd-party commercial iOS controls like PSPDF and FoxIt display the images fine, so it's clearly an issue with PDFKit and WebKit. Any known workarounds?
1
0
1.3k
Jul ’22
Export SwiftUI View
I know this is a strange and easy question. but JUST CANT FIND ANY REFERENCE aaaaaaaa I'm using SwiftUI and wants to export to PDF (best I can find Creating PDFs on MacOS without UIKit) export to image export to HTML export to everything possible etc BONUS print the page I can only find UIKit support and they are all outdated. AND IF POSSIBLE how to integrate ShareLink to share these(PDF, Image, HTML, etc) and write them onto disk using NSSavePane? even better how to do this on a of the platforms (I know I'm greedy😂) Thanks for any help🙏
0
0
866
Jun ’22
PDFKit create document version is 1.3 can we create an PDF 1.7 document?
Working with PDFkit on MacOS 12.6 and created a new PDFDocument instance. checking the HEX code of this PDF document and notice this, At the beginning there is "%PDF-1.3%". Is it possible to create a new PDFDocument in PDF Spec 1.7 version instead? if not possible with current version, any plan in the future? is there a plan to have equivalence of PDFKit in SWIFTUI world around the corner? thanks
Replies
0
Boosts
0
Views
1.2k
Activity
Oct ’22
redact functionality absent in PDFKit
Prior to macOS 10.12, text markup annotations were configured through the PDFAnnotationMarkup class (see here). An annotation of this type could be configured to use the redact, underline, strikeOut, or highlight enumerations. However, this has since been deprecated in favor of creating a PDFAnnotation with the PDFAnnotationSubtype structure. Subtypes exist for underline, highlight, and strikeOut, but no option for redact exists. What is the proper way to create a redaction annotation in the current API?
Replies
1
Boosts
1
Views
743
Activity
Oct ’22
Error When Sharing a List
I am building an app that will let users share their views as a PDF. In their views, there is a list but when sharing that view the list disappears. How can I fix it to show the list when sharing?
Replies
0
Boosts
0
Views
964
Activity
Oct ’22
Error exporting a PDF
I am trying to build an app that allows users to share their lists to other. To do this I am trying to capture the list as an image and turn it into a PDF. When I send the PDF it comes with a white screen. Is there a way to fix this? Is there somethings wrong with this code? struct ShareSheet {       static let instance = ShareSheet()       private init() { }       func share(items: [Any]) {     let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)     UIApplication.shared.currentUIWindow()?.rootViewController?.present(controller, animated: true, completion: nil)   }     } public extension UIApplication {   func currentUIWindow() -> UIWindow? {     let connectedScenes = UIApplication.shared.connectedScenes       .filter({         $0.activationState == .foregroundActive})       .compactMap({$0 as? UIWindowScene})           let window = connectedScenes.first?       .windows       .first { $0.isKeyWindow }     return window         } } extension View{       func sharePDF<Content: View> (@ViewBuilder content: @escaping () -> Content, fileName: String) {     exportPDF(content: content, completion: { status , url in       if let url = url, status {         ShareSheet.instance.share(items: [url])       } else {         print("⚠️ Failed to make PDF")       }     }, fileName: fileName)   }       // MARK: Extracting View's Height and width with the Help of Hosting Controller and ScrollView   fileprivate func convertToScrollView<Content: View>(@ViewBuilder content: @escaping ()->Content)->UIScrollView{           let scrollView = UIScrollView()           // MARK: Converting SwiftUI View to UIKit View     let hostingController = UIHostingController(rootView: content()).view!     hostingController.translatesAutoresizingMaskIntoConstraints = false           // MARK: Constraints     let constraints = [             hostingController.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),       hostingController.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),       hostingController.topAnchor.constraint(equalTo: scrollView.topAnchor),       hostingController.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),               // Width Anchor       hostingController.widthAnchor.constraint(equalToConstant: screenBounds().width)     ]     scrollView.addSubview(hostingController)     scrollView.addConstraints(constraints)     scrollView.layoutIfNeeded()           return scrollView   }       // MARK: Export to PDF   // MARK: Completion Handler will Send Status and URL   fileprivate func exportPDF<Content: View>(@ViewBuilder content: @escaping ()->Content,completion: @escaping (Bool,URL?)->(), fileName: String){           // MARK: Temp URL     let documentDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!     // MARK: To Generate New File when ever its generated     let outputFileURL = documentDirectory.appendingPathComponent("\(fileName)\(UUID().uuidString).pdf")           // MARK: PDF View     let pdfView = convertToScrollView {       content()     }     pdfView.tag = 1009     let size = pdfView.contentSize     // Removing Safe Area Top Value     pdfView.frame = CGRect(x: 0, y: getSafeArea().top, width: size.width, height: size.height)           // MARK: Attaching to Root View and rendering the PDF     getRootController().view.insertSubview(pdfView, at: 0)           // MARK: Rendering PDF     let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height))           do{               try renderer.writePDF(to: outputFileURL, withActions: { context in                   context.beginPage()         pdfView.layer.render(in: context.cgContext)       })               completion(true,outputFileURL)     }     catch{       completion(false,nil)       print(error.localizedDescription)     }           // Removing the added View     getRootController().view.subviews.forEach { view in       if view.tag == 1009{         print("Removed")         view.removeFromSuperview()       }     }   }       fileprivate func screenBounds()->CGRect{     return UIScreen.main.bounds   }       fileprivate func getRootController()->UIViewController{     guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{       return .init()     }           guard let root = screen.windows.first?.rootViewController else{       return .init()     }           return root   }       fileprivate func getSafeArea()->UIEdgeInsets{     guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else{       return .zero     }           guard let safeArea = screen.windows.first?.safeAreaInsets else{       return .zero     }           return safeArea   } }
Replies
1
Boosts
0
Views
1k
Activity
Oct ’22
Exporting a PDF that is White
I am building an app which allows users to share their list to other people. To do that I tried to turn the view into a PDF, but when sharing it, it is a white image. How can I fix this so the PDF shows the view instead of a white screen?
Replies
1
Boosts
0
Views
794
Activity
Oct ’22
PDF Annotation for file from AWS S3 bucket
We have application where our cloud storage is on AWS S3 bucket and want to use annotation feature on PDF through my iOS application. iOS application is coded in language native language can anyone please provide necessary documents to implement this yeah. Where I can access files from AWS S3 bucket and do annotation on my PDF file through iOS application
Replies
0
Boosts
0
Views
612
Activity
Sep ’22
PDFKit setBounds to trimBox doesn't work as expected in iOS16
Hi, I found the setBounds:forBox: function doesn't set the bounds of trimBox as expected in iOS16. On iOS15.6, when the setBounds is called and page is larger than the specified bounds, the page will shrink and resize to fit inside the specified bounds; but on iOS16, it doesn't do anything. From the debugger I can tell that the trimBox bounds is indeed set to the specified size, but I'm not sure what underlying logic is broken. Has anyone seen similar issues in iOS16?
Replies
0
Boosts
0
Views
713
Activity
Sep ’22
Accessibility of PDF on Apple platforms in 2022 and beyond
I'm finding it extremely difficult to find accurate and up-to-date information about support for accessibility with PDF on Apple's platforms, in particular Safari and Preview on iOS and Mac. For a long time it seemed that nothing worked (e.g. browsing a PDF with VoiceOver in Preview), but I've started to get some acceptable, but patchy results. Apparently things have changed under the hood since the extensive outcry at High Sierra's implementation of PDFKit but what exactly has changed? Is there a change log anywhere? Did any of the notorious PDFKit bugs from 2017 get fixed? I will mention some important jargon used in the accessibility community: "Accessibility supported". This term has a formal definition in the WCAG spec. Basically it's not enough that a file format (such as PDF) or an app (such as Safari) is hypothetically accessible, if I can't actually browse my PDF in Safari using Voiceover. Legally speaking, this information should be absolutely clear in the VPAT for Mac OS. It isn't. Lawyers with an interest in accessibility suits should take note. My questions: I've studied the latest documentation for PDFKit and can find no mention of semantic tagging, read order or the PDF/UA format in general. How does this work? Did Apple invent new names for these features, or is it simply unsupported? Can I use VoiceOver to browse a well-formed tagged PDF/UA file 'semantically' in Safari? (E.g. 'next heading' keyboard shortcut, or using the rotor). If I save a PDF from Safari or Preview, do I get a well-formed 'accessible PDF' (i.e. a "tagged PDF" file with the PDF/UA flag)? How might HTML semantics be mapped onto PDF/UA output, when saving a web page as PDF from Safari, given that there is not 100% parity between the two semantic systems? Can I browse PDF/UA files in Acrobat Reader with VoiceOver? If not, why aren't Apple and Adobe taking steps to fix this situation? I understand that Pages, Numbers and Keynote all produce tagged PDF. I assume this means some conformance with the PDF/UA 1.7 spec? Are there any omissions in support for the PDF/UA standard by this route? What are those omissions? Regarding the accessibility of the output, is there any difference between "Save as PDF", "Export PDF" and "Print to PDF" in Apple's software? Please advise on any of these points.
Replies
0
Boosts
1
Views
1.5k
Activity
Sep ’22
WKWebView: loadHTMLString and createPDF always fails since updating to macOS Monterey
Hello, I had programmed and used a software for a year without problems but after updating to Monterey and updating XCode, the following, simplified Playground example of the process always fails and I cannot figure out why. Please note this project is specifically written for macOS and I cannot use the iOS libraries for PDF generation. import WebKit import PDFKit import SwiftUI import CoreGraphics let webView: WKWebView = WKWebView(frame: CGRect(x: 0, y: 0, width: 595.0, height: 842.0), configuration: WKWebViewConfiguration()) let htmlString = "<html><body><h1>Hello</h1></body></html>" webView.loadHTMLString(htmlString, baseURL: nil) webView.createPDF(completionHandler: compHandler) func compHandler(res: Result<Data, Error>) -> Void { print(res) } This always results in an error: failure(Error Domain=WKErrorDomain Code=1 "An unknown error occurred" UserInfo={NSLocalizedDescription=An unknown error occurred}) I cannot find anything in the documentation regarding this and most examples and questions are old and not applicable (many still using Objective-C). Debugging seems to suggest that the loadHTMLString itself fails, not even necessarily the PDF itself. Any pointers would be appreciated. Thanks
Replies
0
Boosts
0
Views
1.2k
Activity
Sep ’22
Highlighter Annotation Large Frame
I am using PDFKit to draw annotation over PDF view. While performing multiple highlighter annotation most of the time long pressing on the highlighter annotation is getting proper frame but in one PDF when long pressing on the highlighter annotation is getting large frame and it is selecting all the nearest highlighter. This method is giving the wrong location and this is the default method of PDFKit. let tapPageLocation = pdfView.convert(location, to: page)
Replies
0
Boosts
0
Views
1.5k
Activity
Aug ’22
How to create and store the pdf file
I'm using CGContext.init(withUrl) to create a pdf context and doing some rendering inside that context. I was able to save the pdf in the location which will be available in the url. But in my case i will not have a location while creating the CGContext. So in my case i need a create a CGPDFContext without the location. I tried using the CGDataConsumer, but that also not working. My Requirements 1. Have to create PDF file without the save location. 2. In certain time interval i have to save that pdf to the particular location
Replies
3
Boosts
0
Views
3.6k
Activity
Aug ’22
Enable Live Text on PDFKit
Hi! I watched WWDC2022's 10089 session "What's New in PDFKit?" where it's said that Live Text is now compatible with PDFKit. However, I can't seem to find anything related to it in documentation or code. ImageAnalyzer needs an UIImage to work. But that would mean retrieve the current PDFPage and then convert it to UIImage which is a performance hog. How can I enable Live Text in PDFKit? thanks.
Replies
1
Boosts
0
Views
1.7k
Activity
Aug ’22
Multipage PDF with PDFKit on macOS with swift
Hello everybody, After weeks and months of searching for a solution (with interruptions) I finally have to ask the question: is there a tutorial to generate PDF with multiple pages from a macOS app with swift / swiftui? I am programming a macOS app and want (must) save and print letters and other documents as PDFs at the touch of a button. All the examples that I have been able to find so far are only for iOS and simply turning "UIGraphicsPDFRenderer" into "NSGraphicsPDFRenderer" is not possible. It can't be that no PDF can be created under macOS. It has to work somehow, doesn't it? Alternatively, it would be enough for me if you could print a view from SwiftUI. But that doesn't seem to work that easily, too. I would be very grateful for your help.
Replies
1
Boosts
0
Views
1.9k
Activity
Aug ’22
Error loading a file from Firebase
Hi all, I have been facing a problem while loading a file from the firebase storage. Basically in my code i have a data model which is the file/document (pdf in this case), a manager which goes into the database of Firebase to fetch the object and finally two views, one to list the files fetched and another one to show the document. I can fetch all the documents with their specific data, pass them to my view and then show the document pdf in another view. Everything seems correct but the problem comes when opening one of this docs. First, the doc doesn't open at first so you need to close the view and try to open the doc again. Then when i want to open another doc from my list, when i click on it the previous document is shown and not the correct one, so i need to do the same, close the view and click again on the doc to open the correct one. So at the end what i'm looking for is to open the doc just clicking once but i don't know where is my problem. List of docs: 1st time: 2nd time: 2nd doc but 1st time: 2nd doc and 2nd time clicking on it: Here is my code Model: struct DocumentoPdf {     let titulo: String     let docUrl: URL?     let id: String     let storageUrl: String } Manager which fetches the documents from firebase: final class DatabaseManager { [...]     public func getNovedades(completion: @escaping ([DocumentoPdf]) -> Void) {         database.collection("novedades").getDocuments { snapshot, error in             guard let documents = snapshot?.documents.compactMap ({ $0.data() }), error == nil else {                 return             }             let novedades: [DocumentoPdf] = documents.compactMap({ dictionary in                 guard let id = dictionary["id"] as? String,                       let titulo = dictionary["titulo"] as? String,                       let docUrlString = dictionary["docUrl"] as? String,                       let storageUrl = dictionary["storageUrl"] as? String else {                           return nil                       }                 let novedad = DocumentoPdf(titulo: titulo,                                            docUrl: URL(string: docUrlString),                                            id: id,                                            storageUrl: storageUrl)                 return novedad             })             completion(novedades)         }     } } First View: class NovedadesViewControllerViewModel {     let docUrl: URL?     var docData: Data?     init(docUrl: URL?) {         self.docUrl = docUrl     } } class NovedadesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PDFViewDelegate {     private var tableView =  UITableView()    private var doc = PDFDocument()     public func configureDocPdf(with viewModel: NovedadesViewControllerViewModel) {         if let data = viewModel.docData {             doc = PDFDocument(data: data)!         }         else if let url = viewModel.docUrl {             // fetch doc & cache             let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in                 guard let data = data else {                     return                 }                 viewModel.docData = data                 DispatchQueue.main.async {                     self?.doc = PDFDocument(data: data)!                 }             }             task.resume()         }     }     private var novedades: [DocumentoPdf] = []     private func obtenerNovedades() {         DatabaseManager.shared.getNovedades() { [weak self] novedades in             self?.novedades = novedades             DispatchQueue.main.async {                 self?.tableView.reloadData()             }         }     }     override func viewDidLoad() { [...]         obtenerNovedades() [...]     } [... sections, rows in section...]     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {         let novedad = novedades[indexPath.row]         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)         cell.textLabel?.text = novedad.titulo         return cell     }     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {         let novedad = novedades[indexPath.row]         switch indexPath.section {         case 0:             configureDocPdf(with: .init(docUrl: novedad.docUrl))             let lectorPdfView = LectorPdfViewController(doc: self.doc, nameDoc: novedad.titulo)             self.present(lectorPdfView, animated: true, completion: nil)         default:             break         }     } } Second View to load the pdf: class LectorPdfViewController: UIViewController, PDFViewDelegate {     private let navBar = UINavigationBar()     private let pdf = PDFView()     let nameDoc: String     let doc: PDFDocument     init(doc: PDFDocument, nameDoc: String) {         self.doc = doc         self.nameDoc = nameDoc         super.init(nibName: nil, bundle: nil)     }     required init?(coder: NSCoder) {         fatalError()     }     override func viewDidLoad() {         super.viewDidLoad()         view.backgroundColor = .systemBackground         view.addSubview(navBar)         view.addSubview(pdf)         pdf.document = self.doc         pdf.delegate = self         let item = UINavigationItem(title: self.nameDoc)         navBar.setItems([item], animated: false)         navBar.barTintColor = .systemBackground     }     override func viewDidLayoutSubviews() {         navBar.frame = CGRect(x: 0,                               y: 0,                               width: view.frame.size.width,                               height: 50)         pdf.frame = CGRect(x: 0,                            y: navBar.frame.height,                            width: view.frame.size.width,                            height: view.frame.size.height - navBar.frame.height)     } } Please if someone can help me with this will be fantastic. I hope you understood my code and my problem. Sorry for my bad english Thank you so much in advance
Replies
4
Boosts
1
Views
1.9k
Activity
Aug ’22
PDFKit Link Annotations gets stripped off when saving
I'm using the following code to draw a text over PDF page.Everything works fine, but if you process a PDF with internal links eg: a Book with Content links to pages, the resultant PDF file seems to have the links stripped off.Why does this happen? let data = NSMutableData() let consumer = CGDataConsumer(data: data as CFMutableData)! let context = CGContext(consumer: consumer, mediaBox: nil, nil)! let pdffile=PDFDocument(url: input) for y in stride(from: 0, to: pagecount, by: 1) { let page: PDFPage = pdffile!.page(at: y)! var mediaBox = page.bounds(for: PDFDisplayBox.mediaBox) NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false) let bounds = page.bounds(for: PDFDisplayBox.mediaBox) let size = bounds.size page.draw(with: .mediaBox, to: context) text.draw(in:drawrect,withAttributes:textFontAttributes); context.endPDFPage() } context.closePDF() try! data!.write(to: GetOutputFileName(inputfile: x), options[.atomicWrite]) What I have tried is saving the annotation of each page applying it before ending the page for annotation in pageannottaions                 {                     page.addAnnotation(annotation)                 } This also does not work.Please advice
Replies
0
Boosts
0
Views
676
Activity
Aug ’22
Export MacOS SwiftUI form to pdf
I am building a MacOS dedicated app where I want to build a document template using a form. Inside the form there are multiple data types: text, pickers, images, links to other pdfs and signatures. I want to be able to export the data in the form to pdf, retaining the formatting of the form. I have searched high and low for some sort of solution, where PDFKit and Quartz seem to come up but no viable solution. This really should not be a complex process... And I do not want to use storyboard but only use SwiftUI.
Replies
1
Boosts
0
Views
710
Activity
Aug ’22
Can FileProvider provide the full quicklook experience for PDF's?
For local files, it's an amazing feature to be able to space-bar open a PDF document and quickly swipe through the contents of it. How can I enable this for pdf files stored on a volume exposed by FileProvider? Thanks David
Replies
1
Boosts
0
Views
1.4k
Activity
Jul ’22
Upside down drawings on iOS 16 preview
We are currently testing our mobile application on the iOS 16 preview. Our application allows you to draw and sign using the UIKit/PDFKit which results in an image that we store. When the image is opened it is displayed upside down. Is this an expected change caused by the new OS or is this a bug that will be fixed when the stable version is released? Is there any guide/advice on this if this is an expected change?
Replies
2
Boosts
0
Views
987
Activity
Jul ’22
PDFKit & WebKit problem with JPEG2000 in PDF
We have some PDFs that were created with JPEG2000 images in them (*.jp2 files). Using PDFKit, and also WebKit, the images in these PDFs in some cases don't display at all, and in others cases appear badly warped. You can view the PDF using either Adobe Reader, or the Chrome app, and the images appear fine, so it's clearly not an issue of a corrupt PDF. Also, 3rd-party commercial iOS controls like PSPDF and FoxIt display the images fine, so it's clearly an issue with PDFKit and WebKit. Any known workarounds?
Replies
1
Boosts
0
Views
1.3k
Activity
Jul ’22
Export SwiftUI View
I know this is a strange and easy question. but JUST CANT FIND ANY REFERENCE aaaaaaaa I'm using SwiftUI and wants to export to PDF (best I can find Creating PDFs on MacOS without UIKit) export to image export to HTML export to everything possible etc BONUS print the page I can only find UIKit support and they are all outdated. AND IF POSSIBLE how to integrate ShareLink to share these(PDF, Image, HTML, etc) and write them onto disk using NSSavePane? even better how to do this on a of the platforms (I know I'm greedy😂) Thanks for any help🙏
Replies
0
Boosts
0
Views
866
Activity
Jun ’22