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
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 denz1612.
Last updated
.
Post not yet marked as solved
0 Replies
218 Views
I'm building an app that will have a lot of ebooks that will be sold individually, like the Kindle app on IOS. This is my first app build, so I have a lot of questions. To store the pdfs for the books, do I just have them stored with Firebase, and connect that with my app? How do I make each book purchasable? How would I download the pdf onto the user's phone once the book is purchased? Not onto his downloads folder, but so that the user can only access the downloaded pdf through the app. When adding in-app purchases to my app, do I add every single book as a product, or is "buying a book" just one product that is applicable to every book on the app? Any clarity would be greatly appreciated, thank you!
Posted Last updated
.
Post not yet marked as solved
1 Replies
458 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 Last updated
.
Post not yet marked as solved
2 Replies
385 Views
H i, I have used the PKCanvas view in my app. writing something in my PKCanvas View then convert it into a PDF. But adding the header for each page in PDF by using the following code,   let printable:CGRect = CGRect(x: 0, y: 50, width: 595 , height: 841)       render.setValue(NSValue(cgRect: page), forKey: "paperRect")       render.setValue(NSValue(cgRect: printable), forKey: "printableRect")       // 4. Create PDF context and draw       let pdfData = NSMutableData()       UIGraphicsBeginPDFContextToData(pdfData, CGRect(x:0,y:0,width: 595.2,height:841), nil)       for i in 1...render.numberOfPages {           UIGraphicsBeginPDFPage();           let bounds = UIGraphicsGetPDFContextBounds()           render.drawPage(at: i-1, in: bounds)       }       UIGraphicsEndPDFContext(); But while renderer the PKCanvas View it was broken, I think PKCanvas view rendering is not properly working in iOS 15.0,15.0.1 and 15.0.2. I have attached the following screenshot,
Posted Last updated
.
Post not yet marked as solved
0 Replies
222 Views
Hi I'm working on app using PDFKit I try to use function write(to:) in order to write the PDF in a specific folder. Here is the twist the url is in network drive using and the url looks like this: smb://User:Password@IP/ShareThis When I test the URL in the Mac Finder connect to server and its goes directly and open the shared folder I'm try to replicate this behavior using an iPad. But in the background. The documentation doesn't explain much Is this posible ?
Posted
by Josean.
Last updated
.
Post not yet marked as solved
0 Replies
271 Views
Are there any known issues sharing a PDF file from Adobe reader to a host app in iOS/objective-c? I have source code that works, but it appears to "work when it wants to work." Maybe 1/20 times or so the PDF is successfully passed back to my host app. I am essentially taking a PDF from an app directory (file:///private/var/mobile/Containers/Data/Application/EB6B8570-6422-49D8-BCBD-C68B9CBCF3C9/tmp/BBTempFileManager/sharedcopies/C2FB25ED-1414-49F0-8953-FFF3A4F6C76C/Sky.pdf) and saving it to a shared container so the file can be accessed from the host app. I'm using the shared container perfectly fine in other use cases.. The odd thing is in a debug view, every time, the correct file path is saved to the UserDefaults in the share extension, but when the same key is checked in the host app it only pulls the path from the UserDefaults 1/20 attempts. Otherwise it will be nil. As I said, in the same debug session on the ShareExtension I can see that the correct shared app container URL is pushed into UserDefaults... I've recently seen issues sharing from Safari (when Chrome supports the same share) so I thought I'd ask...
Posted
by mposchZ.
Last updated
.
Post not yet marked as solved
0 Replies
290 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 Last updated
.
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 Last updated
.
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 WolfJonas.
Last updated
.
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 alexsof.
Last updated
.
Post marked as solved
1 Replies
853 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 alexsof.
Last updated
.
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 DJHarter.
Last updated
.
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 bbrittain.
Last updated
.
Post marked as solved
1 Replies
546 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 Claude31.
Last updated
.
Post not yet marked as solved
0 Replies
656 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 Tahreem.
Last updated
.
Post not yet marked as solved
1 Replies
503 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 Claude31.
Last updated
.
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 Last updated
.