LoginSignup
2
3

More than 5 years have passed since last update.

iOSでPDFを表示してみる

Last updated at Posted at 2018-05-27

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みたいなアプリも作れそうですね

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3