Some test text!

platform
search
< iOS samples

DOCX to PDF Conversion in Swift

Sample Swift code to use PDFTron SDK for direct, high-quality Word to PDF conversion by using the pdftron.PDF.Convert utility class. This conversion is performed entirely within PDFTron SDK and has no external or system dependencies. Conversion results will be the same on all platforms. Learn more about our PDF 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-2017 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
// .docx 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 WordToPDFTest: NSObject {
    class func simpleDocxConvert(inputPath: String, outputPath: String) {
        // Start with a PDFDoc (the conversion destination)
        let pdfDoc: PTPDFDoc = PTPDFDoc()
        
        // perform the conversion with no optional parameters
        PTConvert.word(toPDF: pdfDoc, in_filename: inputPath, options: nil)
        
        pdfDoc.save(toFile: outputPath, flags: e_ptremove_unused.rawValue)
        
        print("Saved: \(outputPath)")
    }
    
    class func flexibleDocxConvert(inputPath: String, outputPath: String, pluginPath: String) -> Bool {
        // Start with a PDFDoc (the conversion destination)
        let pdfDoc: PTPDFDoc = PTPDFDoc()
        
        let options: PTWordToPDFOptions = PTWordToPDFOptions()
        options.setSmartSubstitutionPluginPath(pluginPath)
        
        // create a conversion object with optional parameters
        let conversion: PTDocumentConversion = PTConvert.word(toPDFConversion: 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 runWordToPDFTest() -> 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
                    WordToPDFTest.simpleDocxConvert(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
                    _ = WordToPDFTest.flexibleDocxConvert(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
                    WordToPDFTest.simpleDocxConvert(inputPath: inputPath, outputPath: outputPath)
                }
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        return ret
    }
}