Why this happens
PDF rendering on iOS is expensive because each page is a vector description that must be rasterized into pixels for display. The classic trade-off appears in three common approaches:
- UIImage rasterization – Drawing an entire page into a
UIImageat screen scale produces a crisp result at 1× zoom, but the bitmap consumeswidth × height × 4bytes. A single US-Letter page at 2× Retina resolution exceeds 20 MB. Generating that bitmap blocks the main thread and spikes memory, causing jank or jetsam kills. - CATiledLayer –
CATiledLayerbreaks the page into small tiles (default 256 × 256 pt) and draws only visible tiles. This keeps memory low, but each tile incurs aCGContextDrawPDFPagecall. At high zoom levels the user sees individual tiles pop in, and the cumulative CPU time for a full page can still be high. - UIWebView / WKWebView – Web views handle tiling and caching internally, but they add process overhead, lack fine-grained control (annotations, text selection, custom gestures), and
UIWebViewis deprecated.
The root cause in all cases is synchronous, full-page rasterization on the main thread combined with no strategy for discarding off-screen content. The accepted Stack Overflow answer describes a hybrid technique: show a pre-rendered low-res UIImage at 1× zoom, then switch to CATiledLayer for zooming, while caching images to disk and rendering ahead on background queues.
How to fix it
1. Use PDFKit’s PDFView for most apps (iOS 11+)
PDFView is Apple’s built-in, highly optimized PDF viewer. It handles tiling, caching, text selection, annotations, and accessibility out of the box. Before building a custom solution, check whether PDFView meets your needs.
import PDFKit
let pdfView = PDFView()
pdfView.autoScales = true
pdfView.displayMode = .singlePageContinuous
pdfView.displayDirection = .vertical
if let url = Bundle.main.url(forResource: "document", withExtension: "pdf"),
let document = PDFDocument(url: url) {
pdfView.document = document
}
PDFView uses an internal tiled layer and a background render queue. It also respects memory warnings by dropping off-screen tiles. If you need custom gestures, overlay views, or non-standard paging, subclass PDFView or embed it in a UIScrollView‑like container.
2. Build a CATiledLayer viewer with disk-cached thumbnails
When you need full control (e.g., custom page transitions, synchronized dual-page spread, or offline annotation layer), implement the hybrid approach from the accepted answer:
Step 1 – Low-res thumbnail cache
Generate a screen-size UIImage for each page on a background queue and write it to the caches directory. Use CGContextSetInterpolationQuality(.high) for better down-sampling.
func thumbnailURL(for pageIndex: Int) -> URL {
let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
return caches.appendingPathComponent("page-\(pageIndex).jpg")
}
func generateThumbnail(for page: PDFPage, at index: Int, completion: @escaping (UIImage?) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
let size = UIScreen.main.bounds.size
let format = UIGraphicsImageRendererFormat()
format.scale = 1.0 // 1× is enough for thumbnail
let renderer = UIGraphicsImageRenderer(size: size, format: format)
let image = renderer.image { ctx in
UIColor.white.setFill()
ctx.fill(CGRect(origin: .zero, size: size))
ctx.cgContext.setInterpolationQuality(.high)
ctx.cgContext.setRenderingIntent(.defaultIntent)
let pageRect = page.bounds(for: .mediaBox)
let scale = min(size.width / pageRect.width, size.height / pageRect.height)
ctx.cgContext.translateBy(x: (size.width - pageRect.width * scale) / 2,
y: (size.height - pageRect.height * scale) / 2)
ctx.cgContext.scaleBy(x: scale, y: scale)
page.draw(with: .mediaBox, to: ctx.cgContext)
}
// Write to disk asynchronously
if let data = image.jpegData(compressionQuality: 0.7) {
try? data.write(to: self.thumbnailURL(for: index), options: .atomic)
}
completion(image)
}
}
Step 2 – Tiled page layer
Create a CALayer subclass that draws a PDFPage via CATiledLayer. Override draw(_:in:) to render only the requested tile.
final class PDFPageLayer: CALayer {
var pdfPage: PDFPage?
override class func fadeDuration() -> CFTimeInterval { 0 } // disable cross-fade
override func draw(in ctx: CGContext) {
guard let page = pdfPage else { return }
ctx.setInterpolationQuality(.high)
ctx.setRenderingIntent(.defaultIntent)
// Flip coordinate system for Core Graphics
ctx.translateBy(x: 0, y: bounds.height)
ctx.scaleBy(x: 1, y: -1)
let pageRect = page.bounds(for: .mediaBox)
let scale = min(bounds.width / pageRect.width, bounds.height / pageRect.height)
ctx.translateBy(x: (bounds.width - pageRect.width * scale) / 2,
y: (bounds.height - pageRect.height * scale) / 2)
ctx.scaleBy(x: scale, y: scale)
page.draw(with: .mediaBox, to: ctx)
}
}
Step 3 – View controller that swaps thumbnail → tiled layer
final class PDFPageView: UIView {
private let tiledLayer = CATiledLayer()
private let pageLayer = PDFPageLayer()
private var thumbnailImageView: UIImageView?
private var currentPage: PDFPage?
private var pageIndex = 0
private let document: PDFDocument
init(document: PDFDocument, pageIndex: Int) {
self.document = document
self.pageIndex = pageIndex
super.init(frame: .zero)
setupTiledLayer()
loadThumbnailThenPage()
}
private func setupTiledLayer() {
tiledLayer.tileSize = CGSize(width: 512, height: 512) // larger tiles = fewer draws
tiledLayer.levelsOfDetail = 4
tiledLayer.levelsOfDetailBias = 2
tiledLayer.contentsScale = UIScreen.main.scale
layer.addSublayer(tiledLayer)
tiledLayer.addSublayer(pageLayer)
}
private func loadThumbnailThenPage() {
// 1. Try disk cache
let url = thumbnailURL(for: pageIndex)
if let data = try? Data(contentsOf: url),
let image = UIImage(data: data, scale: 1.0) {
showThumbnail(image)
}
// 2. Ensure full page is ready for zoom
guard let page = document.page(at: pageIndex) else { return }
currentPage = page
pageLayer.pdfPage = page
pageLayer.frame = bounds
pageLayer.setNeedsDisplay()
}
private func showThumbnail(_ image: UIImage) {
let iv = UIImageView(image: image)
iv.contentMode = .scaleAspectFit
iv.frame = bounds
iv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(iv)
thumbnailImageView = iv
}
override func layoutSubviews() {
super.layoutSubviews()
tiledLayer.frame = bounds
pageLayer.frame = bounds
thumbnailImageView?.frame = bounds
}
// Call when zoom scale > 1.0
func enableTiledDrawing() {
thumbnailImageView?.removeFromSuperview()
thumbnailImageView = nil
}
}
Step 4 – Pre-render neighbors and purge on memory warning
class PDFViewerController: UIViewController {
var pageViews: [Int: PDFPageView] = [:]
let document: PDFDocument
var focusedIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(memoryWarning),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
}
func focusPage(_ index: Int) {
focusedIndex = index
// Keep index-2 … index+2 alive
let keep = Set((index-2)...(index+2))
for (idx, view) in pageViews where !keep.contains(idx) {
view.removeFromSuperview()
pageViews[idx] = nil
}
// Ensure neighbors exist
for i in keep where pageViews[i] == nil, let page = document.page(at: i) {
let pv = PDFPageView(document: document, pageIndex: i)
pageViews[i] = pv
// add to scroll view, etc.
}
}
@objc func memoryWarning() {
// Drop all thumbnails and tiled layers; they’ll rebuild on demand
pageViews.values.forEach { $0.prepareForReuse() }
// Optionally release PDFDocument and reload to clear internal caches
}
}
3. Cancel background work when pages go off-screen
Wrap each thumbnail generation in an Operation stored in a dictionary keyed by page index. When the page moves out of the keep range, cancel the operation and remove the reference.
var thumbnailOps: [Int: Operation] = [:]
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 2
func startThumbnail(for index: Int) {
guard thumbnailOps[index] == nil else { return }
let op = BlockOperation { [weak self] in
guard let self = self, let page = self.document.page(at: index) else { return }
self.generateThumbnail(for: page, at: index) { _ in }
}
thumbnailOps[index] = op
queue.addOperation(op)
}
func cancelThumbnail(for index: Int) {
thumbnailOps[index]?.cancel()
thumbnailOps[index] = nil
}
4. Reuse PDFDocument via a singleton wrapper
PDFDocument (and the underlying CGPDFDocumentRef) holds internal caches. Creating multiple instances for the same file multiplies memory. Wrap it in a thread-safe singleton:
final class PDFDocumentStore {
static let shared = PDFDocumentStore()
private var docs: [URL: PDFDocument] = [:]
private let lock = NSLock()
func document(for url: URL) -> PDFDocument? {
lock.lock(); defer { lock.unlock() }
if let existing = docs[url] { return existing }
let doc = PDFDocument(url: url)
docs[url] = doc
return doc
}
func releaseAll() {
lock.lock(); defer { lock.unlock() }
docs.removeAll()
}
}
Call PDFDocumentStore.shared.releaseAll() on memory warning.
How to prevent it
- Default to
PDFView– Only build a custom tiled viewer when you need behaviorPDFViewcannot provide. - Tile size 512 × 512 or larger – Reduces draw calls; the default 256 × 256 causes visible tile pop-in.
- Cache thumbnails to disk (JPEG, 0.7 quality) – Survives app restarts, avoids re-rasterizing on every launch.
- Render ahead on
userInitiatedqueue – Keep 2–3 pages each side of the focused page ready. - Cancel and purge aggressively – Cancel background ops for off-screen pages; drop
PDFPageLayercontents andPDFDocumenton memory warning. - Set interpolation quality to
.high– Produces better down-sampled thumbnails with negligible cost. - Avoid
UIImageat zoom > 1× – Switch toCATiledLayerthe moment the user pinches; a scaled-up bitmap looks blurry and wastes memory.
FAQ
Why does my custom PDF viewer still spike memory when zooming?
Even with CATiledLayer, each tile draws the entire page into the tile’s context at the current zoom scale. At 4× zoom a single tile covers 1/16 of the page but still requires the full page interpretation. Limit levelsOfDetail to 3–4 and use larger tileSize (512 or 1024) to reduce the number of tiles drawn per frame.
Can I use PDFKit for thumbnails and CATiledLayer for zoom?
Yes. PDFPage has a thumbnail(of:for:) method that returns a pre-scaled UIImage. Use it for the 1× placeholder, then hand the same PDFPage to your PDFPageLayer for tiled zoom drawing. This avoids duplicate rasterization code.
How do I handle PDF links and annotations in a custom viewer?
PDFPage exposes annotations (array of PDFAnnotation). Iterate them, convert each annotation’s bounds(for: .mediaBox) to view coordinates using the same CTM you use for drawing, and overlay UIButton or UIView hit-test areas. For links, inspect annotation.url or annotation.destination and navigate accordingly.
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.