Skip to content

Instantly share code, notes, and snippets.

@Shilo
Created July 31, 2017 22:35
Show Gist options
  • Save Shilo/f0b56b04d6684e1c37f1e96de1a14551 to your computer and use it in GitHub Desktop.
Save Shilo/f0b56b04d6684e1c37f1e96de1a14551 to your computer and use it in GitHub Desktop.
Swift snippet for jumping to a specific PDF page in WKWebView.
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);
}
}
@sovata8
Copy link

sovata8 commented May 16, 2019

For anyone stumbling upon this - it seems a better way to get page dimensions is using CGPDFDocument, CGPDFPage and getBoxRect() - see this discussion: https://stackoverflow.com/questions/3045587/how-to-get-actual-pdf-page-size-in-ipad

Also 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 and goToPreviousPage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment