Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
}
}
@project-academy

This comment has been minimized.

Copy link

commented Sep 21, 2018

Hi Shilo

I tried using this code, but it does not seem to be working.
In webViewGoToPDFPage(index:), I get the following printouts:
print(pdfView) // <UIImageView: 0x10233ede0; frame = (761.5 -17; 2.5 36); alpha = 0; opaque = NO; autoresize = LM; userInteractionEnabled = NO; layer = <CALayer: 0x282053100>>
print(pdfView.subviews) // []
∴ the code inside the for-loop never actually runs since there are no subviews for pdfView.

Did you have any similar issues with this?

Cheers

@sovata8

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.