3
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

iOSでPDFを表示してみる

iOSでPDFを表示する方法を知らなかったのでメモ書き

//: Playground - noun: a place where people can play

import PlaygroundSupport
import UIKit
import CoreGraphics

class PDFView: UIView {
    var page: CGPDFPage?

    override func draw(_ rect: CGRect) {
        guard let page = page else { return }

        guard let context = UIGraphicsGetCurrentContext() else {
            fatalError()
        }

        context.translateBy(x: 0, y: rect.size.height)
        context.scaleBy(x: 1.0, y: -1.0)

        let box = page.getBoxRect(.mediaBox)

        let xScale = rect.size.width / box.size.width
        let yScale = rect.size.height / box.size.height
        let scale = min(xScale, yScale)

        let tx = (rect.size.width - box.size.width * scale) / 2
        let ty = (rect.size.height - box.size.height * scale) / 2

        context.translateBy(x: tx, y: ty)
        context.scaleBy(x: scale, y: scale)
        context.drawPDFPage(page)
    }
}

guard let url = NSURL(string: "http://devstreaming.apple.com/videos/wwdc/2016/402h429l9d0hy98c9m6/402/402_whats_new_in_swift.pdf"), let doc = CGPDFDocument(url) else {
    fatalError()
}

let pageCount = doc.numberOfPages
let number = 1
let page = doc.page(at: number)

let view = PDFView(frame: UIScreen.main.bounds)
view.backgroundColor = UIColor.lightGray
view.page = page

PlaygroundPage.current.liveView = view

上のコードはPlaygroundで検証しました。PlaygroundPage.current.liveView = viewでPlaygroundでもViewの検証ができます。

20161111181540.png

今回はシングルページの表示ですが、doc.page(at: number)でページを切り替えれるので、簡単にPDFViewerみたいなアプリも作れそうですね

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
3
Help us understand the problem. What are the problem?