Some test text!

Discord Logo

Chat with us

PDFTron is now Apryse, learn more here.

Merge, copy, delete and rearrange PDF pages in Swift

More languages

More languages
JavaScript
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 PDFTron SDK to copy pages from one document to another, delete and rearrange pages, and use ImportPages() method for very efficient copy and merge operations. Learn more about our Swift PDF Library and PDF Editing & Manipulation 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

func runPDFPageTest() -> Int {
    return autoreleasepool {
        var ret = 0
        
        
        // Sample 1 - Split a PDF document into multiple pages
        do {
            try PTPDFNet.catchException {
                print("_______________________________________________")
                print("Sample 1 - Split a PDF document into multiple pages...")
                print("Opening the input pdf...")
                let in_doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                in_doc.initSecurityHandler()
                
                let page_num = in_doc.getPageCount()
                for i in 1...page_num {
                    let new_doc: PTPDFDoc = PTPDFDoc()
                    let output_file: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_split_page_\(i).pdf").path
                    new_doc.insertPages(0, src_doc: in_doc, start_page: i, end_page: i, flag: e_ptinsert_none)
                    new_doc.save(toFile: output_file, flags: e_ptremove_unused.rawValue)
                    print("Done. Result saved in newsletter_split_page_\(i).pdf")
                }
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        // Sample 2 - Merge several PDF documents into one
        do {
            try PTPDFNet.catchException {
                print("_______________________________________________")
                print("Sample 2 - Merge several PDF documents into one...")
                let new_doc: PTPDFDoc = PTPDFDoc()
                new_doc.initSecurityHandler()
                
                let page_num: Int = 15
                for i in 1...page_num {
                    let input_file: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_split_page_\(i).pdf").path
                    print("Opening newsletter_split_page_\(i).pdf")
                    let in_doc: PTPDFDoc = PTPDFDoc(filepath: input_file)
                    new_doc.insertPages(Int32(i), src_doc: in_doc, start_page: 1, end_page: in_doc.getPageCount(), flag: e_ptinsert_none)
                }
                new_doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_merge_pages.pdf").path, flags: e_ptremove_unused.rawValue)
                print("Done. Result saved in newsletter_merge_pages.pdf")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        // Sample 3 - Delete every second page
        do {
            try PTPDFNet.catchException {
                print("_______________________________________________")
                print("Sample 3 - Delete every second page...")
                print("Opening the input pdf...")
                let in_doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                in_doc.initSecurityHandler()
                
                var page_num = in_doc.getPageCount()
                while page_num >= 1 {
                    let itr: PTPageIterator = in_doc.getPageIterator(UInt32(page_num))
                    in_doc.pageRemove(itr)
                    page_num -= 2
                }
                
                in_doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_page_remove.pdf").path, flags: 0)
                print("Done. Result saved in newsletter_page_remove.pdf...")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        // Sample 4 - Inserts a page from one document at different
        // locations within another document
        do {
            try PTPDFNet.catchException {
                print("_______________________________________________")
                print("Sample 4 - Insert a page at different locations...")
                print("Opening the input pdf...")
                
                let in1_doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                in1_doc.initSecurityHandler()
                
                let in2_doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "fish", ofType: "pdf"))
                in2_doc.initSecurityHandler()
                
                let src_page: PTPageIterator = in2_doc.getPageIterator(1)
                let dst_page: PTPageIterator = in1_doc.getPageIterator(1)
                var page_num: Int = 1
                while dst_page.hasNext() {
                    if (page_num % 3) == 0 {
                        in1_doc.pageInsert(dst_page, page: src_page.current())
                    }
                    page_num += 1
                    dst_page.next()
                }
                
                in1_doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_page_insert.pdf").path, flags: 0)
                print("Done. Result saved in newsletter_page_insert.pdf...")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        // Sample 5 - Replicate pages within a single document
        do {
            try PTPDFNet.catchException {
                print("_______________________________________________")
                print("Sample 5 - Replicate pages within a single document...")
                print("Opening the input pdf...")
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                // Replicate the cover page three times (copy page #1 and place it before the
                // seventh page in the document page sequence)
                let cover: PTPage = doc.getPage(1)
                let p7: PTPageIterator = doc.getPageIterator(7)
                doc.pageInsert(p7, page: cover)
                doc.pageInsert(p7, page: cover)
                doc.pageInsert(p7, page: cover)
                
                // Replicate the cover page two more times by placing it before and after
                // existing pages.
                doc.pagePushFront(cover)
                doc.pagePushBack(cover)
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_page_clone.pdf").path, flags: 0)
                print("Done. Result saved in newsletter_page_clone.pdf...")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        // Sample 6 - Use ImportPages() in order to copy multiple pages at once
        // in order to preserve shared resources between pages (e.g. images, fonts,
        // colorspaces, etc.)
        do {
            try PTPDFNet.catchException {
                print("_______________________________________________")
                print("Sample 6 - Preserving shared resources using ImportPages...")
                print("Opening the input pdf...")
                let in_doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                in_doc.initSecurityHandler()
                
                let new_doc: PTPDFDoc = PTPDFDoc()
                
                let copy_pages: PTVectorPage = PTVectorPage()
                let itr: PTPageIterator = in_doc.getPageIterator(1)
                while itr.hasNext() {
                    copy_pages.add(itr.current())
                    itr.next()
                }
                
                let imported_pages: PTVectorPage = new_doc.importPages(copy_pages, import_bookmarks: false)
                for i in 0..<imported_pages.size() {
                    new_doc.pagePushFront(imported_pages.get(Int32(i)))
                    // Order pages in reverse order.
                    // Use PagePushBack() if you would like to preserve the same order.
                }
                
                new_doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_import_pages.pdf").path, flags: 0)
                print("Done. Result saved in newsletter_import_pages.pdf...")
                
                print("Note that the output file size is less than half the size of the file produced using individual page copy operations between two documents")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        return ret
    }
}