For a recent project I had to create a small PDF ‘Google Maps like’ viewer for iOS. The viewer needs to handle zooming and dragging to navigate the PDF page. And for performance issues it’s best to load the PDF using tiles.
In some code snippets below, I’ll show you how it’s done. Make sure to check out Github for an example XCode project with comments for almost every line of code.
This is the setup I used in this tutorial:
- I have a
UIViewControllerwith an attached XIB file.
- I created a map
UIViewthat is a subview belonging to the controller’s view (which is a
- I built a
CATiledLayerthat is added as a sublayer to the map view.
CATiledLayeris responsible for the tiling of the PDF map.
Create the PDF
Here is how you create the PDF. First grab a
NSURL instance with the PDF’s location, and then you create the
CGPDFDocumentRef that’s needed to construct the
CGPDFPageRef which represents a page.
I want the PDF to load like the Google Maps application is loaded. That’s why you have to use the
CATiledLayer, this does everything. You can specify the size, level of detail (for vectorized PDF’s)… For more info check out the Apple Developer Reference
Don’t forget to set the delegate for the
CATiledLayer, this makes sure the
drawLayer method is called.
Afterwards the tiled layer delegate will do the rest if you implement this method:
It looks a bit low level but it’s fairly easy to get it to work.
Now the last thing you have to do is to tell the
UIView has to be zoomed. That is why you need to set the delegate of the
UIScrollView. This makes sure the following methods is called:
Here you return the
UIView that needs to zoom depending on the finger gestures.
Sign up for our newsletter
Who’s got the mic?
Architecture & Design
Koen Van Der Auwera
Bob Van Landuyt
Nathan de Witte