Display and manipulate PDF documents in your applications using PDFKit.

Posts under PDFKit tag

200 Posts

Post

Replies

Boosts

Views

Activity

Problems with PDFKit
How to fix it? Errors: "Cannot find type 'UIViewRepresentable' in scope" "Cannot find type 'Context' in scope" "Cannot find type 'Context' in scope" I tried: Re-installed the Xcode Re-started computer Great thanks. import SwiftUI import PDFKit struct PDFViewerView: UIViewRepresentable { var url: URL func makeUIView(context: Context) -> PDFView { let pdfView = PDFView() pdfView.document = PDFDocument(url: self.url) return pdfView } func updateUIView(_ uiView: PDFView, context: Context) { // Update the view. } } Xcode Version 15.0.1 (15A507)
1
0
800
Nov ’23
Rotating a page in a pdf file - and get a mirrored image
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
2
0
2.3k
Nov ’23
search for specific words inside a pdf document in Xcode
RB24 is my pdf doc. Im using a "view" inside my View Controller and the Class for that view is a PDFView. When I see the pdf on my app, I can't do a search inside the pdf document. How can I achieve that? When you open a pdf in your iPhone, iPhone uses an app that lets you do search and annotations on the pdf. Is there any way to do that for your app ? Any help will be greatly appreciated ! UIKit import PDFKit class ViewControllerRB: UIViewController { @IBOutlet weak var PDFViewRB: PDFView! override func viewDidLoad() { super.viewDidLoad() let url = Bundle.main.url(forResource: "RB24", withExtension: "pdf") if let pdfDocument = PDFDocument(url: url!) { PDFViewRB.autoScales = true PDFViewRB.displayMode = .singlePageContinuous PDFViewRB.displayDirection = .vertical PDFViewRB.document = pdfDocument
1
0
698
Nov ’23
.pageCurl
I am refreshing an old app that used the .pageCurl transition allowing user to drop pages in a multipage PDF file like turning the pages in a book. I am committed to using multipage PDF files. I can use UIPageViewController with .pageCurl transition when I am just using multiple UIViews supplied from my DataSource delegate. I cannot see how to use this with a multipage PDF file. I am committed to using SwiftUI and SwiftData which has new app targeting iOS 17. Can anyone point me to some (preferably Apple) example code to do this (that does not involve using non-Apple third party code).
0
0
555
Nov ’23
Document-based Apple App that can run on iOS, iPadOS, and macOS
I am new to developing native Apple apps and must familiarize myself with the Apple development frameworks. I am starting to create a personal document-based Apple App that can run on iOS, iPadOS, and macOS. The document will contain the following: HTML, PDF, images, video, and audio files. So, I think the document format could be HTML. I need the capability to read, edit (WYSIWYG Editor), save, and share documents with other users using the same app. The data is stored in the user's device and iCloud. I need guidance about what Apple framework I should use to edit the documents using WYSIWYG editing principles. I would really appreciate any recommendation you can provide. Many thanks for considering my request. Thank you so much for your attention and participation.
2
0
1.4k
Nov ’23
Highlighter texts in a pdf are not showing as expected in IOS
The specific pdf when opened in an macOS or web orA Adobe iOS App, it shows the highlighted texts as expected But when opened through any IOS app (except the adobe app) or our native app using pdfkit , the highlights are gone . It disappeared Even the pdf when opened in files app has this issue. Don’t know what’s the problem with the iOS. I have attached the screenshot for the pdf when opened in mac versus the pdf opened in any iOS app. **PDF when opened via Adobe App, ** Pdf when opened via our native app, Raised a feedback regarding this unexpected behaviour . FB Id - FB13326307 Do anyone faced the same issue? Anything am i missing regarding this>
0
0
719
Nov ’23
NavigationLink from PDF
Hi there, I am currently developing an app. I would like to make NavigationLinks from certain words inside an implemented .pdf-file to other Swift view files. Is there a possibility to do this? Here is my code: import PDFKit struct BasismassnahmenPDF: UIViewRepresentable { let pdfDocument: PDFDocument init(showing pdfDoc: PDFDocument) { self.pdfDocument = pdfDoc } func makeUIView(context: Context) -> PDFView { let pdfView = PDFView() pdfView.document = pdfDocument pdfView.autoScales = true return pdfView } func updateUIView(_ pdfView: PDFView, context: Context) { pdfView.document = pdfDocument pdfView.minScaleFactor = 0.6 pdfView.scaleFactor = pdfView.scaleFactorForSizeToFit } } struct Basismassnahmen: View { let pdfDoc: PDFDocument init() { let url = Bundle.main.url(forResource: "Basismassnahmen", withExtension: "pdf")! pdfDoc = PDFDocument(url: url)! } var body: some View { BasismassnahmenPDF(showing: pdfDoc) } } #Preview { Basismassnahmen() } Thank you so much for your help! Laurin
0
0
670
Oct ’23
Unable to open mach-O at path: default.metallib Error:2
Hey there, I am quite new to SwiftUI and currently trying to implement a pdf file into my app. When run the app on my iPhone the pdf file opens without any problems but I always get this Error: Unable to open mach-O at path: default.metallib Error:2 I do not actually understand the code completely I found on multiple websites, but what am I doing wrong? I attached my used code. Thanks for your help! Laurin import PDFKit struct PDFKitView: UIViewRepresentable { let pdfDocument: PDFDocument init(showing pdfDoc: PDFDocument) { self.pdfDocument = pdfDoc } func makeUIView(context: Context) -> PDFView { let pdfView = PDFView() pdfView.document = pdfDocument pdfView.autoScales = true return pdfView } func updateUIView(_ pdfView: PDFView, context: Context) { pdfView.document = pdfDocument } } struct Hypoglykaemie: View { let pdfDoc: PDFDocument init() { let url = Bundle.main.url(forResource: "hypoglykaemie", withExtension: "pdf")! pdfDoc = PDFDocument(url: url)! } var body: some View { PDFKitView(showing: pdfDoc) } } #Preview { Hypoglykaemie() }
2
1
5.3k
Oct ’23
Hidden fields / annotations aren't hidden
I'm using PDFKit to show a PDF which contains some hidden fields. Unfortunately, PDFKit seems to ignore that property, annotation.shouldDisplay is always YES. I have to set shouldDisplay by my own depending on the annotation's internal flags: // see Chapter 8.4.2 Annotation Flags in PDF Reference for PDF 1.7 // https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/pdfreference1.7old.pdf static const NSUInteger PDFAnnotationFlagInvisible = 1; static const NSUInteger PDFAnnotationFlagHidden = 1 << 1; // ... for (PDFAnnotation* annotation in page.annotations) { id value = [annotation valueForAnnotationKey:PDFAnnotationKeyFlags]; if (value != nil) { NSInteger annotationFlags = [value integerValue]; if (annotationFlags & (PDFAnnotationFlagInvisible | PDFAnnotationFlagHidden)) { annotation.shouldDisplay = NO; } } } It doesn't feel right that this snippet is needed. So is this a bug / known issue in PDFKit or is my PDF somehow "wrong".
1
0
999
Oct ’23
PDF forms with Radio Buttons Do Not Properly Save Properly, Resulting in Loss of User Input
The Problem In the Preview app in macOS (or the Files app in iOS and iPadOS), when a user selects a radio button to "On", the radio button appears to behave as expected (with related radio buttons, sharing the same parent form field, appearing to turn "Off"). Also, as expected, the app indicates that the user has edited the PDF and, as such, is able to save and close the file as normal. On re-opening the file, the radio buttons seem to have been reset and user input lost. What is Happening Related radio button annotation widgets share the same parent form field. In the PDF 1.7 specification (ISO PDF32000-2008, s. 12.7.4.2.4), the parent form field object holds the field name property (T), the name object of the appearance state of the kid object currently selected (V), as well as an array of the references to the related radio button kid objects (Kids). Each kid object holds a reference to the parent object (Parent). When the user selects a radio button to be on, the V property is updated in the parent object accordingly. On saving the PDF, an incremental update to the file is made with an updated copy of the kid object, corresponding to the selected radio box, created. The kid object created for the updated radio box, however, is updated incorrectly with the Parent object reference removed and the properties that ought to reside with the parent object (for V, T, and FT), instead, incorrectly written/merged into the kid object itself. The original parent object (belonging to the shared field form) is not updated with the incremental update in any way. Impact on User Experience Radio buttons are not functional, with user-input not properly saved. As such, using Preview to complete a PDF form with radio buttons is not possible. On re-opening the PDF, user input to the state of radio buttons appear not to have been saved. Affected Apps/OSs: Preview (macOS 12 and above) and Files (iOS 16 and iPadOS 16) Related Sample of Code Radio button annotation widget object (11 0 obj) and form field parent object (16 0 obj) in original PDF file: 11 0 obj << /Border [ 0 0 0 ] /Rect [ 433 405 453 425 ] /F 4 /BS 13 0 R /Subtype /Widget /DA (/Helvetica 13 Tf 0 g) /MK 14 0 R /C [ 0 ] /AP 15 0 R /M (D:20230803164805Z00'00') /AS /Off /Parent 16 0 R /Type /Annot /Ff 32768 >> endobj 16 0 obj << /V / /Kids [ 10 0 R 11 0 R ] /T (button2) /FT /Btn >> endobj 15 0 obj << /N 17 0 R >> endobj 17 0 obj << /Ted 18 0 R /Off 20 0 R >> endobj Copy of object (11 0 obj) created with incremental update of PDF, included in saved file following user selection: 11 0 obj << /C [ 0 ] /FT /Btn /F 4 /BS << /W 0 >> /Subtype /Widget /DA (//Helvetica 13 Tf 0 g) /Type /Annot /Border [ 0 0 0 ] /M (D:20230803164805Z00'00') /Rect [ 433 405 453 425 ] /MK << /BG [ 0.75 ] >> /AP << /N << /Off 53 0 R /Ted 57 0 R >> >> /T (button2) /AS /Ted /Ff 32768 /V /Ted >> endobj A bug report, describing as much, was submitted to Apple (FB9978281).
1
0
1.8k
Oct ’23
PDFKit crash on iOS 17
Currently I am displaying a pdf in one of my apps using the PDFKit. When I tap on the pdf view there is a strange crash happening related to the the text ranges conversion. No issues with iOS 16, seems to happen only in iOS 17 0x0000000117092fa1 in void PageLayout::ConvertTextRangesToStringRanges<std::__1::span<CFRange, 18446744073709551615ul>, std::__1::back_insert_iterator<std::__1::vector<CFRange, std::__1::allocator<CFRange> > > >(std::__1::span<CFRange, 18446744073709551615ul>&&, std::__1::back_insert_iterator<std::__1::vector<CFRange, std::__1::allocator<CFRange> > >&&) const ()
1
0
950
Oct ’23
Please tell me how to remove highlight from editmenu items of PDFView
I use PDFView to show PDF files. A PDFView has several editmenu items in advance. Among them, I want to remove the highlight from the item. So, I made PDFView subclass and overrode canPerformAction and buildMenu respectively, but I could not remove the highlight item from the editmenu. If you know how to remove the highlight item, please let me know. Thanks for reading my post.
4
1
1.1k
Oct ’23
Link inside PDFDocument using NSAttributedString
I have the following code in a prototype application that displays text with a link and presents it in a PDFView. let a4SizePageRect = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) let renderer = UIGraphicsPDFRenderer(bounds: a4SizePageRect) let title = "Some Title Link" let attributedTitle = NSMutableAttributedString(string: title, attributes: [ .font: UIFont.boldSystemFont(ofSize: 24), .link: "<insert here some correct link>", .underlineStyle: NSUnderlineStyle.single.rawValue ]) let data = renderer.pdfData { ctx in ctx.beginPage() attributedTitle.draw(in: a4SizePageRect.insetBy(dx: 25, dy: 25)) } pdfView.document = PDFDocument(data: data) The link only works on iOS 15 versions, but does not work on iOS 16.4 and iOS 17 RC. Based on the documentation for the property and NSAttributedString, the link attribute should still work. Has NSAttributedString stopped supporting NSAttributedString.Key.link in recent versions of iOS?
1
1
665
Oct ’23
Notes App with pdf
I have a problem with the Notes app on ios17. When I open a pdf file that I created from scanning a document with my iPhone 14, I can't select any text from the pdf. This makes it impossible to copy and paste anything from my pdf. Is anyone else having this issue?
2
0
582
Sep ’23
macOS 14.0 Sonoma: Pages and Keynote Do Not Export Equations Correctly to PDF
I have a 52-page document authored in Pages that contains many equations, most of them pertaining to matrix algebra with many subscripts. Using Pages v13.2 on macOS 14.0 Sonoma (23A344), the exported PDF version of the document does not render the equations correctly. In particular, equations containing a vertical bar "|" are rendered without the vertical bar in the PDF document. For example, an equation for a probability expression of "P(x|y)" gets exported to PDF as "P(x y)". In particular, the Pages "blahtex" form for a discrete-time system equation is \mathbf{x}_{k+1} = \mathbf{\Phi}_{k+1|k} \mathbf{x}_k + \mathbf{u}_k + \mathbf{\Gamma}_{k+1|k} \mathbf{w}_k In Pages, this gets correctly rendered as whereas, in the exported PDF document, it gets incorrectly rendered as Also, using \vert or \mid to generate the "|" in the equation does not help; the PDF export is still missing the "|" symbol. If I save the document in Microsoft Word format and then export to PDF, the equations are rendered correctly. Reverting to Pages v13.1 from Time Machine does not fix the issue; the exported PDF is still wrong. It should be noted that when I used Pages v13.1 in Ventura, exported PDF equations rendered correctly. There may be other formulations that are broken that I have not yet encountered. In addition, my equations in Keynote suffer from the same problem when I export them to PDF. I know that macOS Sonoma removed EPS support, but it looks like other things got broken with this change. I don't want to convert all of my Pages documents to Microsoft Word, but unless this gets fixed, Pages has become useless to me for technical documentation. I'm an engineer with a lot of documents, so this has pretty much brought my workflow to a halt. I've submitted a bug report to Apple (FB13208972), but I am interested if anyone else is experiencing this problem.
1
1
1k
Sep ’23
PDFKit Crash Problem
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?
6
3
2.5k
Sep ’23
Generate a PDF from HTML template using WKWebview
Hello, We have functionality in an existing app, have to generate a pdf and it should be printable in the A4. The PDF is almost 8 to 10 pages I have applied below solution: Loading the HTML template on the WKwebview and doing a few operations on the content and converting it into a pdf. Converting the HTML into a string Replacing a few data with dynamic content Issue: The solutions worked fine in the previous OS(14.5,15.5,16.1), it is not working on the latest os 16.6 The Table background CSS is not Rendering. I have tried both Inline and external CSS loading but still facing the same issue. Approch1: func createPDF(formmatter: UIViewPrintFormatter, filename: String) -> String { let attributedString = NSAttributedString(string: "This is a test", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red]) let printFormatter = UISimpleTextPrintFormatter(attributedText: attributedString) let render = UIPrintPageRenderer() render.addPrintFormatter(printFormatter, startingAtPageAt: 0) // 2. Assign print formatter to UIPrintPageRenderer //let render = UIPrintPageRenderer() render.addPrintFormatter(formmatter, startingAtPageAt: 0) // 3. Assign paperRect and printableRect let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi let printable = page.insetBy(dx: 20, dy: 20) //let printable = page.inset(by: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)); 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.zero, nil) for i in 1...render.numberOfPages { UIGraphicsBeginPDFPage(); let bounds = UIGraphicsGetPDFContextBounds() render.drawPage(at: i - 1, in: bounds) } UIGraphicsEndPDFContext(); // 5. Save PDF file var dst = self.getDestinationPath(1) if dst.contains("file://") { dst = dst.replacingOccurrences(of: "file://", with: "") } //let path = "\(NSTemporaryDirectory())\(filename).pdf" pdfData.write(toFile: dst, atomically: true) print("open \(dst)") return dst } } Approach2: But the pdf is Generating in a single page not multiple and it's not printable using the below solution. func createPDFMethod(webView: WKWebView, title:String="samplepdf"){ let pdfConfiguration = WKPDFConfiguration() /// Using `webView.scrollView.frame` allows us to capture the // entire page, not just the visible portion pdfConfiguration.rect = CGRect(x: 0, y: 0, width: webView.scrollView.contentSize.width, height: webView.scrollView.contentSize.height) webView.createPDF(configuration: pdfConfiguration) { result in switch result { case .success(let data): // Creates a path to the downloads directory DispatchQueue.main.async { let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL let pdfNameFromUrl = "\(title).pdf" let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrl) do { try data.write(to: actualPath, options: .atomic) print("pdf successfully saved!") } catch { print("Pdf could not be saved") } } case .failure(let failure): print(failure.localizedDescription) } } } It seems the issue is with UIGraphics or WKwebview formaters. could you please help me to resolve this issue?
2
1
2.1k
Sep ’23
PDFKit page render issue
Hi there, I am currently facing an issue with PDFKit page rendering. In one of my application, I have to open annoted PDF for reading and when user tap on particular annotation, I have to jump certain number of pages in same PDF to open the new desired page. Example: User is on page 2 and when user tap on menu button, I need to navigate directly on page number 8. With above scenario, my application takes a while to load page number 8 and User can see white screen before loading PDF page. When I checked console log, I can see following as an error. F.I: App requires to use usePageViewController for pagination. I am using as per following: _pdfView = [[PDFView alloc] initWithFrame:[UIScreen mainScreen].bounds]; [view addSubview:self.pdfView]; self.pdfView.delegate = self; [self.pdfView setAutoScales:true]; [self.pdfView setDisplayDirection:kPDFDisplayDirectionHorizontal]; [self.pdfView usePageViewController:true withViewOptions:nil]; [self.pdfView setBackgroundColor:UIColor.whiteColor]; Warning: Unable to complete drawing page index 24 on time as a request to forceUpdateActivePageIndex:withMaxDuration: 0.02 I hope if someone can help me on that Thanks.
0
0
867
Sep ’23
Crash in PDF Kit
Crashed: com.apple.main-thread 0 CoreFoundation 0x7c59c CFArrayGetCount + 8 1 CorePDF 0x28c1c CGPDFTaggedNodeEnumerateChildren + 52 2 CorePDF 0x28b70 CGPDFTaggedNodeGetBounds + 244 3 PDFKit 0x6400 (Missing UUID 4dedb563f2df3dceae5066d6b4718b9f) 4 UIAccessibility 0x818e0 ___axuiElementForNotificationData_block_invoke + 56
2
1
1.4k
Aug ’23
Problems with PDFKit
How to fix it? Errors: "Cannot find type 'UIViewRepresentable' in scope" "Cannot find type 'Context' in scope" "Cannot find type 'Context' in scope" I tried: Re-installed the Xcode Re-started computer Great thanks. import SwiftUI import PDFKit struct PDFViewerView: UIViewRepresentable { var url: URL func makeUIView(context: Context) -> PDFView { let pdfView = PDFView() pdfView.document = PDFDocument(url: self.url) return pdfView } func updateUIView(_ uiView: PDFView, context: Context) { // Update the view. } } Xcode Version 15.0.1 (15A507)
Replies
1
Boosts
0
Views
800
Activity
Nov ’23
PDF Filler functionality for iPadOS from WWDC23
Hi there, I have watched the keynote of WWDC23 and like to have technical information on how to implement Filling forms for iPad OS using PDFKIT into our App. I have reviewed PDFKit API documentation, but there are no any documentation about how to use that technology and no any changes to API. Thanks, Eduard
Replies
0
Boosts
0
Views
645
Activity
Nov ’23
Rotating a page in a pdf file - and get a mirrored image
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
Replies
2
Boosts
0
Views
2.3k
Activity
Nov ’23
search for specific words inside a pdf document in Xcode
RB24 is my pdf doc. Im using a "view" inside my View Controller and the Class for that view is a PDFView. When I see the pdf on my app, I can't do a search inside the pdf document. How can I achieve that? When you open a pdf in your iPhone, iPhone uses an app that lets you do search and annotations on the pdf. Is there any way to do that for your app ? Any help will be greatly appreciated ! UIKit import PDFKit class ViewControllerRB: UIViewController { @IBOutlet weak var PDFViewRB: PDFView! override func viewDidLoad() { super.viewDidLoad() let url = Bundle.main.url(forResource: "RB24", withExtension: "pdf") if let pdfDocument = PDFDocument(url: url!) { PDFViewRB.autoScales = true PDFViewRB.displayMode = .singlePageContinuous PDFViewRB.displayDirection = .vertical PDFViewRB.document = pdfDocument
Replies
1
Boosts
0
Views
698
Activity
Nov ’23
.pageCurl
I am refreshing an old app that used the .pageCurl transition allowing user to drop pages in a multipage PDF file like turning the pages in a book. I am committed to using multipage PDF files. I can use UIPageViewController with .pageCurl transition when I am just using multiple UIViews supplied from my DataSource delegate. I cannot see how to use this with a multipage PDF file. I am committed to using SwiftUI and SwiftData which has new app targeting iOS 17. Can anyone point me to some (preferably Apple) example code to do this (that does not involve using non-Apple third party code).
Replies
0
Boosts
0
Views
555
Activity
Nov ’23
Document-based Apple App that can run on iOS, iPadOS, and macOS
I am new to developing native Apple apps and must familiarize myself with the Apple development frameworks. I am starting to create a personal document-based Apple App that can run on iOS, iPadOS, and macOS. The document will contain the following: HTML, PDF, images, video, and audio files. So, I think the document format could be HTML. I need the capability to read, edit (WYSIWYG Editor), save, and share documents with other users using the same app. The data is stored in the user's device and iCloud. I need guidance about what Apple framework I should use to edit the documents using WYSIWYG editing principles. I would really appreciate any recommendation you can provide. Many thanks for considering my request. Thank you so much for your attention and participation.
Replies
2
Boosts
0
Views
1.4k
Activity
Nov ’23
Highlighter texts in a pdf are not showing as expected in IOS
The specific pdf when opened in an macOS or web orA Adobe iOS App, it shows the highlighted texts as expected But when opened through any IOS app (except the adobe app) or our native app using pdfkit , the highlights are gone . It disappeared Even the pdf when opened in files app has this issue. Don’t know what’s the problem with the iOS. I have attached the screenshot for the pdf when opened in mac versus the pdf opened in any iOS app. **PDF when opened via Adobe App, ** Pdf when opened via our native app, Raised a feedback regarding this unexpected behaviour . FB Id - FB13326307 Do anyone faced the same issue? Anything am i missing regarding this>
Replies
0
Boosts
0
Views
719
Activity
Nov ’23
NavigationLink from PDF
Hi there, I am currently developing an app. I would like to make NavigationLinks from certain words inside an implemented .pdf-file to other Swift view files. Is there a possibility to do this? Here is my code: import PDFKit struct BasismassnahmenPDF: UIViewRepresentable { let pdfDocument: PDFDocument init(showing pdfDoc: PDFDocument) { self.pdfDocument = pdfDoc } func makeUIView(context: Context) -> PDFView { let pdfView = PDFView() pdfView.document = pdfDocument pdfView.autoScales = true return pdfView } func updateUIView(_ pdfView: PDFView, context: Context) { pdfView.document = pdfDocument pdfView.minScaleFactor = 0.6 pdfView.scaleFactor = pdfView.scaleFactorForSizeToFit } } struct Basismassnahmen: View { let pdfDoc: PDFDocument init() { let url = Bundle.main.url(forResource: "Basismassnahmen", withExtension: "pdf")! pdfDoc = PDFDocument(url: url)! } var body: some View { BasismassnahmenPDF(showing: pdfDoc) } } #Preview { Basismassnahmen() } Thank you so much for your help! Laurin
Replies
0
Boosts
0
Views
670
Activity
Oct ’23
Unable to open mach-O at path: default.metallib Error:2
Hey there, I am quite new to SwiftUI and currently trying to implement a pdf file into my app. When run the app on my iPhone the pdf file opens without any problems but I always get this Error: Unable to open mach-O at path: default.metallib Error:2 I do not actually understand the code completely I found on multiple websites, but what am I doing wrong? I attached my used code. Thanks for your help! Laurin import PDFKit struct PDFKitView: UIViewRepresentable { let pdfDocument: PDFDocument init(showing pdfDoc: PDFDocument) { self.pdfDocument = pdfDoc } func makeUIView(context: Context) -> PDFView { let pdfView = PDFView() pdfView.document = pdfDocument pdfView.autoScales = true return pdfView } func updateUIView(_ pdfView: PDFView, context: Context) { pdfView.document = pdfDocument } } struct Hypoglykaemie: View { let pdfDoc: PDFDocument init() { let url = Bundle.main.url(forResource: "hypoglykaemie", withExtension: "pdf")! pdfDoc = PDFDocument(url: url)! } var body: some View { PDFKitView(showing: pdfDoc) } } #Preview { Hypoglykaemie() }
Replies
2
Boosts
1
Views
5.3k
Activity
Oct ’23
Hidden fields / annotations aren't hidden
I'm using PDFKit to show a PDF which contains some hidden fields. Unfortunately, PDFKit seems to ignore that property, annotation.shouldDisplay is always YES. I have to set shouldDisplay by my own depending on the annotation's internal flags: // see Chapter 8.4.2 Annotation Flags in PDF Reference for PDF 1.7 // https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/pdfreference1.7old.pdf static const NSUInteger PDFAnnotationFlagInvisible = 1; static const NSUInteger PDFAnnotationFlagHidden = 1 << 1; // ... for (PDFAnnotation* annotation in page.annotations) { id value = [annotation valueForAnnotationKey:PDFAnnotationKeyFlags]; if (value != nil) { NSInteger annotationFlags = [value integerValue]; if (annotationFlags & (PDFAnnotationFlagInvisible | PDFAnnotationFlagHidden)) { annotation.shouldDisplay = NO; } } } It doesn't feel right that this snippet is needed. So is this a bug / known issue in PDFKit or is my PDF somehow "wrong".
Replies
1
Boosts
0
Views
999
Activity
Oct ’23
PDF forms with Radio Buttons Do Not Properly Save Properly, Resulting in Loss of User Input
The Problem In the Preview app in macOS (or the Files app in iOS and iPadOS), when a user selects a radio button to "On", the radio button appears to behave as expected (with related radio buttons, sharing the same parent form field, appearing to turn "Off"). Also, as expected, the app indicates that the user has edited the PDF and, as such, is able to save and close the file as normal. On re-opening the file, the radio buttons seem to have been reset and user input lost. What is Happening Related radio button annotation widgets share the same parent form field. In the PDF 1.7 specification (ISO PDF32000-2008, s. 12.7.4.2.4), the parent form field object holds the field name property (T), the name object of the appearance state of the kid object currently selected (V), as well as an array of the references to the related radio button kid objects (Kids). Each kid object holds a reference to the parent object (Parent). When the user selects a radio button to be on, the V property is updated in the parent object accordingly. On saving the PDF, an incremental update to the file is made with an updated copy of the kid object, corresponding to the selected radio box, created. The kid object created for the updated radio box, however, is updated incorrectly with the Parent object reference removed and the properties that ought to reside with the parent object (for V, T, and FT), instead, incorrectly written/merged into the kid object itself. The original parent object (belonging to the shared field form) is not updated with the incremental update in any way. Impact on User Experience Radio buttons are not functional, with user-input not properly saved. As such, using Preview to complete a PDF form with radio buttons is not possible. On re-opening the PDF, user input to the state of radio buttons appear not to have been saved. Affected Apps/OSs: Preview (macOS 12 and above) and Files (iOS 16 and iPadOS 16) Related Sample of Code Radio button annotation widget object (11 0 obj) and form field parent object (16 0 obj) in original PDF file: 11 0 obj << /Border [ 0 0 0 ] /Rect [ 433 405 453 425 ] /F 4 /BS 13 0 R /Subtype /Widget /DA (/Helvetica 13 Tf 0 g) /MK 14 0 R /C [ 0 ] /AP 15 0 R /M (D:20230803164805Z00'00') /AS /Off /Parent 16 0 R /Type /Annot /Ff 32768 >> endobj 16 0 obj << /V / /Kids [ 10 0 R 11 0 R ] /T (button2) /FT /Btn >> endobj 15 0 obj << /N 17 0 R >> endobj 17 0 obj << /Ted 18 0 R /Off 20 0 R >> endobj Copy of object (11 0 obj) created with incremental update of PDF, included in saved file following user selection: 11 0 obj << /C [ 0 ] /FT /Btn /F 4 /BS << /W 0 >> /Subtype /Widget /DA (//Helvetica 13 Tf 0 g) /Type /Annot /Border [ 0 0 0 ] /M (D:20230803164805Z00'00') /Rect [ 433 405 453 425 ] /MK << /BG [ 0.75 ] >> /AP << /N << /Off 53 0 R /Ted 57 0 R >> >> /T (button2) /AS /Ted /Ff 32768 /V /Ted >> endobj A bug report, describing as much, was submitted to Apple (FB9978281).
Replies
1
Boosts
0
Views
1.8k
Activity
Oct ’23
PDFKit crash on iOS 17
Currently I am displaying a pdf in one of my apps using the PDFKit. When I tap on the pdf view there is a strange crash happening related to the the text ranges conversion. No issues with iOS 16, seems to happen only in iOS 17 0x0000000117092fa1 in void PageLayout::ConvertTextRangesToStringRanges<std::__1::span<CFRange, 18446744073709551615ul>, std::__1::back_insert_iterator<std::__1::vector<CFRange, std::__1::allocator<CFRange> > > >(std::__1::span<CFRange, 18446744073709551615ul>&&, std::__1::back_insert_iterator<std::__1::vector<CFRange, std::__1::allocator<CFRange> > >&&) const ()
Replies
1
Boosts
0
Views
950
Activity
Oct ’23
Please tell me how to remove highlight from editmenu items of PDFView
I use PDFView to show PDF files. A PDFView has several editmenu items in advance. Among them, I want to remove the highlight from the item. So, I made PDFView subclass and overrode canPerformAction and buildMenu respectively, but I could not remove the highlight item from the editmenu. If you know how to remove the highlight item, please let me know. Thanks for reading my post.
Replies
4
Boosts
1
Views
1.1k
Activity
Oct ’23
Link inside PDFDocument using NSAttributedString
I have the following code in a prototype application that displays text with a link and presents it in a PDFView. let a4SizePageRect = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) let renderer = UIGraphicsPDFRenderer(bounds: a4SizePageRect) let title = "Some Title Link" let attributedTitle = NSMutableAttributedString(string: title, attributes: [ .font: UIFont.boldSystemFont(ofSize: 24), .link: "<insert here some correct link>", .underlineStyle: NSUnderlineStyle.single.rawValue ]) let data = renderer.pdfData { ctx in ctx.beginPage() attributedTitle.draw(in: a4SizePageRect.insetBy(dx: 25, dy: 25)) } pdfView.document = PDFDocument(data: data) The link only works on iOS 15 versions, but does not work on iOS 16.4 and iOS 17 RC. Based on the documentation for the property and NSAttributedString, the link attribute should still work. Has NSAttributedString stopped supporting NSAttributedString.Key.link in recent versions of iOS?
Replies
1
Boosts
1
Views
665
Activity
Oct ’23
Notes App with pdf
I have a problem with the Notes app on ios17. When I open a pdf file that I created from scanning a document with my iPhone 14, I can't select any text from the pdf. This makes it impossible to copy and paste anything from my pdf. Is anyone else having this issue?
Replies
2
Boosts
0
Views
582
Activity
Sep ’23
macOS 14.0 Sonoma: Pages and Keynote Do Not Export Equations Correctly to PDF
I have a 52-page document authored in Pages that contains many equations, most of them pertaining to matrix algebra with many subscripts. Using Pages v13.2 on macOS 14.0 Sonoma (23A344), the exported PDF version of the document does not render the equations correctly. In particular, equations containing a vertical bar "|" are rendered without the vertical bar in the PDF document. For example, an equation for a probability expression of "P(x|y)" gets exported to PDF as "P(x y)". In particular, the Pages "blahtex" form for a discrete-time system equation is \mathbf{x}_{k+1} = \mathbf{\Phi}_{k+1|k} \mathbf{x}_k + \mathbf{u}_k + \mathbf{\Gamma}_{k+1|k} \mathbf{w}_k In Pages, this gets correctly rendered as whereas, in the exported PDF document, it gets incorrectly rendered as Also, using \vert or \mid to generate the "|" in the equation does not help; the PDF export is still missing the "|" symbol. If I save the document in Microsoft Word format and then export to PDF, the equations are rendered correctly. Reverting to Pages v13.1 from Time Machine does not fix the issue; the exported PDF is still wrong. It should be noted that when I used Pages v13.1 in Ventura, exported PDF equations rendered correctly. There may be other formulations that are broken that I have not yet encountered. In addition, my equations in Keynote suffer from the same problem when I export them to PDF. I know that macOS Sonoma removed EPS support, but it looks like other things got broken with this change. I don't want to convert all of my Pages documents to Microsoft Word, but unless this gets fixed, Pages has become useless to me for technical documentation. I'm an engineer with a lot of documents, so this has pretty much brought my workflow to a halt. I've submitted a bug report to Apple (FB13208972), but I am interested if anyone else is experiencing this problem.
Replies
1
Boosts
1
Views
1k
Activity
Sep ’23
PDFKit Crash Problem
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?
Replies
6
Boosts
3
Views
2.5k
Activity
Sep ’23
Generate a PDF from HTML template using WKWebview
Hello, We have functionality in an existing app, have to generate a pdf and it should be printable in the A4. The PDF is almost 8 to 10 pages I have applied below solution: Loading the HTML template on the WKwebview and doing a few operations on the content and converting it into a pdf. Converting the HTML into a string Replacing a few data with dynamic content Issue: The solutions worked fine in the previous OS(14.5,15.5,16.1), it is not working on the latest os 16.6 The Table background CSS is not Rendering. I have tried both Inline and external CSS loading but still facing the same issue. Approch1: func createPDF(formmatter: UIViewPrintFormatter, filename: String) -> String { let attributedString = NSAttributedString(string: "This is a test", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red]) let printFormatter = UISimpleTextPrintFormatter(attributedText: attributedString) let render = UIPrintPageRenderer() render.addPrintFormatter(printFormatter, startingAtPageAt: 0) // 2. Assign print formatter to UIPrintPageRenderer //let render = UIPrintPageRenderer() render.addPrintFormatter(formmatter, startingAtPageAt: 0) // 3. Assign paperRect and printableRect let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi let printable = page.insetBy(dx: 20, dy: 20) //let printable = page.inset(by: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)); 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.zero, nil) for i in 1...render.numberOfPages { UIGraphicsBeginPDFPage(); let bounds = UIGraphicsGetPDFContextBounds() render.drawPage(at: i - 1, in: bounds) } UIGraphicsEndPDFContext(); // 5. Save PDF file var dst = self.getDestinationPath(1) if dst.contains("file://") { dst = dst.replacingOccurrences(of: "file://", with: "") } //let path = "\(NSTemporaryDirectory())\(filename).pdf" pdfData.write(toFile: dst, atomically: true) print("open \(dst)") return dst } } Approach2: But the pdf is Generating in a single page not multiple and it's not printable using the below solution. func createPDFMethod(webView: WKWebView, title:String="samplepdf"){ let pdfConfiguration = WKPDFConfiguration() /// Using `webView.scrollView.frame` allows us to capture the // entire page, not just the visible portion pdfConfiguration.rect = CGRect(x: 0, y: 0, width: webView.scrollView.contentSize.width, height: webView.scrollView.contentSize.height) webView.createPDF(configuration: pdfConfiguration) { result in switch result { case .success(let data): // Creates a path to the downloads directory DispatchQueue.main.async { let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL let pdfNameFromUrl = "\(title).pdf" let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrl) do { try data.write(to: actualPath, options: .atomic) print("pdf successfully saved!") } catch { print("Pdf could not be saved") } } case .failure(let failure): print(failure.localizedDescription) } } } It seems the issue is with UIGraphics or WKwebview formaters. could you please help me to resolve this issue?
Replies
2
Boosts
1
Views
2.1k
Activity
Sep ’23
PDFKit page render issue
Hi there, I am currently facing an issue with PDFKit page rendering. In one of my application, I have to open annoted PDF for reading and when user tap on particular annotation, I have to jump certain number of pages in same PDF to open the new desired page. Example: User is on page 2 and when user tap on menu button, I need to navigate directly on page number 8. With above scenario, my application takes a while to load page number 8 and User can see white screen before loading PDF page. When I checked console log, I can see following as an error. F.I: App requires to use usePageViewController for pagination. I am using as per following: _pdfView = [[PDFView alloc] initWithFrame:[UIScreen mainScreen].bounds]; [view addSubview:self.pdfView]; self.pdfView.delegate = self; [self.pdfView setAutoScales:true]; [self.pdfView setDisplayDirection:kPDFDisplayDirectionHorizontal]; [self.pdfView usePageViewController:true withViewOptions:nil]; [self.pdfView setBackgroundColor:UIColor.whiteColor]; Warning: Unable to complete drawing page index 24 on time as a request to forceUpdateActivePageIndex:withMaxDuration: 0.02 I hope if someone can help me on that Thanks.
Replies
0
Boosts
0
Views
867
Activity
Sep ’23
Crash in PDF Kit
Crashed: com.apple.main-thread 0 CoreFoundation 0x7c59c CFArrayGetCount + 8 1 CorePDF 0x28c1c CGPDFTaggedNodeEnumerateChildren + 52 2 CorePDF 0x28b70 CGPDFTaggedNodeGetBounds + 244 3 PDFKit 0x6400 (Missing UUID 4dedb563f2df3dceae5066d6b4718b9f) 4 UIAccessibility 0x818e0 ___axuiElementForNotificationData_block_invoke + 56
Replies
2
Boosts
1
Views
1.4k
Activity
Aug ’23