Swift PDF create Rectangle?

I would like to create an rectangle on an PDF File, but i dont how to do that. Its simple to create some text or images, but i would like to add some shapes like rectangles and circles.

Is the UIGraphicsBeginPDFPageWithInfo the same as the CGContext?

  • Parse Sort Query Via Pointer
  • Make calls from iPhone app
  • Navigation bar appear over the views with new iOS7 SDK
  • How do I get the error message in Swift 2.0?
  • Using Swift to disable sleep/screen saver for OSX
  • tableView.reloadData() Table not updating
  • At the moment i am using this:

    UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
    
    // add some text
    let mainTitle = "..."
    mainTitle.drawInRect(CGRectMake(30, 110, 552, 40), withAttributes: textAttributesBoldLargeHeader)
    

    But how to add a custom rectangle?

    2 Solutions Collect From Internet About “Swift PDF create Rectangle?”

    Just get the PDF drawing context with UIGraphicsGetCurrentContext()
    and draw anything to it. Simple example:

    UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
    
    let context = UIGraphicsGetCurrentContext()
    
    CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)
    let rect = CGRect(x: 10, y: 10, width: 100, height: 200)
    CGContextFillRect(context, rect)
    
    UIGraphicsEndPDFContext()
    

    You can also extend UIView to render the current context and save the data as pdf file:

    extension UIView {
        var pdfData: NSData {
            let result = NSMutableData()
            UIGraphicsBeginPDFContextToData(result, frame, nil)
            guard let context = UIGraphicsGetCurrentContext() else { return result }
            UIGraphicsBeginPDFPage()
            layer.renderInContext(context)
            UIGraphicsEndPDFContext()
            return result
        }
    }
    

    Testing:

    class ViewController: UIViewController {
        let rectangle = UIBezierPath(rect: CGRectMake(30, 110, 350, 40))
        let shapeLayer = CAShapeLayer()
        override func viewDidLoad() {
            super.viewDidLoad()
            shapeLayer.path = rectangle.CGPath
            shapeLayer.strokeColor = UIColor.blueColor().CGColor
            shapeLayer.fillColor = UIColor.redColor().CGColor
            view.layer.addSublayer(shapeLayer)
            view.pdfData.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent("view.pdf"), atomically: true)
        }
    }