Created
January 16, 2015 09:32
-
-
Save itsdamslife/e2c3cec47a2a7bfea727 to your computer and use it in GitHub Desktop.
Sample code to convert a View to PDF - Referred from : http://stackoverflow.com/questions/15813005/creating-pdf-file-from-uiwebview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(void)convertToPDF:(UIView*)aView withFileName:(NSString*)aFilename | |
{ | |
// Creates a mutable data object for updating with binary data, like a byte array | |
UIWebView *webView = (UIWebView*)aView; | |
NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"]; | |
int height = [heightStr intValue]; | |
CGFloat screenHeight = webView.bounds.size.height; | |
int pages = ceil(height / screenHeight); | |
NSMutableData *pdfData = [NSMutableData data]; | |
UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil); | |
CGRect frame = [webView frame]; | |
for (int i = 0; i < pages; i++) | |
{ | |
// Check to screenHeight if page draws more than the height of the UIWebView | |
if ((i+1) * screenHeight > height) | |
{ | |
CGRect f = [webView frame]; | |
f.size.height -= (((i+1) * screenHeight) - height); | |
[webView setFrame: f]; | |
} | |
UIGraphicsBeginPDFPage(); | |
CGContextRef currentContext = UIGraphicsGetCurrentContext(); | |
// CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins | |
[[[webView subviews] lastObject] setContentOffset:CGPointMake(0, screenHeight * i) animated:NO]; | |
[webView.layer renderInContext:currentContext]; | |
} | |
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]; | |
[webView setFrame:frame]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment