แสดง PDF ใน WebView (UIWebView / WKWebView) บน iOS
โหลดไฟล์ PDF จาก Bundle แล้วแสดงใน WebView ได้ง่ายๆ
ขั้นตอนที่ 1: สร้างโปรเจกต์
Xcode → Single View App → ชื่อ "PDFInWebView"
ขั้นตอนที่ 2: เพิ่ม UIWebView หรือ WKWebView ใน Storyboard
ลาก WebView มาเต็มหน้าจอ สร้าง IBOutlet ชื่อ webView
ขั้นตอนที่ 3: เพิ่มไฟล์ PDF เข้าโปรเจกต์
- ลากไฟล์ PDF (เช่น sample.pdf) เข้า Project Navigator
- ติ๊ก "Copy items if needed" และ Target Membership
ขั้นตอนที่ 4: โหลด PDF ใน viewDidLoad
ใช้ UIWebView (Legacy)
override func viewDidLoad() {
super.viewDidLoad()
if let pdfURL = Bundle.main.url(forResource: "sample", withExtension: "pdf") {
let request = URLRequest(url: pdfURL)
webView.loadRequest(request)
}
}
ใช้ WKWebView (แนะนำ iOS 8+)
import WebKit
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
if let pdfURL = Bundle.main.url(forResource: "sample", withExtension: "pdf") {
let request = URLRequest(url: pdfURL)
webView.load(request)
}
}
ขั้นตอนที่ 5: รันโปรเจกต์
PDF จะแสดงใน WebView พร้อม Zoom, Scroll, Page Navigation อัตโนมัติ
วิธีอื่น: ใช้ PDFKit (iOS 11+) - ควบคุมได้มากกว่า
import PDFKit
let pdfView = PDFView(frame: view.bounds)
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(pdfView)
if let pdfURL = Bundle.main.url(forResource: "sample", withExtension: "pdf"),
let document = PDFDocument(url: pdfURL) {
pdfView.document = document
pdfView.autoScales = true
pdfView.displayMode = .singlePageContinuous
pdfView.displayDirection = .vertical
}
คุณสมบัติ PDFKit
- Thumbnail Navigation, Bookmarks, Annotations
- Text Selection, Search, Outline (Table of Contents)
- Custom Page Rendering, Printing
โหลด PDF จาก URL (Remote)
// WKWebView
if let url = URL(string: "https://example.com/document.pdf") {
webView.load(URLRequest(url: url))
}
// PDFKit (ต้อง Download ก่อน)
let task = URLSession.shared.downloadTask(with: remoteURL) { localURL, _, _ in
guard let localURL = localURL,
let document = PDFDocument(url: localURL) else { return }
DispatchQueue.main.async {
pdfView.document = document
}
}
task.resume()
สรุป: เลือกไหนดี?
| ความต้องการ | แนะนำ |
|---|---|
| แค่แสดง PDF เรียบง่าย | WKWebView |
| ต้องการควบคุม: Zoom, Search, Bookmark, Annotation | PDFKit (PDFView) |
| Legacy Support (iOS < 8) | UIWebView (Deprecated) |