Post not yet marked as solved
Anyone Work on PDFKit, I draw a custom Annotation in PDFView, But I want to add action in Custom Annotation and I can't able to add Gesture in PDFAnnotation because it does not inherit from UIView, so is there any way to add Gesture in PDFAnnotation.
Post not yet marked as solved
Hi all,
I have been facing a problem while loading a file from the firebase storage.
Basically in my code i have a data model which is the file/document (pdf in this case), a manager which goes into the database of Firebase to fetch the object and finally two views, one to list the files fetched and another one to show the document.
I can fetch all the documents with their specific data, pass them to my view and then show the document pdf in another view.
Everything seems correct but the problem comes when opening one of this docs. First, the doc doesn't open at first so you need to close the view and try to open the doc again. Then when i want to open another doc from my list, when i click on it the previous document is shown and not the correct one, so i need to do the same, close the view and click again on the doc to open the correct one.
So at the end what i'm looking for is to open the doc just clicking once but i don't know where is my problem.
List of docs:
1st time:
2nd time:
2nd doc but 1st time:
2nd doc and 2nd time clicking on it:
Here is my code
Model:
struct DocumentoPdf {
let titulo: String
let docUrl: URL?
let id: String
let storageUrl: String
}
Manager which fetches the documents from firebase:
final class DatabaseManager {
[...]
public func getNovedades(completion: @escaping ([DocumentoPdf]) -> Void) {
database.collection("novedades").getDocuments { snapshot, error in
guard let documents = snapshot?.documents.compactMap ({ $0.data() }), error == nil else {
return
}
let novedades: [DocumentoPdf] = documents.compactMap({ dictionary in
guard let id = dictionary["id"] as? String,
let titulo = dictionary["titulo"] as? String,
let docUrlString = dictionary["docUrl"] as? String,
let storageUrl = dictionary["storageUrl"] as? String else {
return nil
}
let novedad = DocumentoPdf(titulo: titulo,
docUrl: URL(string: docUrlString),
id: id,
storageUrl: storageUrl)
return novedad
})
completion(novedades)
}
}
}
First View:
class NovedadesViewControllerViewModel {
let docUrl: URL?
var docData: Data?
init(docUrl: URL?) {
self.docUrl = docUrl
}
}
class NovedadesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PDFViewDelegate {
private var tableView = UITableView()
private var doc = PDFDocument()
public func configureDocPdf(with viewModel: NovedadesViewControllerViewModel) {
if let data = viewModel.docData {
doc = PDFDocument(data: data)!
}
else if let url = viewModel.docUrl {
// fetch doc & cache
let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
guard let data = data else {
return
}
viewModel.docData = data
DispatchQueue.main.async {
self?.doc = PDFDocument(data: data)!
}
}
task.resume()
}
}
private var novedades: [DocumentoPdf] = []
private func obtenerNovedades() {
DatabaseManager.shared.getNovedades() { [weak self] novedades in
self?.novedades = novedades
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
}
override func viewDidLoad() {
[...]
obtenerNovedades()
[...]
}
[... sections, rows in section...]
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let novedad = novedades[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = novedad.titulo
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let novedad = novedades[indexPath.row]
switch indexPath.section {
case 0:
configureDocPdf(with: .init(docUrl: novedad.docUrl))
let lectorPdfView = LectorPdfViewController(doc: self.doc, nameDoc: novedad.titulo)
self.present(lectorPdfView, animated: true, completion: nil)
default:
break
}
}
}
Second View to load the pdf:
class LectorPdfViewController: UIViewController, PDFViewDelegate {
private let navBar = UINavigationBar()
private let pdf = PDFView()
let nameDoc: String
let doc: PDFDocument
init(doc: PDFDocument, nameDoc: String) {
self.doc = doc
self.nameDoc = nameDoc
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
view.addSubview(navBar)
view.addSubview(pdf)
pdf.document = self.doc
pdf.delegate = self
let item = UINavigationItem(title: self.nameDoc)
navBar.setItems([item], animated: false)
navBar.barTintColor = .systemBackground
}
override func viewDidLayoutSubviews() {
navBar.frame = CGRect(x: 0,
y: 0,
width: view.frame.size.width,
height: 50)
pdf.frame = CGRect(x: 0,
y: navBar.frame.height,
width: view.frame.size.width,
height: view.frame.size.height - navBar.frame.height)
}
}
Please if someone can help me with this will be fantastic. I hope you understood my code and my problem. Sorry for my bad english
Thank you so much in advance
Post not yet marked as solved
XCode - Swift
private var mPdfView = PDFView()
private var mDocumentData: Data?
mDocumentData = MakePdfDocument()
mPdfView.document = PDFDocument(data: mDocumentData!)
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.outputType = UIPrintInfo.OutputType.general
printInfo.jobName = “JobName”
let printController = UIPrintInteractionController.shared
printController.printInfo = printInfo
printController.printingItem = mPdfView
printController.showsNumberOfCopies = true
printController.present(animated: true, completionHandler: nil)
**When print is executed, only the blank screen is output, not the generated PDF.
How can I print the generated PDF content?**
Post not yet marked as solved
I'm trying to use PDFPageOverlayViewProvider by copying the code provided in the "What's new in PDFKit" WWDC22 session here: https://developer.apple.com/videos/play/wwdc2022/10089/
I've copied the method implementations and set my pdfView's pageOverlayViewProvider property to the view where I implemented the protocol. However, when I try to run my app, the pdfView(_ view: PDFView, overlayViewFor page: PDFPage) method is never getting called.
Has anyone been able to get this working successfully?
Post not yet marked as solved
I know this is a strange and easy question.
but JUST CANT FIND ANY REFERENCE aaaaaaaa
I'm using SwiftUI and wants to
export to PDF (best I can find Creating PDFs on MacOS without UIKit)
export to image
export to HTML
export to everything possible etc
BONUS print the page
I can only find UIKit support and they are all outdated. AND IF POSSIBLE how to integrate ShareLink to share these(PDF, Image, HTML, etc) and write them onto disk using NSSavePane?
even better
how to do this on a of the platforms
(I know I'm greedy😂)
Thanks for any help🙏
Post not yet marked as solved
There are some errors when attempting to run the sample code:
Cannot convert value of type 'String' to expected argument type 'PDFAnnotationSubtype'
I understand the error but I'm unsure what it's looking for.
I'm running Xcode 14, targeting iOS 12
Thx for any feedback!
Post not yet marked as solved
I create a UIViewRepresentable to show my PDF inside my SwiftUI app. I want to access the current page number using currentPage?.pageRef?.pageNumber. from the view in which I display the pdf. How to make PDFView Created in func makeUIView(context: UIViewRepresentableContext<PDFDisplayRepresentedView>) -> PDFView Available in the view displaying the pdf so I can access its properties to obtain page number.
import SwiftUI
import PDFKit
struct PDFDisplayView: View {
@Binding var pdfDocument : PDFDocument?
var body: some View {
PDFDisplayRepresentedView(pdfDocument: pdfDocument!)
}
}
struct PDFDisplayRepresentedView: UIViewRepresentable {
let pdfDocument: PDFDocument
init(pdfDocument: PDFDocument) {
self.pdfDocument = pdfDocument
}
func makeUIView(context: UIViewRepresentableContext<PDFDisplayRepresentedView>) -> PDFView {
return createPDFViewUsing(document: pdfDocument)
}
func updateUIView(_ pdfView: PDFView, context: UIViewRepresentableContext<PDFDisplayRepresentedView>) {
pdfView.document = pdfDocument
}
private func createPDFViewUsing(document : PDFDocument) -> PDFView {
let pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
pdfView.document = document
... set up pdfView attributes
return pdfView
}
}
view showing pdf where I want to know the page number
pseudo code
…
@State private var pdfDisplayView : PDFDisplayView?
….
var body: some View {
load the pdf into this view.
need to access the page number
pdfDisplayView
}
Post not yet marked as solved
Good afternoon (o;
Doing a simple SwiftUI app where it fetches a PDF barcode from a web service to be printed on a thermal label printer.
So I use this snippet to fetch the PDF and launch the printing dialog:
let pdfView = PDFView()
pdfView.document = PDFDocument(url: self.url!)
let wnd = NSWindow()
pdfView.autoScales = true
pdfView.displaysPageBreaks = false
wnd.setContentSize(pdfView.frame.size)
wnd.contentView = pdfView
pdfView.print(with: printInfo, autoRotate: false)
But the printing dialog appears on the lower left corner of the screen...and when choosing "details" the dialog extends to the offscreen area....
Also no paper size is choosable.
thanks in advance
richard
We have some PDFs that were created with JPEG2000 images in them (*.jp2 files). Using PDFKit, and also WebKit, the images in these PDFs in some cases don't display at all, and in others cases appear badly warped. You can view the PDF using either Adobe Reader, or the Chrome app, and the images appear fine, so it's clearly not an issue of a corrupt PDF. Also, 3rd-party commercial iOS controls like PSPDF and FoxIt display the images fine, so it's clearly an issue with PDFKit and WebKit. Any known workarounds?
Post not yet marked as solved
https://pdftron.s3.amazonaws.com/custom/test/jack/blank+(34).pdf
Here is the pdf. You could download it. In the PDF, there is a checkbox. When we open the PDF in Acrobat and Chrome, it can be edited. However, when we open it in Mac Preview and IOS devices. The checkbox is hidden and cannot be edited anymore. It could be a bug from Preview and IOS PDF editor
Post not yet marked as solved
Is there a way to apply color filters to the contents of a PDF displayed in a PDFView? My desired effect is to display the PDF with colors inverted. CIFilter and compositingFilter seem relevant, but I couldn't get to a working example. Any guidance appreciated!
Post not yet marked as solved
Feature request: a new PDFView layout in PDFKit
This feature request is from the Skim.app Sourceforge page
https://sourceforge.net/p/skim-app/feature-requests/1640/
orignial feature request
It would be nice if we can have a PDF Display option "Single-page Two-column Continuous" which I would explain below.
I imagine we can have a layout like the "Two Pages Continuous", but the right-hand-side page is the same page as the left-hand-side page, continued from the bottom.
Like this:
| /|
| / |
|/ ↓
L R
This will be extremely helpful for short displays, as it take full advantage of the width of the display while still gives rather large fonts.
response from the Skim team
The page layout is implemented by Apple's PDFKit. If you want to have support for it, you should first ask Apple to provide it.
My problem
I have no idea how to ask Apple to provide it.
If the provider of PDFKit can see this, that would be great.
Or if anyone know what should I do to ask for this feature, please help.
I suppose this can benefit more as it would not only be implemented in Skim.app but probably also Preview.app
Post not yet marked as solved
Hello!
I need help on getting rid of these other actions whenever saving pdf files.
Post not yet marked as solved
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?
Post not yet marked as solved
Hi,
I am trying to export the following SwiftUI View to PDF using UIGraphicsPDFRenderer.
The problem I am getting is there is somehow a margin on top of the exported PDF.
The code I am using
import SwiftUI
struct ContentView: View {
var body: some View {
let pressGesture = TapGesture()
.onEnded { value in
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let outputFileURL = documentDirectory.appendingPathComponent("SwiftUI.pdf")
let pdfVC = UIHostingController(rootView: self)
let pageSize = CGSize(width: 2.625 * 72.0, height: 1.0 * 72.0)
pdfVC.view.frame = CGRect(origin: .zero, size: pageSize)
let rootVC = UIApplication.shared.windows.first?.rootViewController
rootVC?.addChild(pdfVC)
rootVC?.view.insertSubview(pdfVC.view, at: 0)
let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: pageSize.width, height: pageSize.height))
DispatchQueue.main.async {
do {
try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
context.beginPage()
pdfVC.view.layer.render(in: context.cgContext)
})
print("wrote file to: (outputFileURL.path)")
pdfVC.removeFromParent()
pdfVC.view.removeFromSuperview()
} catch {
print("Could not create PDF file: (error.localizedDescription)")
}
}
}
VStack(){
Text("Hello")
}
.frame(width: 2.625 * 72.0, height: 1.0 * 72.0, alignment: .center)
.gesture(pressGesture)
.background(Color.red)
}
}
May I know what am I doing wrong? Thanks in advance.
Post not yet marked as solved
I have a bunch of PDF files that I try to open either with CGPDFDocument or PDFDocument (PDFKit) and the init return NULL. Where can I get some feedback why this is happening? I cannot find anything on Console (for connected iOS device) or the Xcode Debug Output window.
Let me say that this is not true for all PDF files, some open and some do not. It is also not a problem with permissions, the files are accessible by the app.
Post not yet marked as solved
For local files, it's an amazing feature to be able to space-bar open a PDF document and quickly swipe through the contents of it.
How can I enable this for pdf files stored on a volume exposed by FileProvider?
Thanks David
Post not yet marked as solved
Description
I am having issue with UIImage "generated" from PDFPage via method .thumbnail(of:for). UIImage, which I later display in UIImageView does not respect rotation of the PDF page, but for iOS 13 only.
When PDF page is rotated for example by 90° and presented in PDFView all is good and shown correctly. But when I want to take the UIImage (i.e. thumbnail) of the PDFPage and show it in UIImageView, for some reason, iOS 13 does not respect the initial rotation of the PDF page and present it in UIImageView incorrectly.
Please behold on below sample code and example screenshots.
Testing environment
iOS 13 on simulator only, not having real device
Xcode 13.1
Sample code
for sake of shorter example, I force unwrap where optionals occur
import UIKit
import PDFKit
class TestingViewController: UIViewController {
lazy var imageView: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
// Pass URL of the PDF document when instantiating this VC
init(withURL: URL) {
super.init(nibName: nil, bundle: nil)
let pdfDoc = PDFDocument(url: withURL)
let pdfPage = pdfDoc!.page(at: 0) // Getting first page of the doc
let pdfPageRect = pdfPage!.bounds(for: .mediaBox)
imageView.image = pdfPage!.thumbnail(of: pdfPageRect.size, for: .mediaBox) // Getting the UIImage of the PDF page and assign it to the needed image view
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
print("\(pdfPage?.rotation)") // Prints the correct rotation value, even though UIImageView does not respect it
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Layout only
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemPink
view.addSubview(imageView)
NSLayoutConstraint.activate([
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
imageView.widthAnchor.constraint(equalToConstant: 350),
imageView.heightAnchor.constraint(equalToConstant: 700),
])
}
}
Example screenshots from simulator
✅ Presented correctly (iOS 15)
❌ Presented incorrectly (iOS 13.2)
Post not yet marked as solved
Greetings,
this may be an odd question but I was not able to find an answer to this.
So I am developing this pure MacOS program for a client and one thing he wants is to create some PDFs along the way. Great chance I thought to try out this fancy Swift 5 with SwiftUI and so far it's going great, most of the program is up and running but I've hit a wall with the PDF generation, which I thought would be one of the easiest parts.
Since it's a pure MacOS program, UIKit is not available but there is not a single tutorial out there for generating PDFs which is not using UIKit to do it. It seems people only want to create PDFs on iOS.
Can someone give me a small breakdown or starter or tutorial or skeleton on how I would do that?
Thanks and have a nice day
Post not yet marked as solved
I'm currently using PDFKit with Annotations in a unique way. The Annotations are Icons that serve as a link to an asset on a technical drawing. In this way, the user can view the asset details or find the asset from the asset details. I'm using flat images as annotation icons but would like to use 3D assets, preferably 'real' 3D assets where the prospective changes as the user moves the PDF. I'm curious on the best way to accomplish this task. The specific need for the PDF is because it holds the annotation text, which serves as a location indicator (X,Y) to place my Annotation image on top of. PDFs also hold a very high resolution at a relatively low file size, which is good for viewing the rest of the technical document.
SceneKit Solution:
From my research, I believe SceneKit would accomplish this by utilizing a PDF as a texture (or converting to high resolution PNG). However, I'm unsure how I would take the Annotation location in this method. I believe I can accomplish this by using PDFKit to extract the (X,Y) then place it in the comparable SceneKit scene, but have not tested this theory.
I'm wondering if there is an easier or more direct way of accomplishing this task?