Search code examples
swiftpdfkit

Working with PDFKit: How to make page breaks?


Looking for some direction

I'm working with PDFKit. Everything is going fine but having trouble finding the methods (documentation / WWDC / elsewhere ) on how to stop text from drawing at a certain y position and start the next page. Any saved references or a snippet of code would be a great help.


Solution

  • I dont know, wether this is the best way to implement your use case, but it worked for me. When adding a new line into the PDF_Context, I recalculate a variable the keeps tracking of the current content height of my PDF_Page. When it exceeds a certain value, I create a NEW page, set the content height to zero and go on filling, ...

    And you might wanna find some good answers, practices HERE -> RayWenderlich.

    // my initial value
    private var myCurrentPageContentHeight: CGFloat = 20
            
    // in your PDF fill procedures add something like
    myCurrentPageContentHeight += 40
                
    // I also have a struct the encapsulates 
    // PageSize with padding, ...
                
    enum PDF_PageSize {
         case din_A4_Portrait
         case din_A4_Landscape
                    
          // -------------------------------
          // getPDF_TotalRect
          // -------------------------------
          func getPDF_TotalRect() -> CGRect {
               switch self {
               case .din_A4_Portrait : return CGRect(x: 0, y: 0, width: 595, height: 842)
               case .din_A4_Landscape : return CGRect(x: 0, y: 0, width: 842, height: 595)
               }
     }
     // ....
     }