文字列・画像をPDF化
以下のコードはサイズとPDF化したい文字列、画像を受け取り、PDFをData型に変換して返す処理になります。
Data型で返しているので、返り値をそのままActivityViewControllerに渡せば、それでPDFの共有ができます。
調べるのにちょっと手こずったので備忘録として残しておきます。
import UIKit
import PDFKit
class PDFUtils {
var pdfData = NSMutableData()
var render = UIPrintPageRenderer()
let a3Width: CGFloat = 841.8
let a3Height: CGFloat = 1190.5
let a4Width: CGFloat = 595.2
let a4Height: CGFloat = 841.8
let a5Width: CGFloat = 419.5
let a5Height: CGFloat = 595.2
let b3Width: CGFloat = 1031.8
let b3Height: CGFloat = 1459.8
let b4Width: CGFloat = 728.5
let b4Height: CGFloat = 1031.8
let b5Width: CGFloat = 515.9
let b5Height: CGFloat = 728.5
func createPDFfromImages(images: [UIImage], size: String) -> Data {
let pdfData = NSMutableData()
for index in 0..<images.count {
UIGraphicsBeginPDFContextToData(pdfData, getPDFPageFrame(size: size), nil)
UIGraphicsBeginPDFPageWithInfo(getPDFPageFrame(size: size), nil)
guard let pdfContext = UIGraphicsGetCurrentContext() else { return Data() }
let imageView = UIImageView(frame: getPDFPageFrame(size: size))
imageView.image = images[index]
imageView.contentMode = .scaleAspectFit
imageView.layer.render(in: pdfContext)
UIGraphicsEndPDFContext()
}
return pdfData as Data
}
func createPDFfromString(size: String, text: String) -> Data {
render = UIPrintPageRenderer()
render.addPrintFormatter(UIMarkupTextPrintFormatter(markupText: text), startingAtPageAt: 0)
render.setValue(getPDFPageFrame(size: size), forKey: "paperRect")
render.setValue(getPDFPageFrame(size: size), forKey: "printableRect")
pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)
for i in 0..<render.numberOfPages {
UIGraphicsBeginPDFPage()
render.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())
}
UIGraphicsEndPDFContext()
return pdfData as Data
}
private func getPDFPageFrame(size: String) -> CGRect {
switch size {
case "A3": return CGRect(x: 0, y: 0, width: a3Width, height: a3Height)
case "A4": return CGRect(x: 0, y: 0, width: a4Width, height: a4Height)
case "A5": return CGRect(x: 0, y: 0, width: a5Width, height: a5Height)
case "B3": return CGRect(x: 0, y: 0, width: b3Width, height: b3Height)
case "B4": return CGRect(x: 0, y: 0, width: b4Width, height: b4Height)
case "B5": return CGRect(x: 0, y: 0, width: b5Width, height: b5Height)
default: return CGRect(x: 0, y: 0, width: a4Width, height: a4Height)
}
}
}