How do I create transformed image in PDF from a UIView?

151 Views Asked by At

I'm using below code to create PDF from a UIView which already has subviews. I'm getting all subviews and redrawing in pdf context. But I'm not able to transform UIImageView. Below is my code

NSMutableData *pdfData = [NSMutableData data];
CGRect pageFrame = CGRectMake(0, 0, aView.frame.size.width, aView.frame.size.height);
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);
if([view isKindOfClass:[UIImageView class]]) {
    UIImageView *imgv = (UIImageView *)view;
    [imgv.image  drawInRect:CGRectMake(view.frame.origin.x + imgv.frame.origin.x, view.frame.origin.y + imgv.frame.origin.y, imgv.frame.size.width, imgv.frame.size.height)];
}
UIGraphicsEndPDFContext();

Even though image is rotated in my UIView but pdf showing no rotation. How do I transform it to 90 degree in pdf context?

2

There are 2 best solutions below

1
On

Note that the following method creates just a bitmap of the view; it does not create actual typography.

-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
    // Creates a mutable data object for updating with binary data, like a byte array
    NSMutableData *pdfData = [NSMutableData data];

    // Points the pdf converter to the mutable data object and to the UIView to be converted
    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
    UIGraphicsBeginPDFPage();
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();


    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData

    [aView.layer renderInContext:pdfContext];

    // remove PDF rendering context
    UIGraphicsEndPDFContext();

    // Retrieves the document directories from the iOS device
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

    // instructs the mutable data object to write its context to a file on disk
    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

Also make sure you import: QuartzCore/QuartzCore.

3
On

If you just need to draw some element with rotation, try to use matrix transformation functions for current context (it will be PDF context).

CGContextRotateCTM(currentContext, M_PI / 2);