Display and manipulate PDF documents in your applications using PDFKit.

Posts under PDFKit tag

200 Posts

Post

Replies

Boosts

Views

Activity

iOS/iPadOS 17.2 Bug in PDFKit duplicates content of filled PDF form fields
The following situation is given: In your code you have a PDFDocument object. This contains a PDF file with form fields that are filled with text. If you call the dataRepresentation() method on this PDFDocument object, you get back a data object: let myDocumentData: Data = pdfDocument.dataRepresentation()! If you now want to initialize a new PDFDocument object with this data object, the contents of the form fields are duplicated within the PDF. let newPDF: PDFDocument = PDFDocument(data: myDocumentData) If you now want to print the newPDF PDFDocument object by creating a new print job, you will get the following result: What you actually expect to see: You only see this behavior when you want to print or share the PDF. You won't see this behaviour inside a PDF View in your application. This behaviour only appears since iOS/iPadOS 17.2 Steps to reproduce: Get a PDF file with form fields, especially text fields fill out these text fields with text create a PDFDocument object with this PDF file call the dataRepresentation() method on this PDFDocument object and store the result in a new variable create a new PDFDocument object with the data object created in the previous step:PDFDocument(data: <data>) Print the new created PDFDocument within iOS/iPadOS 17.2 or share it for example via email I hope Apple will fix this bug soon!
7
5
1.7k
Dec ’23
Create PDF file with Spot Colors
I am trying to generate a PDF file with certain components draw with Spot Colours. Spot colours are used for printing and I am not clear on how one would do that but I think that if I can create a custom ColorSpace with a specific name or a color that has a specific name - our printer looks for the name Spot1 and they use the colour green. Can anyone shed any light on how I might be able to do this. For reference I have attached two pdf files with two different spot colours in them. I need to be able to create similar using CGContext and CGPDFDocument. I can already generate the PDF documents using CMYK colors but don't know how I can create the equivalent "spot" colors. At the moment I am loading the page from these attached pdf files and scaling them to fill the page to get a background with the spot color. This works fine but I also need to generate text and lines using this same spot color and I am not clear how I could do that using the Core Graphics APIs. My guess is I need to create a custom ColorSpace with a single color and then use that color for drawing with. The only 'custom' option for creating a ColorSpace seems to be the CGColorSpace(propertyListPList:) constructor, however there does not appear to be any documentation on what needs to be in the property list to do so. Nor can I find any examples of that. Any pointers would be appreciated. Regards
1
0
1.6k
Dec ’23
ios17 breaks custom page size for PDF export
We have an app that exports PDFs with a custom page size, using PSDKit. In iOS16 the PDF export would have the correct page size dimensions, but now iOS17 exports everything to a Letter (8.5x11) size, regardless of what the PDF size specs are defined in the code: let pageWidth: CGFloat = 86.0 / 25.4 * 72 let pageHeight: CGFloat = 54.0 / 25.4 * 72 let pageSize = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight) Any thoughts as to how to fix this?
3
0
1.4k
Dec ’23
PDFKit on macOS. Nearest page & converting point to document point not working.
On macOS page(for: viewPoint, nearest: false) returns the wrong page. If I enter a coordinate on page 1 less than 1/3 of the way down, it returns that it is on page 0. Likewise on page 2 it will say page 1 anywhere in the top third. Also PDFView's convert(point, to: page) will return seemingly random values for the document point's y value, but in the expected range of 0 to about 792 (for an 11" page at 72dpi). Displaying the document horizontal/vertical doesn't matter. The x value of the point is always correct and everything works correctly on iOS. I've tried Xcode 15.0 and 15.1 beta 3. Anyone using these functions correctly, or seeing the same issue?
0
0
721
Dec ’23
Why does it not exist via @AppStorage
2 versions 1 works 1 doesn't. UIViewRepresentable to show a PDF @AppStorage(DefaultsKey.userActiveBook.rawValue) var activeBook : URL = Bundle.main.url(forResource: "BookPlaceHolder", withExtension: "pdf")! func makeUIView(context: Context) -&gt; PDFView { do { let pdfData = try Data(contentsOf: activeBook) pdfView.document = PDFDocument(data: pdfData) //&lt;---- is nil ... } catch let Error { print(Error) } } fails with Error Domain=NSCocoaErrorDomain Code=260 "The file “BookPlaceHolder.pdf” couldn’t be opened because there is no such file." func makeUIView(context: Context) -&gt; PDFView { do { let pdfData = try Data(contentsOf: Bundle.main.url(forResource: "BookPlaceHolder", withExtension: "pdf")!) pdfView.document = PDFDocument(data: pdfData) ... } catch let Error { print(Error) } } Works perfectly. What is it with using @AppStorage to access the exact same URL causing the discrepancies ?
2
0
1k
Dec ’23
How to set the Anchors Points of a PDF in PDFKit?
I am trying to set the top anchor point of a pdf that is inside of a view with the .ignoresSafeArea() modifier. I would also like it to work on the edges when the phone is in landscape although for simplicity I will only explain what I want for the top. I want it to function like the iOS Files app pdf viewer where when tapped it hides the navigation bars but the top of the pdf stays at the same place, but when you zoom in on the pdf it can fill the whole screen. When you zoom back out the top should return to the same place as before. Here is a simple view to show how it is being used: @MainActor struct ContentView: View { @State var showBars: Bool = true @State var pdfUrl: URL? var body: some View { NavigationStack { GeometryReader { geo in ScrollView { TabView { if let url = pdfUrl { PDFViewer(pdfUrl: url) .onTapGesture { withAnimation { showBars.toggle() } } } } .tabViewStyle(.page(indexDisplayMode: .never)) .frame(width: geo.size.width, height: geo.size.height) } .scrollDisabled(true) } .ignoresSafeArea(edges: !showBars ? .all : []) } .task { pdfUrl = renderPDF() } } func renderPDF() -> URL { let renderer = ImageRenderer(content: VStack {}) let url = URL.documentsDirectory.appending(path: "samplepdf.pdf") renderer.render { size, context in guard let pdf = CGContext(url as CFURL, mediaBox: nil, nil) else { return } pdf.beginPDFPage(nil) context(pdf) pdf.endPDFPage() pdf.beginPDFPage(nil) context(pdf) pdf.endPDFPage() pdf.closePDF() } return url } } And here is what my pdfView looks like so far: struct PDFViewer: View { var pdfUrl: URL var body: some View { PDFSheetView(document: .init(url: pdfUrl)) } } class PDFViewController: UIViewController { let document: PDFDocument? var pdfView: PDFView! init(document: PDFDocument?) { self.document = document super.init(nibName: nil, bundle: nil) } override func loadView() { let view = PDFView() self.view = view self.pdfView = view view.document = document view.displayDirection = .vertical view.autoScales = true view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true view.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true view.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true } required init?(coder: NSCoder) { document = nil super.init(coder: coder) return nil } override func viewDidLayoutSubviews() { let bounds = view.bounds if let document { if let page = document.page(at: 0) { let pageBounds = page.bounds(for: .mediaBox) if bounds.width > 0 && pageBounds.width > 0 { let scaleFactor = bounds.width / pageBounds.width let subtractionFactor = scaleFactor * 0.0125 pdfView.minScaleFactor = scaleFactor - subtractionFactor } } } } } struct PDFSheetView: UIViewControllerRepresentable { typealias UIViewControllerType = PDFViewController let document: PDFDocument? func makeUIViewController(context: Context) -> PDFViewController { let controller = PDFViewController(document: document) return controller } func updateUIViewController(_ uiViewController: PDFViewController, context: Context) { } } Is this possible to do? Like I said before, I want it to function just like the iOS Files app pdf viewer.
0
0
661
Nov ’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)
1
0
930
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.5k
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
823
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
643
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.6k
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
805
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
758
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.4k
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
1.1k
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.9k
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
1.1k
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.2k
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
791
Oct ’23
iOS/iPadOS 17.2 Bug in PDFKit duplicates content of filled PDF form fields
The following situation is given: In your code you have a PDFDocument object. This contains a PDF file with form fields that are filled with text. If you call the dataRepresentation() method on this PDFDocument object, you get back a data object: let myDocumentData: Data = pdfDocument.dataRepresentation()! If you now want to initialize a new PDFDocument object with this data object, the contents of the form fields are duplicated within the PDF. let newPDF: PDFDocument = PDFDocument(data: myDocumentData) If you now want to print the newPDF PDFDocument object by creating a new print job, you will get the following result: What you actually expect to see: You only see this behavior when you want to print or share the PDF. You won't see this behaviour inside a PDF View in your application. This behaviour only appears since iOS/iPadOS 17.2 Steps to reproduce: Get a PDF file with form fields, especially text fields fill out these text fields with text create a PDFDocument object with this PDF file call the dataRepresentation() method on this PDFDocument object and store the result in a new variable create a new PDFDocument object with the data object created in the previous step:PDFDocument(data: <data>) Print the new created PDFDocument within iOS/iPadOS 17.2 or share it for example via email I hope Apple will fix this bug soon!
Replies
7
Boosts
5
Views
1.7k
Activity
Dec ’23
Create PDF file with Spot Colors
I am trying to generate a PDF file with certain components draw with Spot Colours. Spot colours are used for printing and I am not clear on how one would do that but I think that if I can create a custom ColorSpace with a specific name or a color that has a specific name - our printer looks for the name Spot1 and they use the colour green. Can anyone shed any light on how I might be able to do this. For reference I have attached two pdf files with two different spot colours in them. I need to be able to create similar using CGContext and CGPDFDocument. I can already generate the PDF documents using CMYK colors but don't know how I can create the equivalent "spot" colors. At the moment I am loading the page from these attached pdf files and scaling them to fill the page to get a background with the spot color. This works fine but I also need to generate text and lines using this same spot color and I am not clear how I could do that using the Core Graphics APIs. My guess is I need to create a custom ColorSpace with a single color and then use that color for drawing with. The only 'custom' option for creating a ColorSpace seems to be the CGColorSpace(propertyListPList:) constructor, however there does not appear to be any documentation on what needs to be in the property list to do so. Nor can I find any examples of that. Any pointers would be appreciated. Regards
Replies
1
Boosts
0
Views
1.6k
Activity
Dec ’23
ios17 breaks custom page size for PDF export
We have an app that exports PDFs with a custom page size, using PSDKit. In iOS16 the PDF export would have the correct page size dimensions, but now iOS17 exports everything to a Letter (8.5x11) size, regardless of what the PDF size specs are defined in the code: let pageWidth: CGFloat = 86.0 / 25.4 * 72 let pageHeight: CGFloat = 54.0 / 25.4 * 72 let pageSize = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight) Any thoughts as to how to fix this?
Replies
3
Boosts
0
Views
1.4k
Activity
Dec ’23
PDFKit on macOS. Nearest page & converting point to document point not working.
On macOS page(for: viewPoint, nearest: false) returns the wrong page. If I enter a coordinate on page 1 less than 1/3 of the way down, it returns that it is on page 0. Likewise on page 2 it will say page 1 anywhere in the top third. Also PDFView's convert(point, to: page) will return seemingly random values for the document point's y value, but in the expected range of 0 to about 792 (for an 11" page at 72dpi). Displaying the document horizontal/vertical doesn't matter. The x value of the point is always correct and everything works correctly on iOS. I've tried Xcode 15.0 and 15.1 beta 3. Anyone using these functions correctly, or seeing the same issue?
Replies
0
Boosts
0
Views
721
Activity
Dec ’23
Why does it not exist via @AppStorage
2 versions 1 works 1 doesn't. UIViewRepresentable to show a PDF @AppStorage(DefaultsKey.userActiveBook.rawValue) var activeBook : URL = Bundle.main.url(forResource: "BookPlaceHolder", withExtension: "pdf")! func makeUIView(context: Context) -&gt; PDFView { do { let pdfData = try Data(contentsOf: activeBook) pdfView.document = PDFDocument(data: pdfData) //&lt;---- is nil ... } catch let Error { print(Error) } } fails with Error Domain=NSCocoaErrorDomain Code=260 "The file “BookPlaceHolder.pdf” couldn’t be opened because there is no such file." func makeUIView(context: Context) -&gt; PDFView { do { let pdfData = try Data(contentsOf: Bundle.main.url(forResource: "BookPlaceHolder", withExtension: "pdf")!) pdfView.document = PDFDocument(data: pdfData) ... } catch let Error { print(Error) } } Works perfectly. What is it with using @AppStorage to access the exact same URL causing the discrepancies ?
Replies
2
Boosts
0
Views
1k
Activity
Dec ’23
How to set the Anchors Points of a PDF in PDFKit?
I am trying to set the top anchor point of a pdf that is inside of a view with the .ignoresSafeArea() modifier. I would also like it to work on the edges when the phone is in landscape although for simplicity I will only explain what I want for the top. I want it to function like the iOS Files app pdf viewer where when tapped it hides the navigation bars but the top of the pdf stays at the same place, but when you zoom in on the pdf it can fill the whole screen. When you zoom back out the top should return to the same place as before. Here is a simple view to show how it is being used: @MainActor struct ContentView: View { @State var showBars: Bool = true @State var pdfUrl: URL? var body: some View { NavigationStack { GeometryReader { geo in ScrollView { TabView { if let url = pdfUrl { PDFViewer(pdfUrl: url) .onTapGesture { withAnimation { showBars.toggle() } } } } .tabViewStyle(.page(indexDisplayMode: .never)) .frame(width: geo.size.width, height: geo.size.height) } .scrollDisabled(true) } .ignoresSafeArea(edges: !showBars ? .all : []) } .task { pdfUrl = renderPDF() } } func renderPDF() -> URL { let renderer = ImageRenderer(content: VStack {}) let url = URL.documentsDirectory.appending(path: "samplepdf.pdf") renderer.render { size, context in guard let pdf = CGContext(url as CFURL, mediaBox: nil, nil) else { return } pdf.beginPDFPage(nil) context(pdf) pdf.endPDFPage() pdf.beginPDFPage(nil) context(pdf) pdf.endPDFPage() pdf.closePDF() } return url } } And here is what my pdfView looks like so far: struct PDFViewer: View { var pdfUrl: URL var body: some View { PDFSheetView(document: .init(url: pdfUrl)) } } class PDFViewController: UIViewController { let document: PDFDocument? var pdfView: PDFView! init(document: PDFDocument?) { self.document = document super.init(nibName: nil, bundle: nil) } override func loadView() { let view = PDFView() self.view = view self.pdfView = view view.document = document view.displayDirection = .vertical view.autoScales = true view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true view.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true view.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true } required init?(coder: NSCoder) { document = nil super.init(coder: coder) return nil } override func viewDidLayoutSubviews() { let bounds = view.bounds if let document { if let page = document.page(at: 0) { let pageBounds = page.bounds(for: .mediaBox) if bounds.width > 0 && pageBounds.width > 0 { let scaleFactor = bounds.width / pageBounds.width let subtractionFactor = scaleFactor * 0.0125 pdfView.minScaleFactor = scaleFactor - subtractionFactor } } } } } struct PDFSheetView: UIViewControllerRepresentable { typealias UIViewControllerType = PDFViewController let document: PDFDocument? func makeUIViewController(context: Context) -> PDFViewController { let controller = PDFViewController(document: document) return controller } func updateUIViewController(_ uiViewController: PDFViewController, context: Context) { } } Is this possible to do? Like I said before, I want it to function just like the iOS Files app pdf viewer.
Replies
0
Boosts
0
Views
661
Activity
Nov ’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
930
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
730
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.5k
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
823
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
643
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.6k
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
805
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
758
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.4k
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
1.1k
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.9k
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
1.1k
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.2k
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
791
Activity
Oct ’23