1

I want to convert the contents of NSMutableArray to NSData and then convert it to pdf. I am using following code to conver NSdata but it gives error .I have searched many article but not getting anything

  myArray=[[NSMutableArray alloc]init];


  [myArray addObject:@"Jamshed"];
  [myArray addObject:@"Imran"];
  [myArray addObject:@"Ali"];
  [myArray addObject:@"Hussain"];
  [myArray addObject:@"Faisal"];

 for (int i=0; i<[myArray count]; i++)
 {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[myArray objectAtIndex:i]];
NSLog(@"data %@",data);
//create code for pdf file for write b4 read and concatenate readed string with data to write in pdf file.  
 }




   - (NSData*) pdfDataWithSomeText;
   {
// For more on generating PDFs, see http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GeneratingPDF/GeneratingPDF.html
// The PDF content will be accumulated into this data object.
 NSMutableData *pdfData = [NSMutableData data];

// Use the system default font.
 UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];

// Use the default page size of 612*792.
 CGRect pageRect = CGRectMake(0, 0, 612, 792);

// Use the defaults for the document, and no metadata.
 UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);

// Create a page.
 UIGraphicsBeginPDFPageWithInfo(pageRect, nil);

// Store some placeholder text.
 NSString *topLine = @"PDF Sample from";
 NSString *bottomLine = @"http://stackoverflow.com/q/10122216/1318452";

// Draw that placeholder text, starting from the top left.
 CGPoint topLeft = CGPointZero;
 CGSize lineSize = [topLine sizeWithFont:font];
 [topLine drawAtPoint:topLeft withFont:font];
// Move down by the size of the first line before drawing the second.
 topLeft.y += lineSize.height;
 [bottomLine drawAtPoint:topLeft withFont:font];

// Close the PDF context.
 UIGraphicsEndPDFContext();  

// The pdfData object has now had a complete PDF file written to it.
 return pdfData;
 }
Punhoon Khan
  • 48
  • 1
  • 2
  • 6

4 Answers4

3

Writing strings to a PDF is not as simple as generating NSData from those strings. Look at the Drawing and Printing Guide for iOS - Generating PDF Content. Yes, it is a big document. Read it. Try the examples from it. Try adding your own strings to their example. Then, if you have something that almost works, come back here to ask about it.

Generating the PDF

So here is the code from the link above, made even simpler by drawing with NSString instead of Core Text. It draws the input array, but will probably need to some better arithmetic. Can you make it draw in a more structured way?

- (NSData*) pdfDataWithStrings:(NSArray*) strings;
{
    // For more on generating PDFs, see http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GeneratingPDF/GeneratingPDF.html
    strings = [strings arrayByAddingObject:@"https://stackoverflow.com/q/10122216/1318452"];
    // The PDF content will be accumulated into this data object.
    NSMutableData *pdfData = [NSMutableData data];

    // Use the system default font.
    UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];

    // Use the default page size of 612*792.
    CGRect pageRect = CGRectMake(0, 0, 612, 792);

    // Use the defaults for the document, and no metadata.
    UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);

    // Create a page.
    UIGraphicsBeginPDFPageWithInfo(pageRect, nil);

    // Add the strings within the space of the pageRect.
    // If you want to draw the strings in a column or row, in order, you will need to change this bit.
    for (NSString *line in strings)
    {
        // Hint: you will still need to know the lineSize.
        CGSize lineSize = [line sizeWithFont:font];
        CGFloat x = pageRect.origin.x + (arc4random_uniform(RAND_MAX)/(CGFloat) RAND_MAX*(pageRect.size.width-lineSize.width));
        CGFloat y = pageRect.origin.y + (arc4random_uniform(RAND_MAX)/(CGFloat) RAND_MAX*(pageRect.size.height-lineSize.height));
        CGPoint lineTopLeft = CGPointMake(x, y);

        // Having worked out coordinates, draw the line.
        [line drawAtPoint:lineTopLeft withFont:font];
    }

    // Close the PDF context.
    UIGraphicsEndPDFContext();  

    // The pdfData object has now had a complete PDF file written to it.
    return pdfData;
}

Saving to the Documents Directory

To save a document, you need to find the path where the user's documents are kept:

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];

You will be saving a file within that path. For your final app, let the user select their own name. For this example, the name will be build into the program.

NSString *pdfFilename = @"StackOverflow.pdf";

NSString has some excellent path manipulation methods, making it easy to construct the path you will be writing to.

NSString *pdfPath = [documentsPath stringByAppendingPathComponent:pdfFilename];

Then get the data you'll be writing to that path. Here I'll call the method declared above.

NSData *pdfData = [self pdfDataWithStrings:myArray];

Write those data to the path. For a better app, you may at some point want to call [pdfData writeToFile:options:error:] so you can display anything that went wrong.

[pdfData writeToFile:pdfPath atomically:NO];

How do you know if this worked? On the simulator, you can log the path you wrote to. Open this path in the Finder, and see if it contains the PDF you expect.

NSLog(@"Wrote PDF to %@", pdfPath);

On actual devices, you can enable iTunes File Sharing. See How to enable file sharing for my app?

Community
  • 1
  • 1
Cowirrie
  • 7,218
  • 1
  • 29
  • 42
  • thanks for sharing and one thing i will call this method pdfDataWithSomeText:NSData – Punhoon Khan Apr 13 '12 at 05:08
  • No, the `NSData` object you want is _returned_ by this method. You will need to pass an object into this method, but the input should be of type `NSString` or `NSArray`. – Cowirrie Apr 13 '12 at 05:15
  • You said you wanted NSData for a PDF. This method returns the NSData for a PDF. Where do you want your PDF? Do you want to save your PDF to the user's documents directory? Do you want to dislay the PDF? Do you want to print the PDF? Do you want to upload the PDF to a server? – Cowirrie Apr 13 '12 at 05:39
  • 1
    I want to save it in Documents folder of iPhone app – Punhoon Khan Apr 13 '12 at 05:44
  • Its ok but may write this code below above code and how will that method be called – Punhoon Khan Apr 13 '12 at 06:30
  • can you help out please how to call this – Punhoon Khan Apr 13 '12 at 06:52
  • I could continue, but I'm starting to agree with other commenters here. (1) Do you understand what a PDF is? (2) What application do you normally view them with? (3) Why do you need one here? – Cowirrie Apr 13 '12 at 07:00
  • I have run this code it creates file but it contains stackoverflowpdf file not the actual data – Punhoon Khan Apr 13 '12 at 07:05
  • i have tested code it works fine but it only displays the text of top and bottom – Punhoon Khan Apr 13 '12 at 07:14
  • I have made one final change: the method now accepts an array of strings. It draws those strings to the PDF, but you _must_ make any other changes it needs to work as you need it. – Cowirrie Apr 13 '12 at 07:33
  • ok thanks for this and one thing if i want other things like line formatting or anything is there any api or other to see that becuase i am getting line on random – Punhoon Khan Apr 13 '12 at 07:40
  • All you need is in `pdfDataWithStrings:`. You will need to fix it. There is no API to fix it for you. Look at `x` and `y`. Look at `lineSize` and `lineTopLeft`. What do they do? What happens if you change them? Read. Experiment. Learn. That is how you become a programmer. – Cowirrie Apr 13 '12 at 07:48
0

Before doing like

NSData *data = [NSKeyedArchiver archivedDataWithRootObject: myArray];

You convert array in to json string first

NSString *jsonString = [myArray JSONRepresentation];

You must Import json.h api first

Kundan
  • 3,084
  • 2
  • 28
  • 65
Ranga
  • 821
  • 4
  • 11
  • 20
0

You ca convert into json using

 NSData *jsonData        =   [NSJSONSerialization dataWithJSONObject:finalDict options:NSJSONWritingPrettyPrinted error:nil];
mChopsey
  • 548
  • 3
  • 10
-1
myArray=[[NSMutableArray alloc]init];


[myArray addObject:@"Jamshed"];
[myArray addObject:@"Imran"];
[myArray addObject:@"Ali"];
[myArray addObject:@"Hussain"];
[myArray addObject:@"Faisal"];

for (int i=0; i<[myArray count]; i++)
{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[myArray objectAtIndex:i]];
    NSLog(@"data %@",data);
    //create code for pdf file for write b4 read and concatenate readed string with data to write in pdf file.  
}
Ravi Kumar Karunanithi
  • 2,151
  • 2
  • 19
  • 41