Display and manipulate PDF documents in your applications using PDFKit.

PDFKit Documentation

Posts under PDFKit tag

57 Posts
Sort by:
Post not yet marked as solved
0 Replies
14 Views
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.
Posted
by fusioni.
Last updated
.
Post marked as solved
1 Replies
182 Views
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?
Posted Last updated
.
Post not yet marked as solved
3 Replies
131 Views
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
Posted
by moraKevin.
Last updated
.
Post not yet marked as solved
0 Replies
51 Views
XCode - Swift private var mPdfView = PDFView() private var mDocumentData: Data? mDocumentData = MakePdfDocument() mPdfView.document = PDFDocument(data: mDocumentData!) let printInfo = UIPrintInfo(dictionary: nil) printInfo.outputType = UIPrintInfo.OutputType.general printInfo.jobName = “JobName” let printController = UIPrintInteractionController.shared printController.printInfo = printInfo printController.printingItem = mPdfView printController.showsNumberOfCopies = true printController.present(animated: true, completionHandler: nil) **When print is executed, only the blank screen is output, not the generated PDF. How can I print the generated PDF content?**
Posted
by pj3036.
Last updated
.
Post not yet marked as solved
0 Replies
98 Views
I'm trying to use PDFPageOverlayViewProvider by copying the code provided in the "What's new in PDFKit" WWDC22 session here: https://developer.apple.com/videos/play/wwdc2022/10089/ I've copied the method implementations and set my pdfView's pageOverlayViewProvider property to the view where I implemented the protocol. However, when I try to run my app, the pdfView(_ view: PDFView, overlayViewFor page: PDFPage) method is never getting called. Has anyone been able to get this working successfully?
Posted
by pablogb.
Last updated
.
Post not yet marked as solved
0 Replies
114 Views
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🙏
Posted Last updated
.
Post not yet marked as solved
1 Replies
165 Views
There are some errors when attempting to run the sample code: Cannot convert value of type 'String' to expected argument type 'PDFAnnotationSubtype' I understand the error but I'm unsure what it's looking for. I'm running Xcode 14, targeting iOS 12 Thx for any feedback!
Posted
by anm8tr.
Last updated
.
Post not yet marked as solved
2 Replies
1k Views
I took pdfView, and I am trying to load pdf document on this pdfView. Pdf is not displaying/showing full screen w.r.t its pdfView as I added in storyboard. It has some gaps from top and bottom. Here is the code, I wrote swift if let path = Bundle.main.path(forResource: "file-sample_150kB", ofType: "pdf") {             if let pdfDocument = PDFDocument(url: URL(fileURLWithPath: path)) {                                  pdfView.autoresizesSubviews = true                 pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]                 pdfView.displayDirection = .vertical                 pdfView.autoScales = true                 pdfView.displayMode =  .singlePage                 pdfView.displaysPageBreaks = true                 pdfView.document = pdfDocument                 pdfView.maxScaleFactor = 4.0                 pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit                 pdfView.usePageViewController(true, withViewOptions: [:])             }         } How I can remove that extra space from top and bottom and make/show/display that pdf document to full to screen w.r.t pdfView which I added in storyboard that same size. Any solution for this? Note - In my code/requirement displaying single page is needed i.e pdfView.displayMode =  .singlePage Here is project link - [https://github.com/MallikarjunH/TestPDFFullScreen1)
Posted
by ArjuniOS.
Last updated
.
Post not yet marked as solved
0 Replies
169 Views
I create a UIViewRepresentable to show my PDF inside my SwiftUI app. I want to access the current page number using currentPage?.pageRef?.pageNumber. from the view in which I display the pdf. How to make PDFView Created in func makeUIView(context: UIViewRepresentableContext<PDFDisplayRepresentedView>) -> PDFView Available in the view displaying the pdf so I can access its properties to obtain page number. import SwiftUI import PDFKit struct PDFDisplayView: View { @Binding var pdfDocument : PDFDocument? var body: some View { PDFDisplayRepresentedView(pdfDocument: pdfDocument!) } } struct PDFDisplayRepresentedView: UIViewRepresentable { let pdfDocument: PDFDocument init(pdfDocument: PDFDocument) { self.pdfDocument = pdfDocument } func makeUIView(context: UIViewRepresentableContext<PDFDisplayRepresentedView>) -> PDFView { return createPDFViewUsing(document: pdfDocument) } func updateUIView(_ pdfView: PDFView, context: UIViewRepresentableContext<PDFDisplayRepresentedView>) { pdfView.document = pdfDocument } private func createPDFViewUsing(document : PDFDocument) -> PDFView { let pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) pdfView.document = document ... set up pdfView attributes return pdfView } } view showing pdf where I want to know the page number pseudo code … @State private var pdfDisplayView : PDFDisplayView? …. var body: some View { load the pdf into this view. need to access the page number pdfDisplayView }
Posted
by RyanTCB.
Last updated
.
Post not yet marked as solved
0 Replies
101 Views
Good afternoon (o; Doing a simple SwiftUI app where it fetches a PDF barcode from a web service to be printed on a thermal label printer. So I use this snippet to fetch the PDF and launch the printing dialog:         let pdfView = PDFView()         pdfView.document = PDFDocument(url: self.url!)         let wnd = NSWindow()         pdfView.autoScales = true         pdfView.displaysPageBreaks = false         wnd.setContentSize(pdfView.frame.size)         wnd.contentView = pdfView         pdfView.print(with: printInfo, autoRotate: false) But the printing dialog appears on the lower left corner of the screen...and when choosing "details" the dialog extends to the offscreen area.... Also no paper size is choosable. thanks in advance richard
Posted
by davorin.
Last updated
.
Post not yet marked as solved
1 Replies
405 Views
Hi, We need to develop a functionality where we need to lock and unlock Pdf. For this, We need to use inbuilt methods provided by the PDFKit framework. With that locking and unlocking features are working perfectly before updating to iOS 15. But when I upgrade to iOS 15 locking feature works very well but unlocking is not working. I have used the below method for unlocking PDF, unlock(withPassword:) func unlock(withPassword password: String) -> Bool https://developer.apple.com/documentation/pdfkit/pdfdocument/1436033-unlock been searching for this everywhere and can't find anything around this, I believe is a bug, maybe is not.
Posted Last updated
.
Post not yet marked as solved
0 Replies
168 Views
https://pdftron.s3.amazonaws.com/custom/test/jack/blank+(34).pdf Here is the pdf. You could download it. In the PDF, there is a checkbox. When we open the PDF in Acrobat and Chrome, it can be edited. However, when we open it in Mac Preview and IOS devices. The checkbox is hidden and cannot be edited anymore. It could be a bug from Preview and IOS PDF editor
Posted
by Jack-Hou.
Last updated
.
Post not yet marked as solved
0 Replies
513 Views
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.
Posted
by benwiggy.
Last updated
.
Post not yet marked as solved
1 Replies
318 Views
Recently, our app crash monitor detect a lot of PDFKit crash problem at iOS 15.3: MACH_Exception EXC_BREAKPOINT EXC_ARM_BREAKPOINT fault_address:0x00000001809a52d8 Thread 67 name: PDFKit.PDFTilePool.workQueue 0 CoreFoundation _CFRetain (in CoreFoundation) 1 CoreGraphics _CGColorRetain (in CoreGraphics) 2 PDFKit -[PDFPage _drawWithBox:inContext:withRotation:isThumbnail:withAnnotations:withBookmark:withDelegate:] (in PDFKit) 3 PDFKit -[PDFPage drawWithBox:inContext:isThumbnail:] (in PDFKit) 4 PDFKit -[PDFView drawPage:toContext:] (in PDFKit) 5 PDFKit -[PDFTilePool _renderTileForRequest:] (in PDFKit) 6 libdispatch.dylib __dispatch_call_block_and_release (in libdispatch.dylib) 7 libdispatch.dylib __dispatch_client_callout (in libdispatch.dylib) 8 libdispatch.dylib __dispatch_lane_serial_drain (in libdispatch.dylib) 9 libdispatch.dylib __dispatch_lane_invoke (in libdispatch.dylib) 10 libdispatch.dylib __dispatch_workloop_worker_thread (in libdispatch.dylib) 11 libsystem_pthread.dylib __pthread_wqthread (in libsystem_pthread.dylib) 12 libsystem_pthread.dylib _start_wqthread (in libsystem_pthread.dylib) It crash at the thread: PDFKit.PDFTilePool.workQueue Anyone got the same problem? Is there any solutions for this problem?
Posted
by hanson21.
Last updated
.
Post not yet marked as solved
0 Replies
222 Views
Is there a way to apply color filters to the contents of a PDF displayed in a PDFView? My desired effect is to display the PDF with colors inverted. CIFilter and compositingFilter seem relevant, but I couldn't get to a working example. Any guidance appreciated!
Posted Last updated
.
Post not yet marked as solved
0 Replies
176 Views
Feature request: a new PDFView layout in PDFKit This feature request is from the Skim.app Sourceforge page https://sourceforge.net/p/skim-app/feature-requests/1640/ orignial feature request It would be nice if we can have a PDF Display option "Single-page Two-column Continuous" which I would explain below. I imagine we can have a layout like the "Two Pages Continuous", but the right-hand-side page is the same page as the left-hand-side page, continued from the bottom. Like this:   |  /| | / | |/ ↓ L  R This will be extremely helpful for short displays, as it take full advantage of the width of the display while still gives rather large fonts. response from the Skim team The page layout is implemented by Apple's PDFKit. If you want to have support for it, you should first ask Apple to provide it. My problem I have no idea how to ask Apple to provide it. If the provider of PDFKit can see this, that would be great. Or if anyone know what should I do to ask for this feature, please help. I suppose this can benefit more as it would not only be implemented in Skim.app but probably also Preview.app
Posted
by StevenHe.
Last updated
.
Post not yet marked as solved
1 Replies
185 Views
Hello! I need help on getting rid of these other actions whenever saving pdf files.
Posted
by Jdapper.
Last updated
.
Post not yet marked as solved
0 Replies
226 Views
Hi, I am trying to export the following SwiftUI View to PDF using UIGraphicsPDFRenderer. The problem I am getting is there is somehow a margin on top of the exported PDF. The code I am using import SwiftUI struct ContentView: View {     var body: some View {         let pressGesture = TapGesture()                .onEnded { value in                    let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!                    let outputFileURL = documentDirectory.appendingPathComponent("SwiftUI.pdf")                    let pdfVC = UIHostingController(rootView: self)                    let pageSize = CGSize(width: 2.625 * 72.0, height: 1.0 * 72.0)                    pdfVC.view.frame = CGRect(origin: .zero, size: pageSize)                    let rootVC = UIApplication.shared.windows.first?.rootViewController                    rootVC?.addChild(pdfVC)                    rootVC?.view.insertSubview(pdfVC.view, at: 0)                    let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: pageSize.width, height: pageSize.height))                    DispatchQueue.main.async {                         do {                                                                                 try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in                                 context.beginPage()                                 pdfVC.view.layer.render(in: context.cgContext)                             })                             print("wrote file to: (outputFileURL.path)")                             pdfVC.removeFromParent()                             pdfVC.view.removeFromSuperview()                                              } catch {                             print("Could not create PDF file: (error.localizedDescription)")                         }                     }                                }         VStack(){                 Text("Hello")         }         .frame(width: 2.625 * 72.0, height: 1.0 * 72.0, alignment: .center)         .gesture(pressGesture)         .background(Color.red)     } } May I know what am I doing wrong? Thanks in advance.
Posted
by jamesboo.
Last updated
.
Post not yet marked as solved
0 Replies
185 Views
I have a bunch of PDF files that I try to open either with CGPDFDocument or PDFDocument (PDFKit) and the init return NULL. Where can I get some feedback why this is happening? I cannot find anything on Console (for connected iOS device) or the Xcode Debug Output window. Let me say that this is not true for all PDF files, some open and some do not. It is also not a problem with permissions, the files are accessible by the app.
Posted
by zobo.
Last updated
.
Post not yet marked as solved
1 Replies
1.1k Views
So I have this pdfView and I wanna make it so its first display is a zoom of 100% of the page, but the problem is that what I have now is zooming in to much and the UI is not pretty to be like that. It just like zooms to much and I want it to be perfectly zoomed to fit the screen size. I have tried and can't find a solution. My code is this: &#9;&#9;pdfView.translatesAutoresizingMaskIntoConstraints = false &#9;&#9;pdfView.autoScales = true &#9;&#9;pdfView.maxScaleFactor = 4.0 &#9;&#9;pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit &#9;&#9;view.addSubview(pdfView) &#9;&#9;pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true &#9;&#9;pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true &#9;&#9;pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true &#9;&#9;pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true &#9;&#9; &#9;&#9; &#9;&#9;guard let path = Bundle.main.url(forResource: materia , withExtension: "pdf") else { return } &#9;&#9;if let document = PDFDocument(url: path) { &#9;&#9;&#9;&#9;pdfView.document = document &#9;&#9;}
Posted Last updated
.