8

Iam trying to saving an UIImage in PDF file. How can i do this? How i would save and image into pdf file and then export that pdf file? Please suggest the solution for the issue i faced.

Thank You.

mactalent
  • 971
  • 2
  • 13
  • 24
  • Why? While it's possible, PDF is optimized for storing documents and vector graphics, and UIImage is a bitmap... – kennytm Mar 15 '10 at 14:16

4 Answers4

15

Hello there I've found that this works, hope it helps!

-(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();

        // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
        [aView.layer renderInContext:UIGraphicsGetCurrentContext()];

        // 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);
    }
Streeter
  • 556
  • 4
  • 22
user440071
  • 151
  • 1
  • 3
3

My understanding is that you'd create a CGPDFContext, draw your UIImage into it, and save it to a file. Haven't done that myself, though.

Thomas Müller
  • 15,565
  • 6
  • 41
  • 47
0

I got a blank pdf as well. Got it working now though. Try changing:

//[aView drawRect:aView.bounds]; // <- This

[aView.layer renderInContext:UIGraphicsGetCurrentContext()]; // <- To This
Nigel Greens Apps
  • 1,266
  • 1
  • 11
  • 6
-1

You can start a pdf graphics context, and then draw an image into it, using:

[UIImage drawInRect: someRect];

You can either see the docs, they give a good explanation of generating a pdf. There is a good tutorial on pdf generation here.

Bani Uppal
  • 866
  • 9
  • 17