Created
July 31, 2017 22:35
-
-
Save Shilo/f0b56b04d6684e1c37f1e96de1a14551 to your computer and use it in GitHub Desktop.
Swift snippet for jumping to a specific PDF page in WKWebView.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func webViewGotoPDFPage(index: Int) { | |
if (index < 1) { return; } | |
let pageCount = totalPDFPages(filePath: webViewLastURL!); | |
let pageIndex = max(min(index, pageCount), 1)-1; | |
/* | |
let firstPage = self.webView.scrollView.subviews[2].subviews[0]; | |
//let contentHeight = self.webView.scrollView.contentSize.height; | |
//let totalPaddingSize = CGFloat(PDF_INNER_PADDING)*(CGFloat(pageCount)-1) + CGFloat(PDF_OUTER_PADDING)*2; | |
//let averagePageHeight = (contentHeight-totalPaddingSize)/CGFloat(pageCount); | |
let firstPageHeight = firstPage.bounds.size.height; | |
let scrollY = (firstPageHeight*CGFloat(pageIndex)) + (CGFloat(PDF_INNER_PADDING)*CGFloat(pageIndex)) + CGFloat(PDF_OUTER_PADDING); | |
self.webView.scrollView.setContentOffset(CGPoint.init(x: 0, y: scrollY), animated: animated); | |
*/ | |
var pdfView = self.webView.scrollView.subviews[2]; | |
var scrollY:CGFloat = 0.0; | |
for i in 0..<pageIndex { | |
for subview in pdfView.subviews { | |
var y2 = subview.frame.origin.y + subview.frame.size.height; | |
if (y2 > scrollY) { | |
scrollY = y2; | |
break; | |
} | |
self.webView.scrollView.setContentOffset(CGPoint.init(x: 0, y: scrollY), animated: false); | |
} | |
} | |
} | |
func totalPDFPages(filePath: URL) -> Int { | |
let doc = CGPDFDocument.init(filePath as CFURL); | |
return (doc?.numberOfPages)!; | |
} | |
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { | |
webView.isHidden = false; | |
if (webViewStartPDFPageIndex > 1 && webViewLastURL?.pathExtension.lowercased() == "pdf") { | |
webViewGotoPDFPage(index: webViewStartPDFPageIndex); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For anyone stumbling upon this - it seems a better way to get page dimensions is using
CGPDFDocument
,CGPDFPage
andgetBoxRect()
- see this discussion: https://stackoverflow.com/questions/3045587/how-to-get-actual-pdf-page-size-in-ipadAlso note that if you're targeting iOS 11+, then you can simply avoid using web views altogether and use the new PDFView instead. It has functions such as
goToNextPage
andgoToPreviousPage
.