how to save pdf from uiwebview in objective c

1.1k views Asked by At

i want to save pdf to ibook from UIWebView in the app, the html in UIWebView can be multi page.
i try using

NSString *page = [self.lowWebview stringByEvaluatingJavaScriptFromString:@"document.body.outerHTML"];
NSString *path = [self exportHTMLContentToPDF:page];

NSURL *targetURL = [NSURL fileURLWithPath:path];

self.docController = [UIDocumentInteractionController interactionControllerWithURL:targetURL];

if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"itms-books:"]])
{
    [self.docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    NSLog(@"iBooks installed");

} else {

    NSLog(@"iBooks not installed");

}

exportHTMLContentToPDF:

CustomPrintPageRenderer *printPageRenderer = [[CustomPrintPageRenderer alloc] init];

UIMarkupTextPrintFormatter *printFormatter = [[UIMarkupTextPrintFormatter alloc] initWithMarkupText:HTMLContent];

[printPageRenderer addPrintFormatter:printFormatter startingAtPageAtIndex:0];//.addPrintFormatter(printFormatter, startingAtPageAtIndex: 0)

NSData *pdfData = [self drawPDFUsingPrintPageRenderer:printPageRenderer];

NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName = [docDirPath stringByAppendingPathComponent:@"ticket.pdf"];

[pdfData writeToFile:fileName atomically:true];//.writeToFile(fileName, atomically: true)

NSLog(@"%@", fileName);
return fileName;

the problem is exportHTMLContentToPDF create just one page if UIWebView contain multiple page, and some time the output format is not well print in pdf

thanks in advance.

3

There are 3 answers

1
Md. Ibrahim Hassan On

Create PDF from any Microsoft Document loaded in UIWebview

#define kPaperSizeA4 CGSizeMake(595.2,841.8)

First of all implement UIPrintPageRenderer protocol

@interface UIPrintPageRenderer (PDF)

- (NSData*) printToPDF;

@end

@implementation UIPrintPageRenderer (PDF)

- (NSData*) printToPDF
{
    NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, nil );
    [self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
    CGRect bounds = UIGraphicsGetPDFContextBounds();
    for ( int i = 0 ; i < self.numberOfPages ; i++ )
    {
        UIGraphicsBeginPDFPage();
        [self drawPageAtIndex: i inRect: bounds];
    }
    UIGraphicsEndPDFContext();
    return pdfData;
}
@end

Then, call below method after document finished loading in UIWebView

-(void)createPDF:(UIWebView *)webView {

UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
[render addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0];

float padding = 10.0f;
CGRect paperRect = CGRectMake(0, 0, kPaperSizeA4.width, kPaperSizeA4.height);
CGRect printableRect = CGRectMake(padding, padding, kPaperSizeA4.width-(padding * 2), kPaperSizeA4.height-(padding * 2));

[render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];
[render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];

NSData *pdfData = [render printToPDF];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    if (pdfData) {
        [pdfData writeToFile:directoryPath atomically: YES];
    }
    else
    {
        NSLog(@"PDF couldnot be created");
    }
});}

Excerpted from PDF Creation in iOS - Create PDF from any Microsoft Document loaded in UIWebview. The original author was Mansi Panchal. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 2416 and example ID: 28437.

0
jki On
0
Mr.Javed Multani On
#define kPaperSizeA4 CGSizeMake(595.2,841.8)

First of all implement UIPrintPageRenderer protocol

@interface UIPrintPageRenderer (PDF)
- (NSData*) printToPDF;
@end
@implementation UIPrintPageRenderer (PDF)
- (NSData*) printToPDF
{
NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, nil );
    [self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
    CGRect bounds = UIGraphicsGetPDFContextBounds();
    for ( int i = 0 ; i < self.numberOfPages ; i++ )
    {
UIGraphicsBeginPDFPage();
[self drawPageAtIndex: i inRect: bounds];
    }
UIGraphicsEndPDFContext();
return pdfData;
}
@end

Then, call below method after document finished loading in UIWebView


-(void)createPDF:(UIWebView *)webView {
UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
[render addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0];
float padding = 10.0f;
CGRect paperRect = CGRectMake(0, 0, kPaperSizeA4.width, kPaperSizeA4.height);
CGRect printableRect = CGRectMake(padding, padding, kPaperSizeA4.width-(padding * 2), kPaperSizeA4.height-(padding * 2));
[render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];
 [render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];
NSData *pdfData = [render printToPDF];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (pdfData) {
        [pdfData writeToFile:directoryPath atomically: YES];
}
else
{
        NSLog(@"PDF couldnot be created");
} });}

enter image description here

Ref: https://medium.com/@javedmultani16/create-pdf-from-any-microsoft-document-loaded-in-uiwebview-in-ios-15229671060b