About PDFKit learning project on iOS 11, Like iBooks.app.

Related tags

PDF pdfkit ibook
Overview

iBook

About PDFKit learning project on iOS 11, Like iBooks.app.

书库

书库页面获取PDF相关数据, 可以通过KVC获取。

  • PDF书名
if let title = documentAttributes["Title"] as? String {
    cell.title = title
}
  • PDF作者
if let author = documentAttributes["Author"] as? String {
	 cell.author = author
}
  • 获取第一页作为封面,封面已经做了缓存
let thumbnailCache = NSCache<NSURL, UIImage>()
private let downloadQueue = DispatchQueue(label: "com.jovins.pdfview.thumbnail")
if let page = document.page(at: 0), let key = document.documentURL as NSURL? {     
    cell.url = key
    if let thumbnail = thumbnailCache.object(forKey: key) {
        cell.image = thumbnail
    } else {
        downloadQueue.async {
            let imgWidth: CGFloat = (UIScreen.main.bounds.width - 48)/2 - 24
            let imgHeight: CGFloat = 190
            let thumbnail = page.thumbnail(of: CGSize(width: imgWidth, height: imgHeight), for: .cropBox)
            self.thumbnailCache.setObject(thumbnail, forKey: key)
            if cell.url == key {
                DispatchQueue.main.async {
                    cell.image = thumbnail
                }
            }
        }
    }
}

初始化一个DocumentModel模型存储PDFDocument数据。

struct DocumentModel {
    
    var title: String = ""
    var author: String = ""
    var coverImage: UIImage?
    var url: URL?
}
0, let page = document.page(at: 0) { let imgWidth: CGFloat = (UIScreen.main.bounds.width - 48)/2 - 24 let imgHeight: CGFloat = 190 let thumbnail = page.thumbnail(of: CGSize(width: imgWidth, height: imgHeight), for: .cropBox) model.coverImage = thumbnail } if let url = document.documentURL { model.url = url } } return model } } ">
class BookManager {
    
    static let shared = BookManager()
    
    func getDocument(_ pdfDoc: PDFDocument?) -> DocumentModel {
        
        var model = DocumentModel()
        if let document = pdfDoc, let documentAttributes = document.documentAttributes {
            if let title = documentAttributes["Title"] as? String {
                model.title = title
            } else {
                model.title = "No Title"
            }
            
            if let author = documentAttributes["Author"] as? String {
                model.author = author
            } else {
                model.author = "No Author"
            }
            
            if document.pageCount > 0, let page = document.page(at: 0) {
                let imgWidth: CGFloat = (UIScreen.main.bounds.width - 48)/2 - 24
                let imgHeight: CGFloat = 190
                let thumbnail = page.thumbnail(of: CGSize(width: imgWidth, height: imgHeight), for: .cropBox)
                model.coverImage = thumbnail
            }
            
            if let url = document.documentURL {
                model.url = url
            }
        }
        return model
    }
}

PDF浏览

 
 

图一是PDF浏览详情页

private lazy var pdfView: PDFView = {  
    let view = PDFView()
    view.backgroundColor = Device.bgColor
    view.autoScales = true
    view.displayMode = .singlePage
    view.displayDirection = .horizontal
    view.usePageViewController(true, withViewOptions: [UIPageViewController.OptionsKey.spineLocation: 20])
    return view
}()
self.pdfView.document = self.document

图二是该PDF的所有页面

/// 该页面的核心代码
if let doc = self.document, let page = doc.page(at: indexPath.item) {   
    let pageNumber = indexPath.item
    cell.pageNumber = pageNumber
    let key = NSNumber(value: pageNumber)
    if let thumbnail = self.thumbnailCache.object(forKey: key) {
        cell.image = thumbnail
    } else {
        let cellSize = CGSize(width: (UIScreen.main.bounds.width - 16 * 4)/3, height: 140)
        downloadQueue.async {
            let thumbnail = page.thumbnail(of: cellSize, for: .cropBox)
            self.thumbnailCache.setObject(thumbnail, forKey: key)
            if cell.pageNumber == pageNumber {
                DispatchQueue.main.async {
                    cell.image = thumbnail
                }
            }
        }
    }
}

图三是该PDF的目录

/// 该页面核心代码
let outline = self.lines[indexPath.item]
cell.titleString = outline.label
cell.pageString = outline.destination?.page?.label

var indentationLevel = -1
var parent = outline.parent
while let _ = parent {
    indentationLevel += 1
    parent = parent?.parent
}
cell.indentationLevel = indentationLevel

图四是浏览时收藏的页面。

/// 获取收藏页
if let documentURL = self.document?.documentURL?.absoluteString, let bookmarks = UserDefaults.standard.array(forKey: documentURL) as? [Int] {
    self.bookmarks = bookmarks
    self.collection.reloadData()
}
// 显示收藏
let pageNumber = self.bookmarks[indexPath.item]
if let page = self.document?.page(at: pageNumber) {
    cell.pageNumber = pageNumber
    let key = NSNumber(value: pageNumber)
    if let thumbnail = self.thumbnailCache.object(forKey: key) {
        cell.image = thumbnail
    } else {
        let cellSize = CGSize(width: (UIScreen.main.bounds.width - 16 * 4)/3, height: 140)
        downloadQueue.async {
            let thumbnail = page.thumbnail(of: cellSize, for: .cropBox)
            self.thumbnailCache.setObject(thumbnail, forKey: key)
            if cell.pageNumber == pageNumber {
                DispatchQueue.main.async {
                    cell.image = thumbnail
                }
            }
        }
    }
}

打印,直接调取系统方法。

let printInteractionController = UIPrintInteractionController.shared
printInteractionController.printingItem = self.document?.dataRepresentation()
printInteractionController.present(animated: true, completionHandler: nil)

阅读历史

 

在浏览页存储历史记录

private func storgeHistoryList() {
    if let documentURL = self.document?.documentURL?.absoluteString {
        let cache = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].absoluteString
        let key = cache.appending("com.jovins.ibook.storgeHistory")
        if var documentURLs = UserDefaults.standard.array(forKey: key) as? [String] {
            if !documentURLs.contains(documentURL) {
                // 不存在则存储
                documentURLs.append(documentURL)
                UserDefaults.standard.set(documentURLs, forKey: key)
            }
        } else {
            // 第一次存储
            UserDefaults.standard.set([documentURL], forKey: key)
        }
    }
}

获取已浏览的记录

fileprivate func refreshData() {
        
    let cache = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].absoluteString
    let key = cache.appending("com.jovins.ibook.storgeHistory")
    if let documentURLs = UserDefaults.standard.array(forKey: key) as? [String] {
        var urls: [URL] = []
        for str in documentURLs {
            if let url = URL(string: str) {
                urls.append(url)
            }
        }
        self.documents = urls.compactMap { PDFDocument(url: $0) }
        self.tableView.reloadData()
    }
}

搜索

通过PDFDocument设置代理,然后调用beginFindString可以实现搜索功能。

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    let searchText = searchBar.text!.trimmingCharacters(in: CharacterSet.whitespaces)
    if searchText.count < 3 {
        return
    }
    self.searchResults.removeAll()
    self.tableView.reloadData()
    if let document = self.document {
        document.cancelFindString()
        document.delegate = self
        document.beginFindString(searchText, withOptions: .caseInsensitive)
    }
}
/// 代理实现的方法,可以获取到搜索结果
func didMatchString(_ instance: PDFSelection) {
    self.searchResults.append(instance)
    self.tableView.reloadData()
}

未来

该项目未来会增加txtepub浏览功能。

You might also like...
Merges a given number of PDF files into one file using the PDFKit framework

Titanium iOS PDF Merge Merges a given number of PDF files into one file using the PDFKit framework Requirements iOS 11+ Titanium SDK 9+ API's Methods

iOS app for Technex, IIT(BHU) Varanasi. This project is closed before completion. You can use this app for learning purpose. You can use this app as a templet of any event related app.
iOS app for Technex, IIT(BHU) Varanasi. This project is closed before completion. You can use this app for learning purpose. You can use this app as a templet of any event related app.

technex-ios iOS app for Technex, IIT(BHU) Varanasi. This project is closed before completion for some reasons. You can use this app for learning purpo

an IOS learning project built with swift
an IOS learning project built with swift

BMI Calculator Project Goal The goal of this tutorial is to learn more about Optionals, solidify your understanding of the MVC design pattern and to i

The SwiftUI learning project.
The SwiftUI learning project.

The SwiftUI learning project.

Example project which uses Machine Learning frameworks to detect things

ML_IOS Example project which uses Machine Learning frameworks to detect things. Features Object Detection Text Detection Face Detection Audio Detectio

This is an open-source project for the aesthetic evaluation of images based on the deep learning-caffe framework, which we completed in the Victory team of Besti.
This is an open-source project for the aesthetic evaluation of images based on the deep learning-caffe framework, which we completed in the Victory team of Besti.

This is an open-source project for the aesthetic evaluation of images based on the deep learning-caffe framework, which we completed in the Victory team of Besti.

VRTracerSample - Learning project in Metal Ray Tracing and Swift
VRTracerSample - Learning project in Metal Ray Tracing and Swift

VRTracer This is a personal project for learning Metal's Ray Tracing API with sw

HotCoffee is learning project with MVVM, Generic,Swift 5, TableView

HotCoffee A simple Coffee Ordering app built using TableView, MVVM design pattern and Swift5. Tools Xcode Version 13.2.1 Framework -UIKit Architecture

Swipe to "like" or "dislike" any view, just like Tinder.app. Build a flashcard app, a photo viewer, and more, in minutes, not hours!

MDCSwipeToChoose Swipe to "like" or "dislike" any view, just like Tinder.app. Build a flashcard app, a photo viewer, and more, in minutes, not hours!

Demo of iOS app that recognizes finger heart by machine learning
Demo of iOS app that recognizes finger heart by machine learning

HandPoseClassificationAR Demo of iOS app that recognizes finger heart by machine learning How to build 1, Download or Clone this project and open in x

Basic Stop Watch & Countdown app for iOS devices. Created for learning purpose.
Basic Stop Watch & Countdown app for iOS devices. Created for learning purpose.

stopwatch Basic Stop Watch (included Countdown feature) app for iOS devices. Created for learning purpose. How to use Just download source code and un

Basic calculator app for iOS devices using Swift3. Created for learning purpose.
Basic calculator app for iOS devices using Swift3. Created for learning purpose.

iOS Calculator App Basic calculator app for iOS devices using Swift 4 and Xcode 9. Created for learning purpose. How to use Just download source code

Cardshark is an iOS card counting App that uses state of the art machine learning (YOLO) to classify and count the cards at real time.

Cardshark The game of Blackjack is one of the most popular casino games in the world. It is also the most winnable using a skill called Card Counting.

Unit-Converter-SwiftUI - A simple Unit Converter iOS app built in the process of learning SwiftUI
Unit-Converter-SwiftUI - A simple Unit Converter iOS app built in the process of learning SwiftUI

SwiftUI-Unit-Converter A simple Unit Converter iOS app built in the process of l

A clone for netflix iOS app for learning.

Netflix Clone 🇧🇷 Um clone do aplicativo da Netflix voltado para estudos, em Swift, voltado para iOS. O aplicativo conta com uma home, tela de novida

I am learning to build an iOS app with SwiftUI.
I am learning to build an iOS app with SwiftUI.

ios-quiz-app I am learning to build an iOS app with SwiftUI. This is a quiz app with SwiftUI although tutorial was on UIKit Challenges Faced navigatio

Display Apple system-like self-hiding status alerts. It is well suited for notifying user without interrupting user flow in iOS-like way.
Display Apple system-like self-hiding status alerts. It is well suited for notifying user without interrupting user flow in iOS-like way.

StatusAlert is being sponsored by the following tool; please help to support us by takin a look and signing up to a free trial. Dependency managers Fe

Basic app to show how to login with Facebook, Google, Twitter. Created for learning purpose :) using Xcode 9 and Swift 4.0
Basic app to show how to login with Facebook, Google, Twitter. Created for learning purpose :) using Xcode 9 and Swift 4.0

Social Logins iOS Basic app to show how to login with Facebook, Google, Twitter. Created for learning purpose :) using Xcode 9 and Swift 4.0 Note: Bef

Learning App with Firebase Auth
Learning App with Firebase Auth

Learning App Displays how to make a learning app with Swift, iOS's programming l

Owner
Jovins
work hard, play hard.
Jovins
Draw Week Time Table on PDF using PDFKit in iOS Swift

DrawPDFTimeTable Draw Week Time Table on PDF using PDFKit in iOS Swift. Image Info This is the pdf of time table drawn using PDFKit in iOS Swift with

Kushagra Chandra 6 Nov 22, 2022
An iOS PDF viewer and annotator written in Swift that can be embedded into any application.

Requirements iOS 9 or above Xcode 8 or above Swift 3.0 Note This project is still in early stages. Right now the PDF reader works both programmaticall

UXM Studio 269 Dec 11, 2022
PDF Reader Core for iOS

PDF Reader Core for iOS This project is no longer supported or maintained. It is only here for historical reasons. Please see the UXReader PDF Framewo

Julius Oklamcak 4.3k Jan 6, 2023
📚 A Swift ePub reader and parser framework for iOS.

FolioReaderKit is an ePub reader and parser framework for iOS written in Swift. Features ePub 2 and ePub 3 support Custom Fonts Custom Text Size Text

FolioReader 2.5k Jan 8, 2023
TPPDF is a simple-to-use PDF builder for iOS

TPPDF is a fast PDF builder for iOS & macOS using simple commands to create advanced documents! Created and maintained by Philip Niedertscheider and a

techprimate 582 Jan 6, 2023
A Static Library to be embedded on iOS applications to display pdf documents derived from Fast PDF

FastPdfKit This repository contains the FastPdfKit iOS library with some sample projects. FastPdfKit is a library that let you show pdf documents in i

Dimension 1.2k Dec 22, 2022
Small utility to import PDF slides as vector images into Keynote for iOS.

Small utility to import PDF files into Keynote for iOS. This utility is especially helpful when presenting slideshows created by LaTeX

Luming Yin 6 Jun 14, 2022
TPPDF is a simple-to-use PDF builder for iOS

TPPDF is a fast PDF builder for iOS & macOS using simple commands to create advanced documents! Created and maintained by Philip Niedertscheider and a

techprimate 581 Dec 29, 2022
PDFSelectionSample - The project for Apple engineers debugging PDFKit selection

PDFSelectionSample This is the project for Apple engineers debugging PDFKit sele

wyh 1 Dec 28, 2021
Draw Week Time Table on PDF using PDFKit in iOS Swift

DrawPDFTimeTable Draw Week Time Table on PDF using PDFKit in iOS Swift. Image Info This is the pdf of time table drawn using PDFKit in iOS Swift with

Kushagra Chandra 6 Nov 22, 2022