开发者

How do I write a PDF file from NSData source

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?


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...)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜