mysterioustrousers / MTPDF

Objective-C PDF objects. Doing my part to help us stay out of the headache that is Core Foundation.
MIT License
205 stars 28 forks source link

Creating PDF using UIImage #3

Open oskargargas opened 11 years ago

oskargargas commented 11 years ago

If you'd be interested in expanding MTPDF to create PDFs using UIImages I'd like to share this code as a starting point:

+ (MTPDF *)PDFWithImageArray: (NSArray /* <UIImage> */*)imageArray {
    NSMutableData *pdfData = [[NSMutableData alloc] init];
    CGDataConsumerRef pdfConsumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef) pdfData);

    CGContextRef pdfContext = CGPDFContextCreate(pdfConsumer, NULL, NULL);

    for (NSUInteger i = 0; i < imageArray.count; i++) {
        UIImage *image = imageArray[i];
        CGFloat pageWidth = image.size.width;
        CGFloat pageHeight = image.size.height;

        CGRect pageRect = CGRectMake(0, 0, pageWidth, pageHeight);
        CGContextBeginPage(pdfContext,&pageRect);
        CGContextDrawImage(pdfContext, pageRect, image.CGImage);
        CGContextEndPage(pdfContext);
    }

    CGContextRelease(pdfContext);
    CGDataConsumerRelease(pdfConsumer);

    return [MTPDF PDFWithData:pdfData];
}
atomkirk commented 11 years ago

Thanks!