Some test text!

Hamburger Icon

Office template generation in Swift

More languages

More languages
C# (.NET Core)
JS (Node.js)

Sample Swift code for using PDFTron SDK to generate a PDF from an Office document template and a JSON string. Does not require any external dependencies or MS Office licenses. Learn more about our Swift PDF Library and Office Template Generation.

Get Started Samples Download

To run this sample, get started with a free trial of Apryse SDK.

// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.

import PDFNet
import Foundation

// The following sample illustrates how to use the PTConvert utility class
// to convert MS Office files to PDF and replace templated tags present in the document
// with content supplied via json
// For a detailed specification of the template format and supported features,
// see:
// This conversion is performed entirely within the PDFNet and has *no*
// external or system dependencies -- Conversion results will be
// the same whether on Windows, Linux or Android.
// Please contact us if you have any questions.

func runOfficeToPDFTest() -> Int {
    return autoreleasepool {
        var ret = 0

        do {
            try PTPDFNet.catchException {
                let inputPath: String! = Bundle.main.path(forResource: "SYH_Letter.docx", ofType: "docx")
                let imagePath: String! = Bundle.main.path(forResource: "logo_red.png", ofType: "png")
                let outputPath: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("SYH_Letter.pdf").path
                let json: String = String(format:"""
                    "dest_given_name": "Janice N.",
                    "dest_street_address": "187 Duizelstraat",
                    "dest_surname": "Symonds",
                    "dest_title": "Ms.",
                    "land_location": "225 Parc St., Rochelle, QC ",
                    "lease_problem": "According to the city records, the lease was initiated in September 2010 and never terminated",
                    "logo": { "image_url": "%@", "width" : 64, "height":  64 },
                    "sender_name": "Arnold Smith"
                """, imagePath);

                // Start with a PDFDoc (the conversion destination)
                let pdfDoc: PTPDFDoc = PTPDFDoc()

                let options: PTOfficeToPDFOptions = PTOfficeToPDFOptions()

		        // perform the conversion with template delimiters and content dictionary
       pdfDoc, in_filename: inputPath, options: options)

       outputPath, flags: e_ptremove_unused.rawValue)

                print("Saved: \(outputPath)")
        } catch let e as NSError {
            ret = 1

        return ret