Search code examples
swiftcore-foundationcfdatacfdictionary

Swift CGPDFContextBeginPage and CFData


I would like to create some PDF pages in Swift.

This is my code to create a PDF page

// Initialize context and other stuff
CGPDFContextBeginPage(pdfContext, aDictionary);
CGContextDrawPDFPage(pdfContext, pdfPageRef)
CGPDFContextEndPage(pdfContext)

I have a problem with the "aDictionary" variable. I would like to add the media box (which is CGRect type variable) value under the kCGPDFContextMediaBox key. The documentation tells me the following: The media box for the document or for a given page. This key is optional. If present, the value of this key must be a CFData object that contains a CGRect (stored by value, not by reference).

In objective-c it is fairly easy to create a CFData from CGRect, but in Swift I am not sure how to create it. Here's my objective-c code:

CGRect mediaBox = CGRectZero;
CFDataCreate(kCFAllocatorDefault, (const UInt8 *)&mediaBox, sizeof(mediaBox));

What should be the Swift variant?

Let's say somehow I've created a CFData object, the next "hard" step is to add this to a CFDictionary. Here's how I've tried:

let pageDictionary = CFDictionaryCreateMutable(nil, 0, nil, nil);
CFDictionarySetValue(pageDictionary, key: &kCGPDFContextMediaBox, value: data);

For these two line I receive the following error: CFString is not convertible to '@lvalue inout $T3'

Do you have any clues how can I fix these two errors?


Solution

  • CFData is “toll-free bridged” with NSData, and CFDictionary with NSDictionary. So the following should work:

    var mediaBox = CGRect(x: 0.0, y: 0.0, width: 612, height: 792)
    let boxData = NSData(bytes: &mediaBox, length: sizeofValue(mediaBox))
    let pageInfo = [ kCGPDFContextMediaBox as String : boxData ]
    CGPDFContextBeginPage(context, pageInfo)
    

    Update for Swift 3:

    var mediaBox = CGRect(x: 0.0, y: 0.0, width: 612, height: 792)
    let boxData = NSData(bytes: &mediaBox, length: MemoryLayout.size(ofValue: mediaBox))
    let pageInfo = [ kCGPDFContextMediaBox as String : boxData ]
    context.beginPDFPage(pageInfo as NSDictionary)