How to Save as a PDF file from Byte stream in iOS - ios

When i used Sharepoint(getItem) Web Service for getting PDF file i got the response as Byte Stream,
I am trying to convert these Byte Stream as PDF file using below code,
NSMutableData *saveData = [NSMutableData data];
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:byteStreamStr options:0];
[saveData appendBytes:[decodedData bytes] length:decodedData.length];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *writeableDBPath = [documentDirectory stringByAppendingPathComponent:#"test.pdf"];
[[NSFileManager defaultManager] createFileAtPath:writeableDBPath contents:saveData attributes:nil];
The PDF file saved as same size of original one.But i can't open that PDF file.

Related

Store an SVG image in Documents directory iOS

I am fairly new to iOS development, and am unable to store an SVG image in the documents directory of my app. I have access to the raw data and would like to store this in SVG format
The raw data is in NSData format.
NSData *rawData = [[NSData alloc] initWithBytes:ptr length:size];
rawData has the dowloaded file, please help me save this as an SVG. Any help appreciated, also I have been doing this for less than a week, sorry for any mistakes.
yeah, do this:
- (NSString *)writeDataToDocuments:(NSData *)data withFilename:(NSString *)filename {
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [[NSString alloc] initWithString: [docsPath stringByAppendingPathComponent:filename]];
[data writeToFile:filePath atomically:YES];
return filePath;
}
the file path returned is where the SVG is now stored
so in your case it's
NSData *rawData = [[NSData alloc] initWithBytes:ptr length:size];
NSString *fileLocationString = [self writeDataToDocuments:rawData withFilename:#"example.svg"];
and now it's saved and you have the file path

how to write json file in ios

Here i am reading and writing a json file.
Reading is done correctly but while i am writing a file it doesn't write data in json file.
Here is my code.
//reading Json file....
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"bookmark" ofType:#"json"];
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
NSArray *bookmarkJson=[NSJSONSerialization JSONObjectWithData:content options:0 error:nil];
//this contains array's of dictionary....
NSDictionary *newBookmark=#{#"index":#"1.1.1.1",#"text":#"Header",#"htmlpage":#"page_name"};
//take new array to add data with previous one
NSMutableArray *temp=[[NSMutableArray alloc]initWithArray:bookmarkJson];
// add object to new array...
[temp insertObject:newBookmark atIndex:0];
//now serialize temp data....
NSData *serialzedData=[NSJSONSerialization dataWithJSONObject:temp options:0 error:nil];
NSString *saveBookmark = [[NSString alloc] initWithBytes:[serialzedData bytes] length:[serialzedData length] encoding:NSUTF8StringEncoding];
//now i write json file.....
[saveBookmark writeToFile:#"bookmark.json" atomically:YES encoding:NSUTF8StringEncoding error:nil];
In "saveBookmark" (NSString)object i got correct file format but in bookmark.json file i didn't got any new values.
Please help me with this......
EDIT: As correctly pointed out by #IulianOnofrei, use the document directory to read/write files and not the resources directory.
Use these methods to read and write data, and your problem should be solved:
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// The main act...
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// The main act...
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
Code courtesy from another SO answer found here: Writing and reading text files on the iPhone
And of course, the first time you try to read this file from the documents directory you won't get anything, so maybe the first step would be to copy the file there if it does not exist.
Hope this helps.

How to view the downloaded files in Device ipad/iphone

Hi in my application i have option of downloading a pdf file i have searched for that i got the code i have used its working fine in my mac i can see the downloaded pdf file. But the problem is if i download the same pdf in device where i can find the downloaded pdf file in device.
This is my code which i have used to download the pdf file.
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://jesusredeems.com/mag/pdf/JRE-2014-03.pdf"]]; //Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"11011.pdf"]; [pdfData writeToFile:filePath atomically:YES]; NSLog(#"%#",filePath);
If i print the filepath I'm getting like this.
/var/mobile/Applications/353C27AD-1E64-41CA-A429-16C2A20C8606/Documents/11011.pdf
In my mac i can see the downloaded file in that path but in my Ipad where i can see the downloaded pdf file please anyone tell where i have to find it.
Thanks.
Most likely your saving part is correct but try this anyways.
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://jesusredeems.com/mag/pdf/JRE-2014-03.pdf"]];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES);
NSString* documentsPath = [paths objectAtIndex:0];
NSString *destPath = [documentsPath stringByAppendingPathComponent:#"11011.pdf"];
[pdfData writeToFile:destPath atomically:YES];
And do this to retrieve it.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES);
NSString* documentsPath = [paths objectAtIndex:0];
NSString* dataFile = [documentsPath stringByAppendingPathComponent:#"11011.pdf"];
NSData *pdfData3 = [NSData dataWithContentsOfFile:dataFile];

Save NSData as PDF file

I am trying to save some NSData in pdf format. The NSData is from a downloaded pdf. This is how I tried to do it:
NSData* data = [DKStoreManager loadFileWithName:_FileName forFolderNumber:[_FolderNumber intValue] forUser:userID andType:_FolderType];
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSData* dataFile;
NSMutableDictionary* dict = [myDictionary objectForKey:#"MultiFileOtherFile2"];
dataFile = [dict objectForKey:#"FileData"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"mLocalFileName.pdf"];
[dataFile writeToFile:pdfPath atomically:YES];
NSString *phrase = nil; // Document password (for unlocking most encrypted PDF files)
ReaderDocument *document = [ReaderDocument withDocumentFilePath:pdfPath password:phrase];
This doesn't work. The only thing that works is:
NSArray *pdfs = [[NSBundle mainBundle] pathsForResourcesOfType:#"pdf" inDirectory:nil];
NSString *filePath = [pdfs lastObject]; assert(filePath != nil); // Path to last PDF file
ReaderDocument *document = [ReaderDocument withDocumentFilePath:filePath password:phrase];
...with a pdf added manually to Xcode!! I even tried all of the conversion solutions at:
How to convert a NSData to pdf in iPhone sdk?
...and none work!
Thanks in advance for any help.
Your issue is not in these lines of code. Your issue is that either:
the downloaded file is corrupt (so your information in the NSData is corrupt)
ReaderDocument, the class you use to open the file, has an bug and downloads the file incorrectly
Maybe the PDF file uses some PDF features which are not supported by your ReaderDocument class? PDF is a very broad format.

Zip library issue

So I am using this library: https://github.com/flyingdolphinstudio/Objective-Zip
I implemented it and am trying to take a UIImage and NSString and make it a .png and .txt in the .zip file, respectively.
Now these are my 2 concerns, I am trying to save the *zipFile below to the documents directory.
Now with the dropbox API, how come I can't just provide the file itself and skip the path. It seems like I HAVE to save the .zip to the documents directory first and then get the path so I can then upload it to dropbox. Do I have to do that?
In the ...writeToFile line, I am getting a warning that ZipFile may not respond to writeToFile so how would I properly save it to the documents directory?
Anyway this is the code I have so far:
NSString *filename = [NSString stringWithFormat:#"%#.zip", textField.text];
ZipFile *zipFile= [[ZipFile alloc] initWithFileName:filename mode:ZipFileModeCreate];
//Image
NSString *nameImage = #"Image.png";
NSMutableDictionary *theDictionary = [Singleton sharedSingleton].dictionary;
NSData *data = [theDictionary objectForKey:#"image"];
ZipWriteStream *writeImage = [zipFile writeFileInZipWithName:nameImage compressionLevel:ZipCompressionLevelBest];
[writeImage writeData:data];
[writeImage finishedWriting];
//Text
NSString *nameText = #"Text.txt";
NSData *dataText = [textView.text dataUsingEncoding:NSUTF8StringEncoding];
ZipWriteStream *writeText = [zipFile writeFileInZipWithName:nameText compressionLevel:ZipCompressionLevelBest];
[writeText writeData:dataText];
[writeText finishedWriting];
//Now we HAVE to save it to the documents directory to get it to work with dropbox
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:filename]; //Add the file name
[zipFile writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
//Save to Dropbox
NSString *zipPath = [[NSBundle mainBundle] pathForResource:textField.text ofType:#"zip"];
[[self restClient] uploadFile:filename toPath:#"/" withParentRev:nil fromPath:zipPath];
So what am I doing wrong here?
Thanks!
It looks to me like ZipFile already writes to a file, so there's no need for something like writeToFile. Just initialize zipFile with the path you want, be sure to close the file at the end ([zipFile close]), and then upload to Dropbox as you would any other file.

Resources