I am trying to create the PDF and then load the pdf in webview for preview. Now that i can create the pdf successfully. Next I want to create the pdf by pressing button and then load in the webview. I have referenced this link and this link. Although the pdf is successfully created, the pdf cannot load in the webview. Could anyone provide suggestion? Thank you very much.
The code:
-(IBAction)preview:(id)sender
{
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
NSDate*todayDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd-MM-yyyy "];
NSString *mytext = [NSString stringWithFormat:@"form%@",[dateFormatter stringFromDate:todayDate]];
[self createPDFfromUIView:_myView saveToDocumentsWithFileName:mytext];
NSLog(@"is saved in %@", mytext);
NSString *path = [self createPDFfromUIView:_myView saveToDocumentsWithFileName:mytext];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
}
-(NSMutableData *)createPDFDatafromUIView:(UIView*)aView
{
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[aView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
return pdfData;
}
-(NSString*)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
NSMutableData *pdfData = [self createPDFDatafromUIView:aView];
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[aView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
NSLog(@"saved in %@", documentDirectoryFilename);
return documentDirectoryFilename;
}