Some test text!

Search
Hamburger Icon

Convert Office documents (Excel word PowerPoint) to PDF using Swift

More languages

More languages
Java (Android)
C++
C#
C# (.NET Core)
Go
Java
Kotlin
Obj-C
JS (Node.js)
PHP
Python
Ruby
Swift
C# (UWP)
VB
C# (Xamarin)

Sample Swift code for using Apryse 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 Swift PDF Library and Office Document Conversion Library.

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 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
    }
}