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;
}
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?
You ca convert into json using
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalDict options:NSJSONWritingPrettyPrinted error:nil];
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
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.
}
Related
I want am working on a project where I need to save user typed text as .PNG file through objective-c. I mean when user typed some text I give option to the user to choose font type then save it. After that the file will be saved as .PNG file without background.
How can I achieve this. Please share your views.
Thanks in advance
use this method get image from text:
-(UIImage *)imageFromText:(NSString *)text
{
// set the font type and size
//UIFont *font = [UIFont systemFontOfSize:txtView.font];
CGSize size = [text sizeWithFont:txtView.font]; // label or textview
// check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
if (UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
else
// iOS is < 4.0
UIGraphicsBeginImageContext(size);
[text drawInRect:CGRectMake(0,0,size.width,size.height) withFont:txtView.font];
UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return testImg;
}
Now u have image save like this
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir]; // any name u want for image
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)]; your image here
[data1 writeToFile:pngFilePath atomically:YES];
Having weird problem with my NSDocumenDirectory saving.
Here is a sneak preview:
First I pick images ( in my imagePickerViewController):
in my PreviewController:
So at first try, it was okay.
Then I revisit the imagePickerViewController to add another image:
in my PreviewController:
This is where the problem occurs. At the image above, it recopies the last image from the old preview (like a duplicate). I dunno what Im doing wrong in my codes. But Im saving it when a file exist. Kindly see:
for (int i = 0; i < info.count; i++) {
NSLog(#"%#", [info objectAtIndex:i]);
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"firstSlotImages%d.png", i]];
if ([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {
NSLog(#"file doesnt exist");
} else {
ALAssetRepresentation *rep = [[info objectAtIndex: i] defaultRepresentation];
UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage]];
//----resize the images
image = [self imageByScalingAndCroppingForSize:image toSize:CGSizeMake(256,256*image.size.height/image.size.width)];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
NSLog(#"saving at:%#",savedImagePath);
}
}
What I need is to just reAdd AGAIN the same image with the new one.
Same as, like the last preview.
The four images are passed in the sequence that they show in the preview, so in the first example the orange cat is third, and in the second example, the orange cat is fourth. The new image isn't saving because it is third, and you already have a file named "firstSlotImages2.png". If you re-save each image without checking if the file exists, you should get the result you are looking for.
There's a key in the media info: UIImagePickerControllerMediaURL which returns an NSURL, convert it to a string and get the the lastPathComponent. Use this as the file name to save to the directory you are saving it to. You can then save the reference to these images by saving this same file name either in an NSMutableArray, or an NSMutableDictionary
I want to creat the pdf from the view i am using following code i have got this from the web but how to call this method and where to give the file name for creating the pdf which is saved in documents folder.
When i call this method it gives exception unrecognized selector sent.
[self createPDFfromUIView:someView saveToDcumentsWithFileName:#"my_pdf.pdf"];
-(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);
}
This is working code....Dont forget to add QuartzCore.h
#include <QuartzCore/QuartzCore.h>
- (void)viewDidLoad
{
[super viewDidLoad];
[self createPDFfromUIView:self.view saveToDocumentsWithFileName:#"abc.pdf"];
}
-(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);
}
If you have that method implemented in a class, and were calling it from the same class. You would do it like so:
[self createPDFfromUIView:someView saveToDcumentsWithFileName:#"my_pdf.pdf"];
This will save your UIView as a PDF in your Documents directory with a filename of, my_pdf.pdf.
Hope this helps.
I have iphone app which created Pie Chart i want that chart should be save in pdf file in iphone.
Below is the code for PieChart but how can i save it in pdf i have read that we can save text in pdf but how to save this
-(void)createGraph{
PieClass *myPieClass=[[PieClass alloc]initWithFrame:CGRectMake(400,40, 320, 230)];
myPieClass.itemArray=[[NSArray alloc]initWithObjects:textFieldOne.text,textFieldTwo.text,textFieldThree.text, nil];
myPieClass.myColorArray=[[NSArray alloc]initWithObjects:[UIColor purpleColor],[UIColor redColor],[UIColor orangeColor], nil];
myPieClass.radius=100;
[self.view addSubview:myPieClass];
[self creatPDFFromView:#"mydata.pdf"];
}
-(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);
}
Which view you want to create as a pdf in that view do the following changes
NSString *fileName=#"PdfFromView.pdf";
[self createPDFfromUIView:self.view saveToDocumentsWithFileName:fileName];
-(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);
}
After this code has been executed go to documents folder you will find the pdf document containing the same contents of that view you have passed in
Blockquote
[self createPDFfromUIView:self.view saveToDocumentsWithFileName:fileName]
Blockquote
this method call.
this code working fine Thanks to Antonio
Took from here:
How to Convert UIView to PDF within iOS?
(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);
}
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.
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);
}
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.
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
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.