Reputation: 2719
I'm trying to write a simple function that will get the number of pages in a PDF. Every code example I've seen now seems to fail with Swift 3, and whatever Xcode recommends still doesn't work.
func pageCount(filepath: String) -> Int {
let localUrl = filepath as CFString
let pdfDocumentRef = CFURLCreateWithFileSystemPath(nil, localUrl, CFURLPathStyle.cfurlposixPathStyle, false)
let page_count = (pdfDocumentRef as! CGPDFDocument).numberOfPages
return page_count
}
And this doesn't work either:
func pageCount(filepath: String) -> Int {
let url = NSURL(fileURLWithPath: filepath)
let pdf = CGPDFDocument(url)
let page_count = pdf?.numberOfPages
return page_count!
}
Any ideas why?
Upvotes: 1
Views: 721
Reputation: 2719
It seems that Apple has two PDF Objects: CGPDFDocument
, and PDFDocument
. The second is much easier to work with.
import Quartz
func NumPages(filename: String) -> Int {
let pdfDoc = PDFDocument(url: URL(fileURLWithPath: filename))!
return pdfDoc.pageCount
}
Upvotes: 1
Reputation: 3556
Modify your code as follows:
func pageCount(filepath: String) -> Int {
var count = 0
let localUrl = filepath as CFString
if let pdfURL = CFURLCreateWithFileSystemPath(nil, localUrl, CFURLPathStyle.cfurlposixPathStyle, false) {
if let pdf = CGPDFDocument(pdfURL) {
let page_count = pdf.numberOfPages
count = pdf.numberOfPages
}
}
return count
}
Basically, in your code, you were trying to cast a CFURL
as a CGPDFDocument
and you cannot do that :) You need to create a CGPDFDocument
instance from the CFURL
. Once you do that, you can get the page count for the PDF document.
Upvotes: 2