Reputation: 1272
I'm converting my WebView to PDf using following code.
UIWebView *webView = self.webView;
NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
int height = [heightStr intValue];
// CGRect screenRect = [[UIScreen mainScreen] bounds];
// CGFloat screenHeight = (self.contentWebView.hidden)?screenRect.size.width:screenRect.size.height;
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);
f.size.width = self.webView.bounds.size.width*1.6;
[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 stringByAppendingString:@"/pdfFile.PDF"] ;
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
[webView setFrame:frame];
But the issue is its generating PDF with page break as shown in image.
I don't want this page break.can any one suggest what should I do.
Upvotes: 0
Views: 1943
Reputation: 1105
This little css worked for me.
@media print {
.avoid_pagebreak { display: block; page-break-inside:avoid; page-break-before: auto; }
}
...
<div class="avoid_pagebreak">
...
</div>
Upvotes: 0
Reputation: 20021
You are setting the page size here
UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil);
currently set to webView.bounds
Change it with appropriate value.
Upvotes: 1