Create Documents with Document Writers - macOS Swift Console

This tutorial shows how to create a new PDF document and add pages to it in a macOS Swift Console application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to create documents and manipulate their pages in a macOS Swift Console application.
Completion Time 30 minutes
Project Download tutorial project (6 KB)
Platform Swift macOS Console Application
IDE Xcode
Runtime License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Create Documents with Document Writers - macOS Swift Console tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you do not have that project, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project. This tutorial requires the following Framework references located at <INSTALL_DIR>\LEADTOOLS22\Bin\Xcode\Frameworks\macOS:

Edit the Leadtools-Bridging-Header.h file to add the following imports:

#import <Leadtools.Codecs/Leadtools.Codecs.h> 
#import <Leadtools.Document.Writer/Leadtools.Document.Writer.h> 

For a complete list of which files are required for your application, refer to Files to be Included in your Application.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Note

Adding LEADTOOLS references and setting a license are covered in more detail in the Add References and Set a License tutorial.

Create a New PDF Document and Add Pages Code

With the project created, the references added, and the license set, coding can begin.

Using the Project Navigator, open main.swift. Add a new function named CreatePdfDocument() and call it underneath the call to SetLicense(). Add the code below to create a new PDF document and add the first page of each PDF file in a given directory to it.

func CreatePdfDocument() { 
    let codecs = LTRasterCodecs() 
    let dir = "/path/to/LEADTOOLS22/Resources/Images" 
    let outDir = "/path/to/LEADTOOLS22/Resources/Images" 
    let pageNumber = 1 
    let pdfFiles = GetFiles(directory: dir, extension: ".pdf") 
    let format = LTDocumentFormat.pdf 
    let outFile = String("\(outDir)/DocumentWriters.\(LTDocumentWriter.fileExtension(for: format))") 
 
    codecs.options.rasterizeDocument.load.xResolution = 300 
    codecs.options.rasterizeDocument.load.yResolution = 300 
 
    let docWriter = LTDocumentWriter(); 
    let pdfOptions = docWriter.options(for: format) as? LTPdfDocumentOptions 
 
    pdfOptions?.documentType = LTPdfDocumentType.pdfA 
    pdfOptions?.imageOverText = true 
    docWriter.setOptions(pdfOptions, for: format) 
 
    // Begin a new PDF Document 
    do { 
        try docWriter.beginDocument(fileName: outFile, format: format, progress: nil) 
    } catch { 
        print(error.localizedDescription) 
    } 
 
    // Add the pages 
    for file in pdfFiles { 
        let page = LTDocumentWriterSvgPage() 
        do { 
            let svgDoc = try codecs.loadSvg(file, page: pageNumber, options: nil) 
            page.svgDocument = svgDoc 
        } catch { 
            print(error.localizedDescription) 
        } 
        if pdfOptions?.imageOverText != nil { 
            // if we are using image/text, then load the overlay raster image 
            do { 
                try page.image = LTRasterImage.init(image: codecs.load(file: file, pageNumber: pageNumber)) 
            } catch { 
                print(error.localizedDescription) 
            } 
        } 
        // Add the page to the created PDF document 
        do { 
            try docWriter.add(page) 
            guard let filename = URL(string: file) else { continue } 
            print("Added page \(pageNumber) from \(filename.deletingPathExtension().lastPathComponent)\n") 
        } catch { 
            print("Error adding file: \(file)\n\(error.localizedDescription)") 
        } 
        // Dispose of resources 
        if page.svgDocument != nil { 
            page.svgDocument = nil 
        } 
        if page.image != nil { 
            page.image = nil 
        } 
    } 
    // Finalized document to disk 
    do { 
        try docWriter.endDocument(progress: nil) 
        print("PDF document saved successfully!") 
    } catch { 
        print(error.localizedDescription) 
    } 
} 

Additionally, add a helper function named GetFiles(directory: String, extension: String) -> [String]. Call this function inside the CreatePdfDocument() function, as shown above. Add the code to the new function to generate a list of PDF files.

func GetFiles(directory: String, extension: String) -> [String] { 
    var files: [String] = [] 
    let url = URL(fileURLWithPath: directory) 
    let fileManager = FileManager.default 
    let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: url.path)! 
    while let element = enumerator.nextObject() as? String { 
        guard element.hasSuffix(extension) else { continue } 
        let file = String("\(directory)/\(element)") 
        files.append(file) 
    } 
    return files 
} 

Run the Project

Clean the project to clear any errors by selecting Product -> Clean Build Folder or Shift + Command + K.

Run the project by selecting Product -> Run or Command + R.

If the steps were followed correctly, the application runs and creates a new PDF file containing all the first pages from each PDF file in the given directory, using LEADTOOLS SVG and Document Writers.

Screenshot of the console display.

Wrap-up

This tutorial showed how to create documents using the Document Writers. It also covered how to use the LTDocumentWriter, LTPdfDocumentOptions, LTDocumentWriterSvgPage, and LTRasterCodecs classes.

See Also

Help Version 22.0.2021.10.18
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2021 LEAD Technologies, Inc. All Rights Reserved.

Products | Support | Contact Us | Intellectual Property Notices
© 1991-2021 LEAD Technologies, Inc. All Rights Reserved.