I need to implement a functionality of creating pdf with multiple pages of a text.
class PDFCreator {
func prepareData() -> Data {
//1
let pdfMetaData = [
kCGPDFContextCreator: "PDF Creator",
kCGPDFContextAuthor: "Pratik Sodha",
kCGPDFContextTitle: "My PDF"
]
//2
let format = UIGraphicsPDFRendererFormat()
format.documentInfo = pdfMetaData as [String: Any]
//3
let pageWidth = 8.5 * 72.0
let pageHeight = 11 * 72.0
let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
//4
let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
//5
let data = renderer.pdfData { (context) in
//6
context.beginPage()
self.addText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", pageRect: pageRect)
}
return data
}
@discardableResult
func addText(_ text : String, pageRect: CGRect) -> CGFloat {
// 1
let textFont = UIFont.systemFont(ofSize: 60.0, weight: .regular)
// 2
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .natural
paragraphStyle.lineBreakMode = .byWordWrapping
// 3
let textAttributes = [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: textFont
]
let attributedText = NSAttributedString(string: text, attributes: textAttributes)
let textSize = attributedText.boundingRect(with: pageRect.size, options: [.usesFontLeading, .usesLineFragmentOrigin], context: nil)
// 4
let textRect = CGRect(x: 10,
y: 10,
width: pageRect.width - 20,
height: textSize.height)
attributedText.draw(in: textRect)
return textRect.origin.y + textRect.size.height
}
}
Using PDFCreator
class prepare pdf data and display using PDFView.
import UIKit
import PDFKit
class PDFPreviewViewController: UIViewController {
//1
@IBOutlet weak private var pdfView : PDFView!
override func viewDidLoad() {
super.viewDidLoad()
//2
let pdfData = PDFCreator().prepareData()
//3
pdfView.document = PDFDocument(data: pdfData)
pdfView.autoScales = true
}
}
Actual Output
Excepted Output
Whole text will be in PDF with new PDF page without decreasing font size.
Any help much appreciated. Thank you.
Output
Using PDFCreator class prepare pdf data and display using PDFView.