Some test text!

< iOS samples

Convert Office Documents (Excel, Word, PowerPoint) to PDF using Swift

Sample Swift code for using PDFTron SDK to convert Office documents to PDF (including Word, Excel, PowerPoint and Publisher) without needing any external dependencies or MS Office licenses. Office to PDF conversion can be performed on a Linux or Windows server to automate Office-centric workflows, or entirely in the user's client (web browser, mobile device). The conversion functionality can be combined with our Viewer to display or annotate Office files (docx, xlsx, pptx) on all major platforms, including Web, Android, iOS, Xamarin, UWP, and Windows. Learn more about our Office Document Conversion Library.

Step 1: Get your free trial license key, or sign in

Start Trial
Sign in

Step 2: Add the code:

//---------------------------------------------------------------------------------------
// 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 PDF::Convert utility class to convert
// MS office files to PDF
//
// This conversion is performed entirely within the PDFNet and has *no* external or
// system dependencies dependencies -- Conversion results will be the same whether
// on Windows, Linux or Android.
//
// Please contact us if you have any questions.
//---------------------------------------------------------------------------------------

class OfficeToPDFTest: NSObject {
    class func simpleConvert(inputPath: String, outputPath: String) {
        // Start with a PDFDoc (the conversion destination)
        let pdfDoc: PTPDFDoc = PTPDFDoc()

        // perform the conversion with no optional parameters
        PTConvert.office(toPDF: pdfDoc, in_filename: inputPath, options: nil)

        pdfDoc.save(toFile: outputPath, flags: e_ptremove_unused.rawValue)

        print("Saved: \(outputPath)")
    }

    class func flexibleConvert(inputPath: String, outputPath: String, pluginPath: String) -> Bool {
        // Start with a PDFDoc (the conversion destination)
        let pdfDoc: PTPDFDoc = PTPDFDoc()

        let options: PTOfficeToPDFOptions = PTOfficeToPDFOptions()
        options.setSmartSubstitutionPluginPath(pluginPath)

        // create a conversion object with optional parameters
        let conversion: PTDocumentConversion = PTConvert.streamingPDFConversion(with: pdfDoc, in_filename: inputPath, options: options)
        print(String(format: "\(inputPath): %.0f%% \(conversion.getProgressLabel()!)", conversion.getProgress() * 100.0))

        // convert each page, and report progress
        while conversion.getStatus() == e_ptIncomplete {
            conversion.convertNextPage()
            print(String(format: "\(inputPath): %.0f%% \(conversion.getProgressLabel()!)", conversion.getProgress() * 100.0))
        }

        if conversion.tryConvert() == e_ptSuccess {
            // print out any extra information about the conversion
            let num_warnings: UInt32 = conversion.getNumWarnings()
            for i in 0..<num_warnings {
                print("Warning: \(conversion.getWarningString(i)!)")
            }

            //save the result
            pdfDoc.save(toFile: "\(outputPath)", flags: e_ptremove_unused.rawValue)

            print("Saved: \(outputPath)")

            return true
        }
        else {
            print("Encountered an error during conversion: \(conversion.getErrorString()!)")
        }

        return false
    }
}

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


        do {
            try PTPDFNet.catchException {
                do {
                    let inputPath: String! = Bundle.main.path(forResource: "simple-word_2007", ofType: "docx")
                    let outputPath: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("simple-word_2007_a.pdf").path

                    // convert using the simple one-line interface
                    OfficeToPDFTest.simpleConvert(inputPath: inputPath, outputPath: outputPath)
                }

                do {
                    let inputPath: String! = Bundle.main.path(forResource: "the_rime_of_the_ancient_mariner", ofType: "docx")
                    let outputPath: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("the_rime_of_the_ancient_mariner.pdf").path

                    // convert using the more flexible page-by-page interface
                    _ = OfficeToPDFTest.flexibleConvert(inputPath: inputPath, outputPath: outputPath, pluginPath: Bundle.main.resourcePath!)
                }

                do {
                    let inputPath: String! = Bundle.main.path(forResource: "wrap_poly_demo", ofType: "docx")
                    let outputPath: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("wrap_poly_demo.pdf").path

                    // convert a document with a complex layout
                    OfficeToPDFTest.simpleConvert(inputPath: inputPath, outputPath: outputPath)
                }
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }

        return ret
    }
}