Question

I have a method that returns NSData from a CGPathRef like so ...

+ (NSData *) createPDFDataWithCGPath: (CGPathRef) path mediaBox: (CGRect) mediaBox
{
  CFMutableDataRef data = NULL;
  if (path) {
    CFAllocatorRef allocator = NULL;
    data = CFDataCreateMutable(allocator, 0);
    CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData(data);
    CGContextRef context = CGPDFContextCreate(consumer, &mediaBox, NULL);
    CFTypeRef keys[1] = { kCGPDFContextMediaBox };
    CFTypeRef values[1] = { CFDataCreate(allocator, (const UInt8 *)&mediaBox, sizeof(CGRect)) };
    CFDictionaryRef pageInfo = CFDictionaryCreate(allocator, keys, values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CGPDFContextBeginPage(context, pageInfo);
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -mediaBox.size.height);
    CGContextAddPath(context, path);
    CGContextSetRGBFillColor(context, 0, 0, 0, 1);
    CGContextFillPath(context);
    CGPDFContextEndPage(context);

    CFRelease(pageInfo);
    CFRelease(values[0]);
    CGPDFContextClose(context);
    CGContextRelease(context);
    CGDataConsumerRelease(consumer);
  }
  return (NSData *)data;
}

When I attempt to use this and write a PDF file from the data I get my file at the correct size but the paths are not drawn into the PDF ... it's an empty document basically.

Is it enough to just write the file like so ...

[maskData writeToFile: DOCUMENTS_PATH_WITH_STRING(@"maskData.pdf") atomically: YES];

or are their more hoops to jump though to write it as a PDF?

Was it helpful?

Solution 2

This was a bit of a red herring. The paths were being drawn but had no strokes or fills. The code in my question above is sound and works as expected.

OTHER TIPS

You're right. If you have data in an NSData object then you can just write it on the disk. But you should add the correct extension (in your case .pdf). It works for everything (videos, pictures, etc...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top