yuqi6713 / SimplePDFBuilder

Simple tool to create complex PDF files easily.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SimplePDFBuilder

Simple tool to create complex PDF files easily.

Introduction

SimplePDFBuilder is a library built on top of PDFKit which enables you to easily create PDF files in your app. This is a customisable library that allows you to add text, images and other elements including complex tables, making the creation of PDF files very simple, with no need to draw everything from scratch.

Table of Contents

Installation

If you are new to cocoapods read this first.

Firstly, go to terminal and navigate to your project. Then execute command pod init and open the created Podfile.

You want to add pod 'SimplePDFBuilder', '~> 0.1':

target 'YourAppName' do
  pod 'SimplePDFBuilder', '~> 0.1'
end

Then run pod install inside your terminal.

After installation make sure you open .xcworkspace project and NOT .xcodeproj

How to use PDFBuilder

In order to create a simple PDF file with no content in it, you need to import SimplePDFBuilder where you want to use it:

import SimplePDFBuilder

To build pdf data:

You can use like this: OR like this:
  let pdf = PDFBuilder()
  //pdf.someChosenMethod ...
  let pdfData = pdf.build()
let pdfData = PDFBuilder()
                 //.someChosenMethod ...
                 .build()

pdfData contains the data of the PDF which is used in PDFView's document property of PDFKit. See section How to create a custom PDF Preview for more information.

PDF Document parameters

In order to add metadata to your PDF File use the following:

(Example shows a creation of an empty PDF file with Meta Data)

let data = PDFBuilder()
            .withMetaAuthor("AuthorName")
            .withMetaCreator("CreatorName")
            .withMetaTitle("Title")
            .build()

There are a few additional parameters that can be set:

(Example shows a creation of an empty PDF file with default parameters)

let pdf = PDFBuilder()
pdf.withPaperSize(.A4)              // default value
pdf.withPaperOrientation(.Portrait) // default value
pdf.withTextSpacing(1.08)           // default value (Also Word's default)
pdf.withPaperMargins(.Normal)       // default value
let data = pdf.build()
  • withPaperSize: Support paper sizes from .A1 to .A7
  • withPaperOrientation: can be .Album or .Portrait
  • withTextSpacing: Spacing of the text in CGFloat
  • withPaperMargins:
    • .Normal - Inch (2.54cm) on each side
    • .Narrow - Half inch (1.27cm) on each side
    • .Moderate - Inch (2.54cm) for top and bottom and 0.75 inch (or 1.91 cm) for left and right
    • .Wide - Inch (2.54cm) for top and bottom and 2 inches (5.08 cm) for left and right

Adding Text

To add text addText method is used. Added text can be multiline, meaning that if the string is too long for a single line, it will wrap the text around to the next lines.

pdf.addText(text: "BILL TO:", 
            alignment: .left,             // default value
            font: .boldArial(ofSize: 11), // default value
            colour: .black)               // default value
  • alignment - Alignment of the text on the page
  • font - Font of the text
  • colour - Colour of the text

See example on the right:

pdf.addText(text: "Text", alignment: .left, font: .boldSystemFont(ofSize: 30))
pdf.addText(text: "Text", alignment: .centre, font: .boldSystemFont(ofSize: 25))
pdf.addText(text: "Text", alignment: .right, font: .systemFont(ofSize: 20))
pdf.addText(text: someLongText)

Adding Images

In order to add image to the PDF use:

pdf.addImage(image: UIImage(named:"Put Your Image Here"), 
             maxWidth: 150, 
             alignment: .right)
  • image - UIImage that you want to present on the PDF
  • maxWidth - Width of the image in points (72 points is 1 inch)
  • alignment - Alignment of the text on the page

See example on the right:

pdf.addImage(image: #imageLiteral(resourceName: "ShowLogo"), maxWidth: 300, alignment: .left)
pdf.addSpace(inches: 1)
pdf.addImage(image: #imageLiteral(resourceName: "ShowLogo"), maxWidth: 200, alignment: .centre)
pdf.addSpace(inches: 1)
pdf.addImage(image: #imageLiteral(resourceName: "ShowLogo"), maxWidth: 150, alignment: .right)

To understand what addSpace does refer to Adding Spaces section

Adding a Footer

To add a footer to the PDF use:

pdf.addFooter(pagingEnabled: true,
              text: "© Company copyrights reserved example.",
              colour: UIColor.black.withAlphaComponent(0.5))

However, if a footer is being added from the current PDF page, the footer will be drawn only from the second page (example):

pdf.newPage()  // start new PDF page
pdf.addFooter(pagingEnabled: true,
              text: "© Company copyrights reserved example.",
              colour: UIColor.black.withAlphaComponent(0.5))

Adding Tables

To create tables you will first have to create headers and rows. If the rows reach the bottom margin, then a new PDF page will start

Create headers as follows:

let headers = [ PDFColumnHeader(name: "QTY",         alignment: .left,    weight: 1),
                PDFColumnHeader(name: "DESCRIPTION", alignment: .centre,  weight: 4),
                PDFColumnHeader(name: "PRICE",       alignment: .right,   weight: 2)]
  • name - Text that will be shown in Table Column's header
  • alignment - Alignment of the whole column
  • weight - Weight of the column in comparison with others. In the above example, the 2nd column is 4 times wider than first column and twice as wide as the 3rd

Create table rows as follows:

let tableRows = [ PDFTableRow(["1",  "description",  "10"]),
                  PDFTableRow(["2",  "description",  "15"]) ]

Draw table from headers and table rows:

do {
    try pdf.addTable(headers: headers, 
                     rows: tableRows, 
                     tableStyle: .Modern,           // Default value
                     font: .systemFont(ofSize: 11), // Default value
                     tableColour: .darkGray)        // Default value
} catch {
    print(error.localizedDescription)
}
  • tableColour - Theme colour of the table
  • font - Font of the text in the table
  • tableStyle - Currently 2 types are supported:

PDF Table styles

Modern Strict
Modern PDF Table Style Strict PDF Table Style

Adding Spaces

There are to ways of creating space: In inches and in centimeters

pdf.addSpace(inches: 1.25)
pdf.addSpace(centimeters: 3.4)

pdf.addSpace(inches: -0.5) //Note: it can be negative if needed

Start New PDF Page

To start a new page of the PDF use:

pdf.newPage()

Example of using newPage:

let data = PDFBuilder()
            .addText(text: "First page text", alignment: .centre, font: .boldSystemFont(ofSize: 30))
            .newPage()
            .addText(text: "Second page text", alignment: .centre, font: .boldSystemFont(ofSize: 30))
            .build()

Line holding

Line holding allows you to draw multiple elements with the same top offset in the page.

pdf.holdLine()
pdf.addText(text: "LEFT TEXT", font: .systemFont(ofSize: 20))
pdf.addText(text: "CENTER TEXT", alignment: .centre, font: .systemFont(ofSize: 20))
pdf.addText(text: "RIGHT TEXT", alignment: .right, font: .systemFont(ofSize: 20))
pdf.releaseLine()

pdf.addSpace(inches: 1)

pdf.holdLine()
pdf.addImage(image: #imageLiteral(resourceName: "ShowLogo"), maxWidth: 200,alignment: .left)
pdf.addImage(image: #imageLiteral(resourceName: "ShowLogo"), maxWidth: 200,alignment: .right)
pdf.releaseLine()

How to use built-in PDF Preview View Controller

The library comes with a built-in controller called PDFPreviewVC. It is shown at the very top (first image) of the readme. If you want to use it, here is the code. Make sure your app uses NavigationController:

let pdf = PDFBuilder()

pdf.wihMetaAuthor("Maks")
pdf.withMetaCreator("Maks")
pdf.withMetaTitle("My PDF")

pdf.addFooter(pagingEnabled: true,
              text: "© Company copyrights reserved footer.",
              colour: UIColor.black.withAlphaComponent(0.5))

pdf.addText(text: "Sample text")


// Build PDF Data
let data = pdf.build()

let pdfController = PDFPreviewVC(pdfData: data)
navigationController?.pushViewController(pdfController, animated: true)

PDFPreviewVC View Controller has a few parameters that can be passed:

let pdfController = PDFPreviewVC(pdfData: data,
                                 pdfFileName: "Testname",
                                 removeFileOnClose: true)  // Default value
  • pdfData - PDF Data that was generate by PDFBuilder using .build()
  • pdfFileName - If the user will decide to share the file, that will be a name of it.
  • removeFileOnClose - In order to rename and share the file, the app saves it to temporary directory of the app and then shares it. If you don't want to keep the files, set it to true and it will be removed on ViewController's dismissal.

How to create a custom PDF Preview

If you want to build your custom ViewController as a PDF Preview, firstly you will have to include:

import PDFKit

You will have to create a property in your View Controller:

private var pdfView = PDFView()

Example of Custom PDF View Controller:

import UIKit
import PDFKit

class CustomPDFViewController: UIViewController {

    var pdfData: Data?
    private var pdfView = PDFView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        pdfView.backgroundColor = .white
        view.addSubview(pdfView)
        pdfView.translatesAutoresizingMaskIntoConstraints = false
        pdfView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
        pdfView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
        pdfView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
        pdfView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
        
        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.displaysPageBreaks = true
        
        
        // Create PDFDocument from data
        guard let data = pdfData else { return }
        pdfView.document = PDFDocument(data: data)
        pdfView.autoScales = true
    }

}

Then to use it do this in your method where you want to create PDF:

let pdfData = PDFBuilder()
                .addText(text: "First page text")
                .build()
        
let customPDFViewController = CustomPDFViewController()
customPDFViewController.pdfData = pdfData

self.present(customPDFViewController, animated: true)

License

License

About

Simple tool to create complex PDF files easily.

License:MIT License


Languages

Language:Swift 97.8%Language:Ruby 1.5%Language:Objective-C 0.7%