Giter VIP home page Giter VIP logo

swifthtmlpdf's Introduction

SwiftHtmlPdf

CocoaPods compatible Platform iOS Swift 5 compatible License: MIT

Generate HTML and PDF documents by using template html files and filling them with your data.

This library allows you to generate HTML and PDF using HTML template files. Try out our example project!

Requirements

  • IOS 10 +

Installation

You can install SwiftHtmlPdf using Cocoa Pods.

Add SwiftHtmlPdf into your project's Podfile:

target 'MyApp' do
  pod 'SwiftHtmlPdf', '~> 1.0'
end

Then run the following command:

$ pod install

Usage

Create a html template resource and save it in your project

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta content="text/html; charset=utf-8" http-equiv="content-type">
		...
		</style>
	</head>
	<body>
        <h1>PDF Example</h1>
        <ul>
            <item name="MyListItem"/>
        </ul>
	</body>
</html>

<region name="MyListItem">
    <li>
        <field name="Name"/>
    </li>
</region>

Note the following HTML tags

  • <item name="MyListItem"/>
    • This is a reference to the MyListItem region.
  • <region name="MyListItem">...</region>
    • This is a blueprint for an instance of MyListItem
  • <field name="Name"/>
    • This is a field that will be replaced by a variable

Fill the template with data

First create your model and implement PDFComposerDelegate

import SwiftHtmlPdf
...
class MyListItem: PDFComposerDelegate {
    var name: String
    
    init(_ name: String) {
    	self.name = name
    }
    
    func valueForParameter(parameter: String, index: Int) -> String {
        switch parameter {
        case "Name":
            return name
        default:
            print("Unhandled PDF Key \(parameter) in MyListItem")
            return parameter
        }
    }
    
    func itemsForParameter(parameter: String, index: Int) -> [PDFComposerDelegate] {
        return []
    }
}

Now implement the delegate in your root object. In this case, the root object is the ViewController.

extension ViewController: PDFComposerDelegate {
    var myListItems = [MyListItem("Hello"), MyListItem("World")]
    
    func valueForParameter(parameter: String, index: Int) -> String {
    	return ""
    }
    
    func itemsForParameter(parameter: String, index: Int) -> [PDFComposerDelegate] {
        return myListItems
    }

Note the following delegate functions:

  • valueForParameter(parameter: String, index: Int)
    • This function is called for every <field name="{parameter}"/> in your template
  • func itemsForParameter(parameter: String, index: Int) -> [PDFComposerDelegate]
    • The function is called for every <item name="{parameter}"/> in the current region of the template
    • Return an array of child objects that will handle the region.
    • For every returned object, a new region will be instantiated: <region name="{parameter}">...</region>

Show a Preview Dialog in your app

func showPdfPreview() {
        let preview = PDFPreviewController.instantiate()
        
        do {
	    let resourceName = "planbuildpro-baukosten-template"
	    let delegate = self
            try preview.loadPreviewFromHtmlTemplateResource(templateResource: resourceName, delegate: delegate)

            present(preview, animated: true, completion: nil)
        } catch {
            print("Could not open pdf preview")
        }
    }
  • resourceName is the file name of the template html. Do not include the suffix (.html)
  • delegate is the View Controller (the root object)

Parsing templates without the Preview Dialog

To parse the html template without the preview dialog, you can the following function:

let htmlContent = PDFComposer.renderHtmlFromResource(templateResource: templateResource, delegate: delegate)

This function works similar to the preview dialog but returns parsed html.

Next up you can transform the html content into a PDF:

let pdfData = PDFComposer.exportHTMLContentToPDF(HTMLContent: htmlContent)

Alternatively you can use the following function to create a pdf file:

let pdfData = PDFComposer.exportHTMLContentToPDFFile(HTMLContent: htmlContent, path: path)

Now you can share the pdf using a UIActivityViewController:

let activityVC = UIActivityViewController(activityItems: [pdfData], applicationActivities: nil)
        
self.present(activityVC, animated: true, completion: nil)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.