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
2 Replies
506 Views
when calling PDFPage.draw the first page of the pdf prints by repeating the first word over and over. Only in iOS15 all other iOS versions print the page normally. Resaving the document in acrobat with 'optimized' on fixes the issue. However, we can't guarantee our users will do that before uploading a pdf in our system.
Posted Last updated
.
Post not yet marked as solved
4 Replies
428 Views
Greetings, this may be an odd question but I was not able to find an answer to this. So I am developing this pure MacOS program for a client and one thing he wants is to create some PDFs along the way. Great chance I thought to try out this fancy Swift 5 with SwiftUI and so far it's going great, most of the program is up and running but I've hit a wall with the PDF generation, which I thought would be one of the easiest parts. Since it's a pure MacOS program, UIKit is not available but there is not a single tutorial out there for generating PDFs which is not using UIKit to do it. It seems people only want to create PDFs on iOS. Can someone give me a small breakdown or starter or tutorial or skeleton on how I would do that? Thanks and have a nice day
Posted
by Halest.
Last updated
.
Post not yet marked as solved
0 Replies
264 Views
Description I am having issue with UIImage "generated" from PDFPage via method .thumbnail(of:for). UIImage, which I later display in UIImageView does not respect rotation of the PDF page, but for iOS 13 only. When PDF page is rotated for example by 90° and presented in PDFView all is good and shown correctly. But when I want to take the UIImage (i.e. thumbnail) of the PDFPage and show it in UIImageView, for some reason, iOS 13 does not respect the initial rotation of the PDF page and present it in UIImageView incorrectly. Please behold on below sample code and example screenshots. Testing environment iOS 13 on simulator only, not having real device Xcode 13.1 Sample code for sake of shorter example, I force unwrap where optionals occur import UIKit import PDFKit class TestingViewController: UIViewController { lazy var imageView: UIImageView = { let iv = UIImageView() iv.translatesAutoresizingMaskIntoConstraints = false return iv }() // Pass URL of the PDF document when instantiating this VC init(withURL: URL) { super.init(nibName: nil, bundle: nil) let pdfDoc = PDFDocument(url: withURL) let pdfPage = pdfDoc!.page(at: 0) // Getting first page of the doc let pdfPageRect = pdfPage!.bounds(for: .mediaBox) imageView.image = pdfPage!.thumbnail(of: pdfPageRect.size, for: .mediaBox) // Getting the UIImage of the PDF page and assign it to the needed image view imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true print("\(pdfPage?.rotation)") // Prints the correct rotation value, even though UIImageView does not respect it } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Layout only override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemPink view.addSubview(imageView) NSLayoutConstraint.activate([ imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor), imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor), imageView.widthAnchor.constraint(equalToConstant: 350), imageView.heightAnchor.constraint(equalToConstant: 700), ]) } } Example screenshots from simulator ✅ Presented correctly (iOS 15) ❌ Presented incorrectly (iOS 13.2)
Posted Last updated
.
Post not yet marked as solved
1 Replies
551 Views
I have an application coded in objective-c that are using CoreGraphics and CGPDFDocument, it's a PDF reader. With the release of iOS 15 i'm having problems with the rendering of certain pages in certain PDF files. The problem is not present with PDFKit. I have also downloaded the ZoomingPDFViewer example (https://developer.apple.com/library/archive/samplecode/ZoomingPDFViewer/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010281) from the official apple documentation page and i see that the same thing happens. See the problem
Posted Last updated
.
Post marked as solved
28 Replies
6.5k Views
Hey guys, facing the issue that scanned documents on my iPhone 12 Pro Max with Files app are pretty bad quality. Guess it started with iOS 15 beta 3. Unfortunately issue still persists with current non beta iOS 15 release. It‘s the same on iPad OS 15. When I launch ‚scan with iPhone’ using Preview app on macOS quality is good as always. Hence looks like issue is related on files app or PDF processing on iPhone. Have anybody else seen the same? Thanx and cheers, Flory
Posted
by Flory421.
Last updated
.
Post not yet marked as solved
0 Replies
271 Views
I'm currently using PDFKit with Annotations in a unique way. The Annotations are Icons that serve as a link to an asset on a technical drawing. In this way, the user can view the asset details or find the asset from the asset details. I'm using flat images as annotation icons but would like to use 3D assets, preferably 'real' 3D assets where the prospective changes as the user moves the PDF. I'm curious on the best way to accomplish this task. The specific need for the PDF is because it holds the annotation text, which serves as a location indicator (X,Y) to place my Annotation image on top of. PDFs also hold a very high resolution at a relatively low file size, which is good for viewing the rest of the technical document. SceneKit Solution: From my research, I believe SceneKit would accomplish this by utilizing a PDF as a texture (or converting to high resolution PNG). However, I'm unsure how I would take the Annotation location in this method. I believe I can accomplish this by using PDFKit to extract the (X,Y) then place it in the comparable SceneKit scene, but have not tested this theory. I'm wondering if there is an easier or more direct way of accomplishing this task?
Posted
by rtnlsltn.
Last updated
.
Post not yet marked as solved
0 Replies
260 Views
After saving document via PDFKit (using PDFDocument function "write(to: )" ) some important information might be lost. For example, original document generated via Google Drive: "doc_original.pdf" https://www.dropbox.com/s/y0kfdlp2eo9zohs/doc_original.pdf?dl=0 Document after saving via PDFKit: "doc_saved_pdfkit.pdf" https://www.dropbox.com/s/fpegfcifb6yd1oc/doc_saved_pdfkit.pdf?dl=0 If you open files via any PDF viewer (ex. Preview), both looks the same. But if you try to search through doc_saved_pdfkit.pdf, the search won't work (in the original document it works) I've investigated this issue and found that when document saved via PDFDocument function "write(to: )" (even without any modifications) font parameter /ToUnicode being modified and information how to convert glyph codes to unicode is lost (see attached decoded stream contents). That's why it's impossible to find text or copy text from that doc. /ToUnicode stream content for "doc_original.pdf" /ToUnicode content for "doc_saved_pdfkit.pdf" The issue reproduces with Verdana and Roboto font families on iPhone on iOS15.1 and iOS15. Also I've checked on the simulator, it reproduces in iOS 13.5 as well
Posted
by somedev.
Last updated
.
Post not yet marked as solved
0 Replies
342 Views
I'm developing an app that allows you to view PDFs (music notes). I'm using PDFkit to display the pdf and need the pencilkit functionality while viewing the pdf (in the same way that you could mark up a book you are reading in iBooks when you click on the "Mark up" button). I am able to add a canvas on top of the pdf view however, I cannot save the canvas to be merged with the PDF. QuickLook offers a solution because the pencilkit looks to be built into it and works perfectly just the way I need it to, however, I don't need the other things that come with QuickLook. I desperately need your help with how I can get the pencilkit functionality on my custom PDF viewing app. At this point, I can't even find a solution for the "Mark up" button (pencil.tip.crop.circle) to be filled when tapped. Thank you in advance!
Posted
by Mikul29.
Last updated
.
Post not yet marked as solved
3 Replies
458 Views
If I want create pdf to var dokumnetpdf from picker, var dokumnetpdf is empty. How I do that? myCode:  var dokumnetpdf = PDFDocument() func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {         guard let myURL = urls.first else {             return         }         //print("import result : (myURL)")          let url: URL = myURL         //print("PDF link:(myURL)")         pdfname = url.lastPathComponent        // print("PDF name: (pdfname)")        // textfield.text = pdfname         dokumnetpdf = PDFDocument(url: urls.first!)     } Error LoG: import result : file:///private/var/mobile/Library/Mobile%20Documents/comappleCloudDocs/Desktop/rezervacefo.pdf PDF link:file:///private/var/mobile/Library/Mobile%20Documents/comappleCloudDocs/Desktop/rezervacefo.pdf PDF name: rezervacefo.pdf doc:nil AMC/DocumentUploadViewController.swift:68: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value 2022-01-07 11:11:49.159474+0100 AMC[71388:8043348] AMC/DocumentUploadViewController.swift:68: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Posted
by Radim007.
Last updated
.
Post not yet marked as solved
0 Replies
302 Views
Hi, I have some problems with rendering pdf pages in iOS 15.0. On iOS 14 and before iOS versions it’s working perfectly. But in iOS 15 and after releasing new versions I have faced the same issue. I have a PKCanvas View. Actually what I have to achieve is to convert that PKCanvas view into PDF. First I have written some words in the PKCanvas view using PencilKit and converted that PKCanvas view into an image and then I have converted that image into PDF. After that, I have loaded that PDF in WKWebview. There is no problem yet. But when I try to convert that WKWebview to again convert into PDF Using the rendering option there are mirror words are automatically occurring which error I have faced while creating the PDF from WKWebview by rendering option. let render = UIPrintPageRenderer()           render.addPrintFormatter(self.previewWebView.viewPrintFormatter(), startingAtPageAt: 0)         // 3. Assign paperRect and printableRect           let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpilet printable:CGRect = CGRect(x: 0, y: 0, width: 595.2, height: 841.8)        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(); How to resolve this issue? Please help us ASAP. Thanks in advance. For your reference, I have attached the PDF Page screenshot!
Posted Last updated
.
Post not yet marked as solved
0 Replies
174 Views
I am creating a PDF viewer. Is there any way I can programmatically determine which of the dictionaries is used (pre-installed in the iPad/iPhone; e.g., new Oxford American Dictionary, Chinese-English, Oxford Thatheras) for the look-up function?
Posted
by AKY2022.
Last updated
.
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 Last updated
.
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 MostaZa.
Last updated
.
Post not yet marked as solved
0 Replies
183 Views
// assign the print formatter to the print page renderer     let renderer = UIPrintPageRenderer()     renderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)     // assign paperRect and printableRect values     let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi     renderer.setValue(page, forKey: "paperRect")     renderer.setValue(page, forKey: "printableRect")     // create pdf context and draw each page     let pdfData = NSMutableData()     UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)     for i in 0..<renderer.numberOfPages {       UIGraphicsBeginPDFPage()       renderer.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())     }     UIGraphicsEndPDFContext();     // save data to a pdf file and return     guard nil != (try? pdfData.write(to: outputURL, options: .atomic))       else { fatalError("Error writing PDF data to file.") }     return pdfData as Data   }
Posted
by Big-Vi.
Last updated
.
Post not yet marked as solved
1 Replies
448 Views
Hello, fams! I have a probably stupid question for you guys who're coding in Swift. I'm extracting images from PDF with PDFKit and everything works well if there are a few pages. If there are many pages my app crashes and doesn't produce any crash log (I check error logs in XCode > Device and Simulators > Device log). I can guess that iOS terminates the app because methods I use are blocking UI thread for a long time. Could anyone suggest me what to do to improve that? Is there a way to achieve the same result using other methods that can be ran on a background thread? That's an example I found on the internet of how to extract image from PDF page: guard let path = Bundle.main.path(forResource: "filename", ofType: "pdf") else { return } let url = URL(fileURLWithPath: path) // Instantiate a `CGPDFDocument` from the PDF file's URL. guard let document = PDFDocument(url: url) else { return } // Get the first page of the PDF document. guard let page = document.page(at: 0) else { return } // Fetch the page rect for the page we want to render. let pageRect = page.bounds(for: .mediaBox) let renderer = UIGraphicsImageRenderer(size: pageRect.size) let img = renderer.image { ctx in // Set and fill the background color. UIColor.white.set() ctx.fill(CGRect(x: 0, y: 0, width: pageRect.width, height: pageRect.height)) // Translate the context so that we only draw the `cropRect`. ctx.cgContext.translateBy(x: -pageRect.origin.x, y: pageRect.size.height - pageRect.origin.y) // Flip the context vertically because the Core Graphics coordinate system starts from the bottom. ctx.cgContext.scaleBy(x: 1.0, y: -1.0) // Draw the PDF page. page.draw(with: .mediaBox, to: ctx.cgContext) }` Since I'm a .net developer and use C#, I've rewrote this code for my needs in C# and added loop to extract images from all PDF pages. Please, take a look: public IEnumerable<byte[]> ExtractImagesFromPdf(string pathToPdf) { using var data = NSData.FromFile(pathToPdf); using var doc = new PdfDocument(data); var bytesOfImages = new List<byte[]>(); for (int i = 0; i < doc.PageCount; i++) { var page = doc.GetPage(i); var pageRect = page.GetBoundsForBox(PdfDisplayBox.Media); using var renderer = new UIGraphicsImageRenderer(pageRect.Size); var img = renderer.CreateJpeg(100, (ctx) => { UIColor.White.SetColor(); ctx.FillRect(new CoreGraphics.CGRect(0, 0, pageRect.Width, pageRect.Height)); ctx.CGContext.TranslateCTM(-pageRect.X, pageRect.Size.Height - pageRect.Y); ctx.CGContext.ScaleCTM(1.0f, -1.0f); page.Draw(PdfDisplayBox.Media, ctx.CGContext); }); bytesOfImages.Add(img.ToArray()); } return bytesOfImages; } Thanks in advance!
Posted Last updated
.
Post not yet marked as solved
0 Replies
244 Views
Hi. I am trying to view a PDF document using react-pdf. This one particular PDF keeps breaking when I try to view it on iOS safari and chrome. It loads and displays the PDF for a second or two before breaking and navigating back to the previous page. I suspect this file is too huge because we are able to view other PDFs of a smaller file size. This file size is 6.9MB big, approximately 57 pages in length. It works perfectly fine on desktop browsers but breaks for iOS. Is there a recommended file size limit for viewing PDFs on iOS? Thanks for reading! Ian
Posted
by ianshalom.
Last updated
.
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 Tillmoss.
Last updated
.
Post not yet marked as solved
0 Replies
347 Views
I am attempting to add custom page drawing in a PDFDocument on macOS. I adapted the Custom Graphics iOS sample code (https://developer.apple.com/documentation/pdfkit/custom_graphics), which appears possible on macOS based on this evidently successful 2018 example: https://stackoverflow.com/questions/53415176/how-can-i-save-a-watermark-on-pdf-file-and-export-to-desktop-macos-mojave. To adapt the sample, I cut out UIGraphicsPushContext(context), UIGraphicsPopContext(), and the code required to flip the context, as its orientation was already correct. (I tried flipping it, but it did not solve my problem below.) What still works: After the PDFDocumentDelegate is set, the PDFView correctly displays the pages with custom drawing. Further, if I insert the PDFDocument’s pages into a new PDFDocument using insert(_:at:), the PDFView will display the second document with the custom drawing. The problem: The problem is that using either of the methods below will result in a document that contains all the expected elements, including PDFAnnotations, with this exception regarding the PDFPage subclass’s draw(with:to:): The original page can be drawn/removed by adding/removing super.draw(with:to:), but any other drawing in this method is not preserved, despite appearing correctly in the PDFView. These methods produce the problem: Using PDFDocument’s write(to:) to save to a file. The file is successfully saved with all elements except the custom drawing. Using PDFDocument’s dataRepresentation() to convert the document to Data and then using init(data:) to turn it back into a PDFDocument. The PDFDocument appears as before, except without the custom drawing. By contrast, on iOS/Mac Catalyst, both of these methods reproduce the custom drawing. What am I doing wrong here? Is it perhaps a bug, or is this drawing just not possible on macOS? I can paste the full code below if needed. I am using Xcode 13.0 and Big Sur 11.6 on a 2015 MBP.
Posted
by Dalia_.
Last updated
.