Get Print preview and save it in PDF file - iphone

I want to generate a print preview of a web page and save it to an PDF file.
i tried stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight";
and
stringByEvaluatingJavaScriptFromString:#"document.body.scrollWidth";
functions for finding the height and width but problem with this is the java script program stops after 10 second..
I want to use default print option that is used for airPrint, but i don't want that to print.
I just want to save the print preview in PDF.
Please any one help me..

NSString *webServiceUrlString =#"https://www.google.com"; //Google.com is for example use your url
NSData *pdfData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:webServiceUrlString]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:resourceDocPath error:&error]) {
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#/%#", resourceDocPath, file] error:&error];
if (!success || error) {
}
}
NSString* fileName = #"Your File Name.pdf";
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:fileName];
[pdfData writeToFile:filePath atomically:YES];

You can use UIGraphicsBeginPDFContextToFile to create a PDF file from your webpage content.
Check out the following tutorial.MAKING A PDF FROM A UIWEBVIEW

Related

disabling certain services in UIDocumentController

I have the following code to post photo to instagram:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString* homePath = [paths objectAtIndex:0];
NSString* basePath = #"integration/instagram";
NSString* tmpFileName = #"jumpto.ig";
NSString* dirPath = [NSString stringWithFormat:#"%#/%#", homePath, basePath];
NSString* docPath = [NSString stringWithFormat:#"%#/%#", dirPath, tmpFileName];
//clear it out and make it fresh
[[NSFileManager defaultManager] removeItemAtPath:docPath error:nil];
if ([[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil]) {
NSData* imgData = [self generateImageData:img];
[[NSFileManager defaultManager] createFileAtPath:docPath contents:imgData attributes:nil];
NSURL* url = [NSURL fileURLWithPath:docPath isDirectory:NO ];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://camera"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
//imageToUpload is a file path with .ig file extension
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:url];
self.documentInteractionController.UTI = #"com.instagram.exclusivegram";
self.documentInteractionController.delegate = self;
self.documentInteractionController.annotation = [NSDictionary dictionaryWithObject:#"Caption Test" forKey:#"InstagramCaption"];
[self.documentInteractionController presentOptionsMenuFromBarButtonItem:self.navigationItem.rightBarButtonItem animated:YES];
}
}
The issue is that when I open the popover, I see other services such as facebook/twitter/mail/print/assign to contact/copy/etc. How do I make it such that I only have one option which is Open in Instagram?
Instagram listens to both .jpg/.ig files as well as a special extension called .igo (Instagram Only). By changing the filename to .igo, only instagram should show up in the list:
NSString* tmpFileName = #"jumpto.igo";
Source: Instagram iPhone Hooks
Edit: I think there's a logical issue with how you're writing the file. Instead of using NSFileManager to write out the contents on this line:
[[NSFileManager defaultManager] createFileAtPath:docPath contents:imgData attributes:nil];
Try using the NSData object itself to write it into place:
[imgData writeToFile:docPath atomically:NO];
I'm not certain this will result in a different file, but I'm wondering if the way NSFileManager creates files with data is differently than how NSData writes the data directly.

Download file to Folder in iPhone

I am new to iPhone,
I made app in which, when user downloads anything it gets downloaded into DocumentDirectory
I wants downloading inside my folder which i have created in DocumentDirectory
How to achieve this ?
I thought I will download file to my DocumentDirectory and i will move that file to my folder inside DocumentDirectory.
Is it good practice ?
Here is my code snippet, But still i am unable to move my file.
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *file = [NSString stringWithString:[url absoluteString]];
NSURL *fileURL = [NSURL URLWithString:file];
NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
[NSURLConnection connectionWithRequest:req delegate:self];
NSString *DestPath=[[[SourcePath stringByAppendingString:#"/"]stringByAppendingString:BookCateg]stringByAppendingString:#"/"];
if ([fm copyItemAtPath:SourcePath toPath:DestPath error:&error])
{
NSLog(#"Success !");
}
else{
NSLog(#"Fail to Move!");
}
}
My log shows Fail to Move!
Any help will be appreciated.
You should directly download file to folder of document directory and for that u need to create directory as #iPhone Developer suggested and write file in that directory
For example:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/File"];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSURL *url = [NSURL URLWithString:#"http://www.ndqatar.mobi/18December/admin/rington/133/QatarDay13.mp3"];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data)
{
stringPath = [stringPath stringByAppendingPathComponent:[url lastPathComponent]];
[data writeToFile:stringPath atomically:YES];
}
If u want u can move file like this:
NSString *destPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/Dest"];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:destPath])
[[NSFileManager defaultManager] createDirectoryAtPath:destPath withIntermediateDirectories:NO attributes:nil error:&error];
destPath = [destPath stringByAppendingPathComponent:[stringPath lastPathComponent];];
[[NSFileManager defaultManager] copyItemAtPath:stringPath toPath:destPath error:&error];
You can use the following code:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/Your Folder Name"];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *DestPath=[stringPath stringByAppendingString:#"/Your file Name"];
You are using string by appending string instead of string by appending path component this will append the path and your file will move there
Enjoy coding
Framework: ReactJS
Library: Material-UI
Version: 4.0
i try using https://material-ui.com/api/button/
(add link in href of button) and it works on ipad/iphone/ios safari.
import Button from '#material-ui/core/Button';
<Button href={add_your_link_here} />

ios writeToFile changes don't save

ios claims the file has been written to, but the changes never actually save, as if they remain in buffer. Do I have to flush or something?
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:#"MyFile"
ofType:#"txt"];
NSLog(#"\n\nPath = \n%#", myFilePath);
NSString *myFileContents = [NSString stringWithContentsOfFile:myFilePath
encoding:NSUTF8StringEncoding
error:nil];
NSLog(#"\n\nContents = \n%#", myFileContents);
[#"This line will be written to file" writeToFile:myFilePath
atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSString *changedContents = [NSString stringWithContentsOfFile:myFilePath
encoding:NSUTF8StringEncoding
error:nil];
NSLog(#"\n\nChanged Contents = \n%#", changedContents);
}
Output:
Path =
/Users/hamzeh/Library/Application Support/iPhone Simulator/5.1/Applications/2B318687-A745-4CD9-85BA-52A01AB76F6E/savepersistentdata_tutorial.app/MyFile.txt
Contents =
This is a text file.
The file will be displayed on the iPhone.
That is all for now.
Changed Contents =
This line will be written to file
This is the output I get every time I run, so the changes don't actually get written to the file.
Thanks for the help.
You can't edit files in your main bundle. You have to first save the file to the applications documents folder then make any changes.
Here's some code to maybe fix your issue:
First save the text to a directory you create:
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:#"MyFile"
ofType:#"txt"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *directory = [NSString stringWithFormat:#"%#/Some_Directory", [paths objectAtIndex:0]];
// Check if the directory already exists
if (![[NSFileManager defaultManager] fileExistsAtPath:directory]) {
// Directory does not exist so create it
[[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
}
NSData *data = [[NSData dataWithContentsOfFile:myFilePath] retain];
NSString *filePath = [[directory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", [myFilePath lastPathComponent]]] retain];
NSError *error = nil;
if (![data writeToFile:filePath options:NSDataWritingFileProtectionNone error:&error]) {
[data writeToFile:filePath atomically:NO];
}
[data release];
[filePath release];
Use NO parameter
[#"This line will be written to file" writeToFile:myFilePath atomically:NO encoding:NSUTF8StringEncoding error:nil];
iOS docs says
(BOOL)useAuxiliaryFile
If YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the receiver is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.
You can not write file on main bundle, because resource bundle are read only. You can also check return of writeToFile method. Which returns false if you deploy it on device.

How to retrieve the Xml file from Cachedirectory?

Im new to Iphone development, I have locally saved one xml file and showing the details by using NSXmlParser(Which is stored in Resource folder). But, now i want to download new xml from url(from client side) and need to store that new xml file in Cache directory and also delete the xml file from resource folder. but i did not parse the new xml file from cache directory, How can i parse the new xml file from cache directory? Any one know this, please help me
I've actually just recently written this functionality for one of my projects. I'll share the code i used to do to save and write the XML file to my cache.
- (NSString *)XMLCacheFilePath
{
NSString *directory = #"/Library/Caches/XML/";
NSString *fileName = [#"file" stringByAppendingPathExtension:#"xml"];
// Setup directory path
NSString *homeDirectoryPath = NSHomeDirectory();
NSString *unexpandedDirectoryPath = [homeDirectoryPath stringByAppendingString:directory];
NSString *directoryPath = [NSString pathWithComponents:[NSArray arrayWithObjects:
[NSString stringWithString:[unexpandedDirectoryPath stringByExpandingTildeInPath]],
nil]];
// Setup file path
NSString *unexpandedFilePath = [directoryPath stringByAppendingPathComponent:fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:
[NSString stringWithString:[unexpandedFilePath stringByExpandingTildeInPath]],
nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:nil]) {
NSError *error = [[NSError alloc] init];
[[NSFileManager defaultManager] createDirectoryAtPath:directoryPath
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
return filePath;
}
- (void)saveXMLStringToDisk:(NSString *)xmlString
{
NSError *error;
[xmlString writeToFile:self.XMLCacheFilePath
atomically:YES
encoding:NSUTF8StringEncoding
error:&error];
}
- (NSString *)XMLStringFromDisk
{
NSString *XMLString = [NSString stringWithContentsOfFile:self.XMLCacheFilePath
encoding:NSUTF8StringEncoding
error:nil];
return XMLString;
}

Read RTFD data in IOS

I have RTFD data in NSData objects in IOS that I need to read. In MacOSX I just used to read them with NSAttributedString, but now I know that they are not supported in IOS.
attribString = [[NSAttributedString alloc] initWithRTFD:note documentAttributes:&dict];
Is there any way to read only the text of the RTFD data in IOS?
The rtfd in iOS is something like as a directory. If you only want to get the text part, you can try:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"photo" ofType:#"rtfd"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *content = [fileManager contentsOfDirectoryAtPath:filePath error:nil];
NSString *textFilePath = [filePath stringByAppendingPathComponent:#"TXT.rtf"];//you can get the path component from the content; usually it is TXT.rtf
NSError *error = nil;
NSString *pureText = [[NSString alloc] initWithContentsOfFile:textFilePath encoding:NSASCIIStringEncoding error:&error];
NSLog(#"pureText:\n%#",pureText);
Hope it can help.