Skip to content

Instantly share code, notes, and snippets.

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;
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);

This comment has been minimized.

Copy link

project-academy 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?



This comment has been minimized.

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:

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.