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
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: 		pdfView.translatesAutoresizingMaskIntoConstraints = false 		pdfView.autoScales = true 		pdfView.maxScaleFactor = 4.0 		pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit 		view.addSubview(pdfView) 		pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true 		pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true 		pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true 		pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true 		 		 		guard let path = Bundle.main.url(forResource: materia , withExtension: "pdf") else { return } 		if let document = PDFDocument(url: path) { 				pdfView.document = document 		}
Posted
by
Post not yet marked as solved
0 Replies
463 Views
Hi! I'm dropping a pdf file in an app, and I'm getting 2 errors I cannot understand. When I drop the file I'm supposed to create a pdf view, which, by the way I can. I perform the drop th in a swiftui view.             GeometryReader { geometry in                 ZStack {                     Rectangle()                         .foregroundColor(.white)                         .overlay(OptionalPDFView(pdfDocument: self.document.backgroundPDF))                                     }.onDrop(of: ["public.data"], isTargeted:nil) { providers, location in                     for provider in providers { provider.loadDataRepresentation(forTypeIdentifier: "public.data") { (data, err) in                             if let safeData = data {                                 self.document.setBackgroundData(data: safeData)                             } else {                                 print("problem")                             }                         }                     } ]                    return self.drop(providers: providers, al: location)                 }             } The problem is if I define and on drop of public.adobe.pdf, nothing is recognized when I drag a file into it, and when I specify public.data and I want to extract the provider data for that identifier, I get this console message : " Cannot find representation conforming to type public.data". I'm trying to build a Mac app (Appkit). Thanks a lot.
Posted
by
Post not yet marked as solved
1 Replies
691 Views
Good Day, I am experiencing issue on viewing PDF file using WKWebview. The view turns white after the page load or the pdf does not finished render yet. Upon checking on console, I saw this error in the log. Can somebody help me with this issue. Thank you. btw, I am using iOS 14 2020-11-17 09:34:20.782707+0800 TEST[848:49473] [lifecycle] [u 76D7227D-EDDA-4B7D-899D-94CC599E51B8:m (null)] [com.apple.PDFKit.PDFExtensionView(1.0)] Connection to plugin interrupted while in use. 2020-11-17 09:34:20.784351+0800 TEST[848:49715] [lifecycle] [u 76D7227D-EDDA-4B7D-899D-94CC599E51B8:m (null)] [com.apple.PDFKit.PDFExtensionView(1.0)] Connection to plugin invalidated while in use. 2020-11-17 09:34:20.785713+0800 TEST[848:49388] [Loading] 0x10a14ee18 - [pageProxyID=6, webPageID=7, PID=854] WebPageProxy::dispatchProcessDidTerminate: reason = 3 2020-11-17 09:34:20.793156+0800 TEST[848:49388] viewServiceDidTerminateWithError:: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "(null)" UserInfo={Message=Service Connection Interrupted}
Posted
by
Post not yet marked as solved
1 Replies
457 Views
Tagged PDF (also known as PDF/UA), created in 2012, is an ISO standard mandated by EU accessibility directives since 2019, and in other jurisdictions. As far as I can tell, Apple has no support for this format in any of its products (Notably Safari and Preview, but also the "Save as PDF" feature in Apple's print dialog, and the PDFKit Framework). This shortcoming makes Apple platforms far less than ideal for customers (and organisations) who seek (or are required to procure) accessible products. I know that Apple generally does not comment on unreleased products, but Safari and Preview are already released. Any Apple device is therefore non-compliant with an increasingly common legally mandated file format out-of-the-box. Accessibility consultants can therefore not (in good faith) recommend Apple products to any EU public sector org which relies on documents in PDF/UA format. How long must we continue to recommend *against* Apple products to customers with disabilities, and the organisations that hope to serve them?
Posted
by
Post not yet marked as solved
4 Replies
2.2k Views
Hi, I use this function to generate a QRCode Image func generateQRCode(string: String, height: CGFloat, width: CGFloat)->UIImage?{   let data = string.data(using: String.Encoding.ascii)       if let filter = CIFilter(name: "CIQRCodeGenerator") {     filter.setValue(data, forKey: "inputMessage")     filter.setValue("Q", forKey: "inputCorrectionLevel")     let transform = CGAffineTransform(scaleX: 3, y: 3)           if let output = filter.outputImage?.transformed(by: transform) {       let scaleX = width / output.extent.size.width       let scaleY = height / output.extent.size.height               let transformedImage = output.transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY))               return UIImage(ciImage: transformedImage)     }   }   return UIImage() } In another app works correctly but in the app that I develop I get this error. The filter 'CIPortraitEffectSpillCorrection' is not implemented in the bundle at /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/CoreImage/PortraitFilters.cifilter How can I solve this?
Posted
by
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
Post not yet marked as solved
0 Replies
655 Views
I have implemented a PDFView in the app but it is unable to show the pdf downloaded from the web service. If I add a bundle resource in the project it loads it fine. But the one from the API is not loaded. I have added the code below to check further. struct UploadQuotationView: View {       let frId: String = "FR-DEMO-062021-00116"   @State var downloadURL = URL(string: "https://www.apple.com") //  @State var fileURL = Bundle.main.url(forResource: "c4611_sample_explain", withExtension: "pdf")   @State var docSheet = false   @State var pdfView = PDFKitRepresentedView(Data())   @State var data = Data()   var body: some View {                      VStack{       Button("View PDF"){                   //downloadFile()         downloadAndView(fileName: "Quotation\(frId)")         //fileURL = Bundle.main.url(forResource: "fileSample", withExtension: "pdf")                 }       .onAppear(){ //        downloadAndView(fileName: "Quotation\(frId)")       }       .padding()       PDFKitRepresentedView(data)         .cornerRadius(10)         .padding()         .shadow(radius: 10)               Button("document picker"){         docSheet.toggle()       }       .sheet(isPresented: $docSheet) {         DocumentPickerView()       }       .padding()     }   }               func downloadAndView(fileName:String) {           guard let url = URL(string: "\(CommonStrings().apiURL)faultreport/quotation/\(frId)") else {return}           var urlRequest = URLRequest(url: url)     urlRequest.httpMethod = "GET"     urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")     urlRequest.setValue(UserDefaults.standard.string(forKey: "token"), forHTTPHeaderField: "Authorization")     urlRequest.setValue(UserDefaults.standard.string(forKey: "role"), forHTTPHeaderField: "role")     urlRequest.setValue( UserDefaults.standard.string(forKey: "workspace"), forHTTPHeaderField: "workspace")           print(urlRequest)           let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in       if let error = error {         print("Request error: ", error)         return       }               guard let response = response as? HTTPURLResponse else {         print("response error: \(String(describing: error))")         return       }               if response.statusCode == 200 {                   if let pdfData = data {           print("success")           //pdfView = PDFKitRepresentedView(pdfData)           self.data = pdfData         }       }else{         print("Error: \(response.statusCode). There was an error")       }     }     dataTask.resume()   }   } struct PDFKitRepresentedView: UIViewRepresentable {       let pdfView = PDFView()       let data: Data   init(_ data: Data) {     self.data = data   }       func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {     pdfView.document = PDFDocument(data: data)     pdfView.displayMode = .singlePage     pdfView.displayDirection = .horizontal     return pdfView   }       func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {     pdfView.document = PDFDocument(data: data)   }     } There are some variables that you can modify as per your liking like the api URL and similar. I have added the screenshot that shows the data is loaded in the "data" variable when the API request is success. Please check the screenshot.
Posted
by
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
Post not yet marked as solved
0 Replies
361 Views
We are using PDFKit framework to display PDF and add annotation on PDF files. Before rendering PDF for the display we are using PDFKit framework's write method to save the PDF file in documents directory. It supports most of the functionality required for our application but for few PDF files we are not able to recognize text on PDF. To those PDF files we are unable to search keyword. After lot of research we found out that the issue is occurring for PDF files which are created via CorelDRAW. We are requesting your assistance in this issue as lot of our users are creating PDFs via CoralDraw software. Please let me know in case of more clarification.
Posted
by
Post not yet marked as solved
1 Replies
502 Views
How to reorder a pdf document? move page p after page n, or at a given m position. add new page at certain position rotate a page 90° or 180°. I've seen libraries, but I would prefer to redevelop those simple functions directly in an iOS app (Swift). I don't need to edit the document content, just rearrange.
Posted
by
Post marked as solved
1 Replies
545 Views
I try to rotate a page 180° in a pdf file. I nearly get it, but the page is also mirrored horizontally. Some images to illustrate: Initial page: Result after rotation (see code): it is rotated 180° BUT mirrored horizontally as well: The expected result It is just as if it was rotated 180°, around the x axis of the page. And I would need to rotate 180° around z axis (perpendicular to the page). It is probably the result of writeContext!.scaleBy(x: 1, y: -1) I have tried a lot of changes for transform, translate, scale parameters, including removing calls to some of them, to no avail. @IBAction func createNewPDF(_ sender: UIButton) { var originalPdfDocument: CGPDFDocument! let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = urls[0] // read some pdf from bundle for test if let path = Bundle.main.path(forResource: "Test", ofType: "pdf"), let pdf = CGPDFDocument(URL(fileURLWithPath: path) as CFURL) { originalPdfDocument = pdf } else { return } // create new pdf let modifiedPdfURL = documentsDirectory.appendingPathComponent("Modified.pdf") guard let page = originalPdfDocument.page(at: 1) else { return } // Starts at page 1 var mediaBox: CGRect = page.getBoxRect(CGPDFBox.mediaBox) // mediabox which will set the height and width of page let writeContext = CGContext(modifiedPdfURL as CFURL, mediaBox: &mediaBox, nil) // get the context var pageRect: CGRect = page.getBoxRect(CGPDFBox.mediaBox) // get the page rect writeContext!.beginPage(mediaBox: &pageRect) let m = page.getDrawingTransform(.mediaBox, rect: mediaBox, rotate: 0, preserveAspectRatio: true) // Because of rotate 0, no effect ; changed rotate to 180, then get an empty page writeContext!.translateBy(x: 0, y: pageRect.size.height) writeContext!.scaleBy(x: 1, y: -1) writeContext!.concatenate(m) writeContext!.clip(to: pageRect) writeContext!.drawPDFPage(page) // draw content in page writeContext!.endPage() // end the current page writeContext!.closePDF() } Note: This is a follow up of a previous thread, https://developer.apple.com/forums/thread/688436
Posted
by
Post not yet marked as solved
1 Replies
625 Views
What is the currently recommended way to create a pdf document in Xcode 13 for Mac OSX using Swift and SwiftUI? I find very little documentation on this. Most articles are for IOS. Only some articles for OSX from many, many years back. With SwiftUI, it will become common place for our code to be used interchangeable in multiple operating systems. And pdf is pretty much the way to go with document and report printouts. Please point me in the right direction. Maybe I was just not looking in the right place. My pdf documents are created without any problem for IOS and Ipad using CG and PDFKit functions. But the same code did not work for the Mac app. So I modified the UIFont to NSFont, etc. Context functions are different. Moved to using CoreText for the attributed string placements. ( CTFrame ) But the strange stuff is the Y point placement that is correct for IOS but seems to be reversed for OSX. So this was when I thought I must be using some old stuff that is not meant for today's work. Brief Example below: func pdf_placeText_CT( cgContext: CGContext, pageSize: CGSize, text: String, width: CGFloat, height: CGFloat, font: NSFont, alignment: String, xPoint: CGFloat, yPoint: CGFloat ) {         let pointY = pageSize.height - yPoint  // for some reason we have to flip the vertical. Strange.   let paragraphstyle = NSMutableParagraphStyle()           if ( alignment == "R" ) {       paragraphstyle.alignment = .right     } else if ( alignment == "C" ) {       paragraphstyle.alignment = .center     } else {       paragraphstyle.alignment = .left     }         let attributedText = NSAttributedString(string: text, attributes: [       NSAttributedString.Key.font      : font ,       NSAttributedString.Key.paragraphStyle : paragraphstyle      ])         let stringSize = attributedText.size()   let stringRect = CGRect(x: xPoint, y: pointY, width: stringSize.width+5, height: stringSize.height+5)   let stringPath = CGPath(rect: stringRect, transform: nil)    //attributedText.draw(in: stringRect)       let textFrame = CTFramesetterCreateWithAttributedString(attributedText)   let textRange = CFRangeMake(0, attributedText.length)   var pageRange = CFRange()   CTFramesetterSuggestFrameSizeWithConstraints(textFrame, textRange, nil, pageSize, &pageRange)       let frame = CTFramesetterCreateFrame(textFrame, pageRange, stringPath, nil)       CTFrameDraw(frame, cgContext )      }
Posted
by
Post not yet marked as solved
2 Replies
647 Views
Compiled existing app (ObJective-C) with XCode Version 13.0 beta 5 (13A5212g) without any source code changes. Tested on iPhone XR running iOS 15 beta 7(19A5337a) and noticed that the PDFKit Instance Method 'insertPage:atIndex:' generates incorrect results when appending multiple pages from input .pdf files into one consolidated output .pdf. The resulting output .pdf contains the total number of pages appended. However, all pages following the second page are a copy of the second page. Compiling the identical app with Xcode Version 12.5.1 (12E507) and running on another iPhone XR with iOS 14.7.1 does work as expected. The app also works as expected on iOS releases prior to version 14.6. Downloading the app from the App Store and executing it on the Phone with iOS 15(beta) shows the same issue. Has anyone experienced a similar problem using iOS 15 (beta) and found a solution. Any recommendations, including from Apple, are welcome. Thanks, DJ
Posted
by
Post marked as solved
1 Replies
537 Views
Hi! I'm creating an app for iOS and I want just to display a pdf from an external url with the width of 300 and height of 500. I tried with UiWebView but it is no longer supported. import SwiftUI let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 500, height: 300)) let targetURL = NSURL(string: "https://www.example.com/document.pdf")! let request = NSURLRequest(URL: targetURL) webView.loadRequest(request) struct StundenplanCard: View {     var body: some View {         VStack(spacing: 20) {             Text("Gimnazium") // here should be displayed the pdf         }     } } struct StundenplanCard_Previews: PreviewProvider {     static var previews: some View {         StundenplanCard().previewLayout(.fixed(width: 320, height: 640))     } }
Posted
by
Post marked as solved
1 Replies
852 Views
Hi! I'm trying to display a pdf inside my iOS app and I'm using the code displayed below, but for every self inside it I'm getting this error: Cannot find 'self' in scope // //  gimnaziumStundenplan.swift //  stundenplan // //  Created by Alex on 04/09/2021. // import UIKit import PDFKit private func createPdfView(withFrame frame: CGRect) -> PDFView {     let pdfView = PDFView(frame: frame)     pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]     pdfView.autoScales = true     return pdfView } private func createPdfDocument(forFileName fileName: String) -> PDFDocument? {     if let resourceUrl = self.resourceUrl(forFileName: fileName) {         return PDFDocument(url: resourceUrl)     }          if let resourceUrl = URL(string: "https://web.stanford.edu/class/archive/cs/cs161/cs161.1168/lecture4.pdf") {             return PDFDocument(url: resourceUrl)         }         return nil } private func displayPdf() {     let pdfView = self.createPdfView(withFrame: self.view.bounds)     if let pdfDocument = self.createPdfDocument(forFileName: "heaps") {         self.view.addSubview(pdfView)         pdfView.document = pdfDocument     } } }
Posted
by
Post not yet marked as solved
0 Replies
313 Views
Hello everyone, I want to extract text from a table inside a PDF. The layout is more or less known, the location isn't always exactly the same but the basic layout is similar in all PDFs. Simply extracting the text as an NSAttributedString or something similar won't do because it gives me the Strings in some weird order and not like line by line. Is there a way of extracting text from a pdf with the associated location? I know there are solutions out there with the integration of tabula (the Java thing), but I would prefer not to use those. Thanks a lot! Jonas
Posted
by
Post not yet marked as solved
0 Replies
269 Views
I am a new developer. I'm trying to see how to create a form (PDF) that can be filled out and then printed. I also need to have the form and data entered into the form to be saved.
Posted
by
Post not yet marked as solved
0 Replies
370 Views
I'm using a PDFView to show PDF file contents, after focus in a UITextField(such as search function),the PDFView can't show any text selection when I long press my finger on the iPhone's screen, can any Apple's PDFKit developer fix this problem ? ps: PDFKit has many strange selection behaviour from iOS 13, as the iOS change text selection interaction, it's buggy and disappointing
Posted
by
Post not yet marked as solved
0 Replies
289 Views
Hey there, I'm currently developing an app that consists of a full-screen PDFView, and I want the program to remember the position in the document before the view is dismissed so the user can pick up where they've left. I'm currently retrieving the location in the document with the PDFDestination object from PDFView.currentDestination, and restoring it using PDFView.go(to destination: PDFDestination). However, I realised that the view will not correctly restore it to the correct location. The following code is used to test out the issue, with a multi-page document: Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in self.DocumentView.go(to: self.DocumentView.currentDestination!) }) self.DocumentView is an instance of the PDFView class Upon execution, the page would spontaneously scroll down by a fixed offset, despite currentDestination remains unchanged. The same outcome was observed on an iPadOS 14.5 simulator and an iPadOS 15 iPad Air (Gen 4). It'd be great if somebody can help. Cheers, Lincoln
Posted
by