How to generate pdf using NSData or using data bytes objective c? - iphone

Hi I want to write pdf using NSData or using data bytes given by webservice ?
-(NSData *)saveData:(NSData*)fileData fileName:(NSString *)fileName fileType:(NSString *)fileType
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.%#",documentsDir,fileName,fileType];
NSData* downloadData = [NSData dataWithData:fileData];
[fileManager createFileAtPath:filePath contents:downloadData attributes:nil];
}
I am using this but it's not working it's give me error "It may be damaged or use a file format that Preview doesn’t recognize." on opening that pdf created by above code.

you can convert NSData to PDF with bellow code... I get the bellow Code From This link
NSString *string=[NSString stringWithFormat:#"%#.pdf",[yourArray objectAtIndex:pageIndex]];
[controller1 addAttachmentData:pdfData mimeType:#"application/pdf" fileName:string];
[self presentModalViewController:controller1 animated:YES];
[controller1 release];
//to convert pdf to NSData
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"test.pdf"];
NSData *myData = [NSData dataWithContentsOfFile:pdfPath];
//to convert NSData to pdf
NSData *data = //some nsdata
CFDataRef myPDFData = (CFDataRef)data;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
-(IBAction)saveasPDF:(id)sender{
NSString *string=[NSString stringWithFormat:#"%#.pdf",[yourArray objectAtIndex:pageIndex]];
[controller1 addAttachmentData:pdfData mimeType:#"application/pdf" fileName:string];
[self presentModalViewController:controller1 animated:YES];
[pdfData writeToFile:[self getDBPathPDf:string] atomically:YES];
}
-(NSString *) getDBPathPDf:(NSString *)PdfName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:PdfName];
}
Summary:
get NSData from pdf file path
NSData *pdfData = [NSData dataWithContentsOfFile:pathToFile1];
NSLog(#"pdfData= %d", pdfData != nil);
write NSData to pdf file
[pdfData writeToFile:pathToFile2 atomically:YES];

#ChallengerGuy (If you are still looking for the Swift 2 approach for the CGPDFDocument)
//to convert data of type NSData
guard let cfData = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(data.bytes), data.length) else { return nil}
let cgDataProvider = CGDataProviderCreateWithCFData(cfData)
guard let cgPDFDocument = CGPDFDocumentCreateWithProvider(cgDataProvider) else { return nil }
Hope the above helps

Related

When we open pdf in iPhone then how to save this pdf in iphone

I am very new to iOS. I create PDF and load this PDF on UIWebView
now this time I want to save or download this PDF in iPhone when we tapped download button then all exits PDF supporter show like as open ibook ,open in chrome. This type of option show but when we tap any one then my application closed.
-(void)show_Button
{
NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [docDirectories objectAtIndex:0];
NSString *filePAth = [docDirectory stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
docContr.delegate=self;
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
so how to save or download this pdf in Iphone please solve this problem....
I believe you can simple use the belo two line:
NSData *myFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"your_url"]];
[myFile writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
I hope this it will help you,
Saving the pdf into app
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"pdfname.pdf"];
NSError *writeError = nil;
[imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
if (writeError) {
NSLog(#"Error writing file: %#", writeError); }
Getting the pdf from the NSDocument Directory
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:&error];
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"pdf"])
{
NSString *pdfPath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:pdfPath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[arrayOfImages addObject:image];
}
}
}

loading Hierarchy in NSMutableData

Is there Hierarchy system in NSMutableData? If so, how do i load information in a hierarchy manner?
Example
//Create path to saving location
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableData *gameData;
NSKeyedUnarchiver *decoder;
NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:#"tierSave.dat"];
gameData = [NSData dataWithContentsOfFile:documentPath];
//end
//start loading
for(NSArray* firstData in gameData){
decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:gameData];
int level1 = [decoder decodeIntegerForKey:level1];
}
//end
However in for(NSArray* firstData in gameData), the compiler tells me that gameData will not respond to count because it is a NSMutableData instead of NSMutableArray etc, How do i exactly re-implement the code above?
Saving:
Create a NSArray with your multiple NSData
Use NSKeyedArchiver to make a NSData from your NSArray
Loading:
Load a NSData from file
Use NSKeyedUnarchiver to extract the NSArray
Loop your NSArray
In code:
NSData *data0 = [NSData data]; // Data 1
NSData *data1 = [NSData data]; // Data 2
/////////// SAVE
// now make a array
NSArray *array = [NSArray arrayWithObjects:data0, data1, nil];
// now archive the data
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:array];
// archivedData contains now a binary plist with your archived array including your NSData objects
[archivedData writeToFile:path atomically:YES];
/////// LOAD
NSData *archivedDataFromFile = [NSData dataWithContentsOfFile:path];
NSArray *newArray = [NSKeyedUnarchiver unarchiveObjectWithData:archivedDataFromFile];
NSData *dataLoaded0 = [newArray objectAtIndex:0];

Check if file exists in resourses/project navigator

I need to check if an image exists in the project navigator. If it doesn't it needs to download it from the internet. The goal is to be able to use images like [UIImage imageNamed:#"23451.jpg"];
So I need to check if the image exists, if not download it. I tried to do this as followed:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Set image
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"12345.jpg"];
//Check if the image exists at a given path
BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
//If the image doesn't exists download it.
if (!imageExists)
{
NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.mywebsite.com/12345.jpg"]]]);
[data writeToFile:imagePath atomically:YES];
}
If everything goes the right way the image is saved at the above path. But I still am not able to use this image with
[UIImage imageNamed:#"12345.jpg"];
I have got the feeling that i'm saving the images in a different directory than I should be saving them to.
Do you have any idea on how I should do this?
imageNamed will only work form image in the app bundle, not those stored in the Document directory. And you can't add the image to the app bundle, it readonly.
if (!imageExists)
{
NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.mywebsite.com/12345.jpg"]]]);
[data writeToFile:imagePath atomically:YES];
}
There is no need to do this, you are now JPG a JPG:
if (!imageExists)
{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.mywebsite.com/12345.jpg"]];
[data writeToFile:imagePath atomically:YES];
}
NSData* data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:imagePath], 0.8)];
[data writeToFile:imagePath atomically:YES];
I did something similar .. here are some excerpts of the code .. not the complete code ...
- (void)loadAndStoreImage{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *theurlPortrait = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:#"portraitImageUrl"] ];
NSLog(#"Image url %# ",theurlPortrait);
imageDataPortrait = [NSData dataWithContentsOfURL:theurlPortrait];
[theurlPortrait release];
imagePortrait= [[UIImage alloc]initWithData:imageDataPortrait];
oldPathPortrait = [documentsDirectory stringByAppendingPathComponent:#"pt_wallpaper_1.png"];
NSURL *theurlLandscape = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:#"landscapeImageUrl"]];
imageDataLandscape = [NSData dataWithContentsOfURL:theurlLandscape];
[theurlLandscape release];
imageLandscape= [[UIImage alloc]initWithData:imageDataLandscape];
oldPathLandscape = [documentsDirectory stringByAppendingPathComponent:#"ls_wallpaper_1.png"];
[self replaceImages];
}
-(void)replaceImages{
//check if images were fully downloaded or corrupted.
if (isUserSignedIn) {
if (imageDataPortrait && imageDataLandscape) {
[UIImagePNGRepresentation(imagePortrait) writeToFile:oldPathPortrait atomically:YES];
[UIImagePNGRepresentation(imageLandscape) writeToFile:oldPathLandscape atomically:YES];
NSLog(#"IMAGES REPLACED");
NSDate *currentDate=[NSDate date];
[[ NSUserDefaults standardUserDefaults] setObject:currentDate forKey:#"previousDate"];
}
}
}

How save images in home directory?

I am making an application in which i have use Json parsing. With the help of json parsing i get photo url which is saved in string. To show images in my cell i use this code
NSString *strURL=[NSString stringWithFormat:#"%#", [list_photo objectAtIndex:indexPath.row]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: strURL]];
CGRect myImage =CGRectMake(13,5,50,50);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImage];
[imageView setImage:[UIImage imageWithData: imageData]];
[cell addSubview:imageView];
Now prblem is that when i go back or forword then i have wait for few second to come back on same view. Now i want that i when application is used first tme then i wait for that screen otherwise get images from home directory. How i save these image in my home directory? How access from home directory?
You can save an image in the default documents directory as follows using the imageData;
// Accessing the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"myImage.png"];
//Writing the image file
[imageData writeToFile:savedImagePath atomically:NO];
You can use this to write a file to your Documents Folder
+(BOOL) downloadFileFromURL:(NSString *) url withLocalName:(NSString*) localName
{
//Get the local file and it's size.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:localName];
NSError *error;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:finalPath error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
int localFileSize = [[fileAttributes objectForKey:NSFileSize] intValue];
//Prepare a request for the desired resource.
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"HEAD"];
//Send the request for just the HTTP header.
NSURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
//Check the response code
int status = 404;
if ([response respondsToSelector:#selector(statusCode)])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
status = [httpResponse statusCode];
}
if (status != 200)
{
//file not found
return NO;
}
else
{
//file found
}
//Get the expected file size of the downloaded file
int remoteFileSize = [response expectedContentLength];
//If the file isn't already downloaded, download it.
if (localFileSize != remoteFileSize || (localFileSize == 0))
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
return YES;
}
//here we may wish to check the dates or the file contents to ensure they are the same file.
//The file is already downloaded
return YES;
}
and this to read:
+(UIImage*) fileAtLocation:(NSString*) docLocation
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:docLocation];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
NSData *databuffer = [[NSFileManager defaultManager] contentsAtPath:finalPath];
UIImage *image = [UIImage imageWithData:databuffer];
return image;
}

store file in NSDocumentDirectory of iPhone

I am using a UIImagePickerController in my application.
After selecting an image by user,
image should be saved at application Documents Directory,
my Code is Give Below.
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[picker dismissModalViewControllerAnimated:YES];
NSData *imgData = UIImagePNGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"]);
UIImage *img = [[UIImage alloc] initWithData:imgData];
stuImgView.image = img;
[img release];
//write image
NSString *imageFilename = [NSString stringWithFormat:#"%i.jpg", currentStudent.stuNo];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0], imageFilename];
UIImage *stuImg;
BOOL success;
NSFileManager *fm=[NSFileManager defaultManager];
// how to store file at documents dir????
}
i dont know how to use file manager to store a file?
Help me Out.
Thanks in advance.
You can use writeToFile:atomically::
[imgData writeToFile:path atomically:NO];