Some test text!

Search
Hamburger Icon

PDF patterns and shadings in 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 create various patterns and shadings in PDF files. 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 CreateTilingPattern(doc: PTPDFDoc) -> PTObj {
    let writer: PTElementWriter = PTElementWriter()
    let eb: PTElementBuilder = PTElementBuilder()
    
    // Create a new pattern content stream - a heart. ------------
    writer.writerBegin(with: doc.getSDFDoc(), compress: true)
    eb.pathBegin()
    eb.move(to: 0, y: 0)
    eb.curve(to: 500, cy1: 500, cx2: 125, cy2: 625, x2: 0, y2: 500)
    eb.curve(to: -125, cy1: 625, cx2: -500, cy2: 500, x2: 0, y2: 0)
    let heart: PTElement = eb.pathEnd()
    heart.setPathFill(true)
    
    // Set heart color to red.
    heart.getGState().setFill(PTColorSpace.createDeviceRGB())
    heart.getGState().setFillColor(with: PTColorPt(x: 1, y: 0, z: 0, w: 0))
    writer.write(heart)
    
    let pattern_dict: PTObj = writer.end()
    
    // Initialize pattern dictionary. For details on what each parameter represents please
    // refer to Table 4.22 (Section '4.6.2 Tiling Patterns') in PDF Reference Manual.
    pattern_dict.putName("Type", name: "Pattern")
    pattern_dict.putNumber("PatternType", value: 1)
    
    // TilingType - Constant spacing.
    pattern_dict.putNumber("TilingType", value: 1)
    
    // This is a Type1 pattern - A colored tiling pattern.
    pattern_dict.putNumber("PaintType", value: 1)
    
    // Set bounding box
    pattern_dict.putRect("BBox", x1: -253, y1: 0, x2: 253, y2: 545)
    
    // Create and set the matrix
    let pattern_mtx: PTMatrix2D = PTMatrix2D(a: 0.04, b: 0, c: 0, d: 0.04, h: 0, v: 0)
    pattern_dict.putMatrix("Matrix", value: pattern_mtx)
    
    // Set the desired horizontal and vertical spacing between pattern cells,
    // measured in the pattern coordinate system.
    pattern_dict.putNumber("XStep", value: 1000)
    pattern_dict.putNumber("YStep", value: 1000)

    return pattern_dict  // finished creating the Pattern resource
}

func CreateImageTilingPattern(doc: PTPDFDoc) -> PTObj {
    let writer: PTElementWriter = PTElementWriter()
    let eb: PTElementBuilder = PTElementBuilder()
    
    // Create a new pattern content stream - a single bitmap object ----------
    writer.writerBegin(with: doc.getSDFDoc(), compress: true)
    let image: PTImage = PTImage.create(doc.getSDFDoc(), filename: Bundle.main.path(forResource: "dice", ofType: "jpg"))
    let img_element: PTElement = eb.createImage(withCornerAndScale: image, x: 0, y: 0, hscale: Double(image.getWidth()), vscale: Double(image.getHeight()))
    writer.writePlacedElement(img_element)
    let pattern_dict: PTObj = writer.end()
    
    // Initialize pattern dictionary. For details on what each parameter represents please
    // refer to Table 4.22 (Section '4.6.2 Tiling Patterns') in PDF Reference Manual.
    pattern_dict.putName("Type", name: "Pattern")
    pattern_dict.putNumber("PatternType", value: 1)
    
    // TilingType - Constant spacing.
    pattern_dict.putNumber("TilingType", value: 1)
    
    // This is a Type1 pattern - A colored tiling pattern.
    pattern_dict.putNumber("PaintType", value: 1)
    
    // Set bounding box
    pattern_dict.putRect("BBox", x1: -253, y1: 0, x2: 253, y2: 545)
    
    // Create and set the matrix
    let pattern_mtx = PTMatrix2D(a: 0.3, b: 0, c: 0, d: 0.3, h: 0, v: 0)
    pattern_dict.putMatrix("Matrix", value: pattern_mtx)

    // Set the desired horizontal and vertical spacing between pattern cells,
    // measured in the pattern coordinate system.
    pattern_dict.putNumber("XStep", value: 300)
    pattern_dict.putNumber("YStep", value: 300)
    return pattern_dict // finished creating the Pattern resource
}

func CreateAxialShading(doc: PTPDFDoc) -> PTObj {
    // Create a new Shading object ------------
    let pattern_dict: PTObj = doc.createIndirectDict()

    // Initialize pattern dictionary. For details on what each parameter represents
    // please refer to Tables 4.30 and 4.26 in PDF Reference Manual
    pattern_dict.putName("Type", name: "Pattern")
    pattern_dict.putNumber("PatternType", value: 2)
    
    // 2 stands for shading
    let shadingDict: PTObj = pattern_dict.putDict("Shading")
    shadingDict.putNumber("ShadingType", value: 2)
    shadingDict.putName("ColorSpace", name: "DeviceCMYK")
    
    // pass the coordinates of the axial shading to the output
    let shadingCoords: PTObj = shadingDict.putArray("Coords")
    shadingCoords.pushBackNumber(0)
    shadingCoords.pushBackNumber(0)
    shadingCoords.pushBackNumber(612)
    shadingCoords.pushBackNumber(794)
    
    // pass the function to the axial shading
    let function: PTObj = shadingDict.putDict("Function")
    let C0: PTObj = function.putArray("C0")
    C0.pushBackNumber(1)
    C0.pushBackNumber(0)
    C0.pushBackNumber(0)
    C0.pushBackNumber(0)
    
    let C1: PTObj = function.putArray("C1")
    C1.pushBackNumber(0)
    C1.pushBackNumber(1)
    C1.pushBackNumber(0)
    C1.pushBackNumber(0)
    
    let domain: PTObj = function.putArray("Domain")
    domain.pushBackNumber(0)
    domain.pushBackNumber(1)
    function.putNumber("FunctionType", value: 2)
    function.putNumber("N", value: 1)
    
    return pattern_dict
}

func runPatternTest() -> Int {
    return autoreleasepool {
        var ret = 0
        
        
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc()
                let writer: PTElementWriter = PTElementWriter()
                let eb: PTElementBuilder = PTElementBuilder()
                
                // The following sample illustrates how to create and use tiling patterns
                var page: PTPage = doc.pageCreate(PTPDFRect(x1: 0, y1: 0, x2: 612, y2: 792))
                writer.begin(page, placement: e_ptoverlay, page_coord_sys: true, compress:true)
                
                var element: PTElement = eb.createTextBegin(with: PTFont.create(doc.getSDFDoc(), type: e_pttimes_bold, embed: false), font_sz: 1)
                writer.write(element)   // Begin the text block

                element = eb.createTextRun("G")
                element.setTextMatrix(720, b: 0, c: 0, d: 720, h: 20, v: 240)
                var gs: PTGState = element.getGState()
                gs.setTextRenderMode(e_ptfill_stroke_text)
                gs.setLineWidth(4)
                
                // Set the fill color space to the Pattern color space.
                gs.setFill(PTColorSpace.createPattern())
                gs.setFillColor(withPattern: PTPatternColor(pattern: CreateTilingPattern(doc: doc)))
                writer.write(element)
                writer.write(eb.createTextEnd()) // Finish the text block

                writer.end()    // Save the page
                doc.pagePushBack(page)
                //-----------------------------------------------
                
                /// The following sample illustrates how to create and use image tiling pattern
                page = doc.pageCreate(PTPDFRect(x1: 0, y1: 0, x2: 612, y2: 792))
                writer.begin(page, placement: e_ptoverlay, page_coord_sys: true, compress: true)
                
                eb.reset(PTGState())
                element = eb.createRect(0, y: 0, width: 612, height: 794)
                
                // Set the fill color space to the Pattern color space.
                gs = element.getGState()
                gs.setFill(PTColorSpace.createPattern())
                gs.setFillColor(withPattern: PTPatternColor(pattern: CreateImageTilingPattern(doc: doc)))
                element.setPathFill(true)
                writer.write(element)
                writer.end()    // Save the page
                doc.pagePushBack(page)
                //-----------------------------------------------

                /// The following sample illustrates how to create and use PDF shadings
                page = doc.pageCreate(PTPDFRect(x1: 0, y1: 0, x2: 612, y2: 792))
                writer.begin(page, placement: e_ptoverlay, page_coord_sys: true, compress: true)
                
                eb.reset(PTGState())
                element = eb.createRect(0, y: 0, width: 612, height: 794)
                
                // Set the fill color space to the Pattern color space.
                gs = element.getGState()
                gs.setFill(PTColorSpace.createPattern())
                gs.setFillColor(withPattern: PTPatternColor(pattern: CreateAxialShading(doc: doc)))
                element.setPathFill(true)

                writer.write(element)
                
                writer.end()    // Save the page
                doc.pagePushBack(page)
                //-----------------------------------------------
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("patterns.pdf").path, flags: e_ptremove_unused.rawValue)
                print("Done. Result saved in patterns.pdf...")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        return ret
    }
}