0

I have open pdf file in uiwebview, add image and text in uiwebview subview.Then i tried created pdf file. Below sample i have used to generate pdf file. Multiple page writing in single page. How can i write sample quality and exact size. Please check screen shots and below sourceenter image description here

UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );

for (int i = 0; i < 10; i++) {

    CGRect f = [pdfView frame];
    [pdfView setFrame: f];

    UIGraphicsBeginPDFPage();
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins
    [[[pdfView subviews] lastObject] setContentOffset:CGPointMake(0, 648 * i) animated:NO];
    [pdfView.layer renderInContext:currentContext];
}

UIGraphicsEndPDFContext();

and also i have tried this following link but i couldn't add uiwebview subview to write the pdf. http://b2cloud.com.au/tutorial/drawing-over-a-pdf-in-ios-pdf-template/

2vision2
  • 4,933
  • 16
  • 83
  • 164

5 Answers5

2

You can use the following category on UIView to create a PDF file:

#import <QuartzCore/QuartzCore.h>

@implementation UIView(PDFWritingAdditions)

- (void)renderInPDFFile:(NSString*)path
{
    CGRect mediaBox = self.bounds;
    CGContextRef ctx = CGPDFContextCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], &mediaBox, NULL);

    CGPDFContextBeginPage(ctx, NULL);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -mediaBox.size.height);
    [self.layer renderInContext:ctx];
    CGPDFContextEndPage(ctx);
    CFRelease(ctx);
}

@end

Bad news: UIWebView does not create nice shapes and text in the PDF, but renders itself as an image into the PDF.

OR

How to Convert UIView to PDF within iOS?

OR

Creating PDF file from UIWebView

This might helps you :)

Community
  • 1
  • 1
Yuyutsu
  • 2,509
  • 22
  • 38
  • Thanks for you answer . I will check it then let you know. But one thing if we add "renderInContext" we have loose our quality – 2vision2 Jan 13 '15 at 13:25
  • i tried to create PDF file from UIwebview but im getting height string in empty . NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"]; – 2vision2 Jan 19 '15 at 09:43
  • if we use "renderInContext" page quality is missing . Please advice – 2vision2 Jan 19 '15 at 11:10
2

I have also used the same its working fine Hope this will be helpful for you.

Create a block:-
typedef void (^PdfCompletion)(BOOL status,NSString *filePath,NSArray *fbArr);

-(void)addData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *contactDict = [[NSMutableDictionary alloc] init];
    [contactDict setObject:contactTextField.text forKey:@"phonenumber"];
    [contactDict setObject:emailTextField.text forKey:@"emailid"];
    [contactDict setObject:userNameLabel.text forKey:@"displayname"];
    [self drawPdf:contactDict completion:^(BOOL status,NSString *filePath,NSArray *fbArr)
     {
         if (status)
         {
             NSMutableArray *arr;
             arr = [[NSMutableArray alloc] init];
             NSData *filedata;
             filedata = [NSData dataWithContentsOfFile:filePath];
             double locaTotalFileSize = filedata.length +498;
             totalFileSize += locaTotalFileSize;
             NSMutableDictionary *fileDict = [[NSMutableDictionary alloc] init];
             [fileDict setObject:userPicImageView.image forKey:@"image"];
             [fileDict setObject:filePath forKey:@"filePath"];
             [fileDict setObject:@"txt" forKey:@"fileType"];
             [fileDict setObject:[NSString stringWithFormat:@"%@_%@_%@",@"contact",[self getFbID],[self CurrentSystemTime]] forKey:@"fileName"];
             [fileDict setObject:@"1" forKey:@"uploadStatus"];
             [fileDict setObject:@"0 KB/0 KB" forKey:@"fileSizeStatus"];
             [fileDict setObject:@"0 KB/0 KB" forKey:@"ContentSize"];
             [arr addObject:fileDict];
             [self switchToReviewFiles:arr];
             //////NSLog(@"pdf convrt successfull");
         }
         else
         {
             //////NSLog(@"Error to convert into pdf");
         }
     }];
}


 // Then Call The DrawPDF Method::--

 -(void)drawPdf:(NSMutableDictionary *)drawText completion:(PdfCompletion)callback
{
    NSString* fileName = @"contact_card.txt";

    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
                                        NSDocumentDirectory,
                                        NSUserDomainMask,
                                        YES);
    NSString *path = [arrayPaths objectAtIndex:0];
    NSString* txtFileName = [path stringByAppendingPathComponent:fileName];

    NSData *data = [NSJSONSerialization dataWithJSONObject:drawText options:NSJSONWritingPrettyPrinted error:nil];
    [data writeToFile:txtFileName atomically:YES];
     callback(YES,txtFileName,nil);

}
Vinod Pandey
  • 183
  • 4
  • Vinod Pandey thanks for your reply . i will test then update you. today only i came after long leave – 2vision2 Jan 19 '15 at 05:31
1

You can try this.It worked for me :)

https://github.com/iclems/iOS-htmltopdf/blob/master/NDHTMLtoPDF.h

NSString *html = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];

 self.PDFCreator = [NDHTMLtoPDF createPDFWithHTML:html
                                          pathForPDF:[path  stringByExpandingTildeInPath]
                                            delegate:self
                                            pageSize:CGSizeMake(595,847)
                                             margins:UIEdgeInsetsMake(105, 0, 0, 0)];

Pass the webView like this

Nikita Khandelwal
  • 1,741
  • 16
  • 25
1

It looks to me like you're just trying to add content to an existing PDF, right?

- (void) drawCustomPDFContent
{
    //  Put your drawing calls here
    //  Draw a red box
    [[UIColor redColor] set];
    UIRectFill(CGRectMake(20, 20, 100, 100));

    //  Example of drawing your view into PDF, note that this will be a rasterized bitmap, including the text.
    //  To get smoother text you'll need to use the NSString draw methods
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
}

- (void) createCustomPDF
{
    NSURL* pdfURL = ... /* URL to pdf file */;
    CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);

    const size_t numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);

    NSMutableData* data = [NSMutableData data];
    UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);

    for(size_t page = 1; page <= numberOfPages; page++)
    {
        //  Get the current page and page frame
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf, page);
        const CGRect pageFrame = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);

        UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);

        //  Draw the page (flipped)
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSaveGState(ctx);
        CGContextScaleCTM(ctx, 1, -1);
        CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
        CGContextDrawPDFPage(ctx, pdfPage);
        CGContextRestoreGState(ctx);

        if(page == 1)
        {
            [self drawCustomPDFContent];
        }
    }

    UIGraphicsEndPDFContext();

    CGPDFDocumentRelease(pdf);
    pdf = nil;

    //  Do something with data here
    [data writeToFile:... atomically:YES];
}

Parts referenced from:

http://b2cloud.com.au/tutorial/drawing-over-a-pdf-in-ios-pdf-template/

SomeGuy
  • 9,670
  • 3
  • 32
  • 35
  • Yes i just draw content in existing PDF. i viewed the pdf file in uiwebview – 2vision2 Jan 19 '15 at 11:53
  • If the problem you're having is drawing on top of an existing PDF, give my code a shot, you'll need to do a few changes to get it to work for your scenario. – SomeGuy Jan 19 '15 at 11:56
  • how to add draw all subviews(more) ?please advice – 2vision2 Jan 19 '15 at 13:49
  • Someguy its working fine . But i have wrote image in uiwebview subview where user have touched. When i have generate the pdf exact GCpoint i dint get to write ? Bz pdf original size diff for UIWebview . Please tel me how it will resolve ? – 2vision2 Jan 19 '15 at 14:39
  • @2vision2 you can use any custom drawing code you need, if you already have the view you want to draw, you can try the same renderInContext method call that others have also suggested – SomeGuy Jan 19 '15 at 14:40
  • how to add subview in renderInContext ? – 2vision2 Jan 19 '15 at 14:54
  • I put example code to draw the view in drawCustomPDFContent, note that it will be rasterized and a bit pixelated, you may be about to get a better result by changing the draw scale though – SomeGuy Jan 19 '15 at 23:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/69167/discussion-between-2vision2-and-someguy). – 2vision2 Jan 20 '15 at 03:58
  • Please SomeGuy help me to resolve still im struggling – 2vision2 Feb 23 '15 at 09:58
0

You are actually very close with the code you have. I have a feeling your biggest problem is grabbing a new CGContextRef with each loop iteration..

UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );
CGContextRef currentContext = UIGraphicsGetCurrentContext();//movedByJef

  //  default pdf..
  // 8.5 X 11 inch
  // 612 x 792


for (int i = 0; i < 10; i++) {

    CGContextSaveGstate( currentContext ); //addedByJef

    CGRect f = [pdfView frame];
    [pdfView setFrame: f]; // hmm what does this even do??

    UIGraphicsBeginPDFPage();
    CGContextTranslateCTM(currentContext, -72, -72); // Translate for 1" margins ///editedByJef, you had it backwards..

//assuming you want a 72pt margin on right and bottom as well..
//we want to reduce our size (612 x 792) by 72pts on all four sides..

CGSize printPageSize = CGSizeMake( (612.0 - (72.0 * 2.0)), (792.0 -(72.0*2.0)) );
CGSize layrSize = self.layer.bounds.size;

//so we translate the context so our view fills it nicely..
CGFloat xScaler = layrSize.width / printPageSize.width;
CGFloat yScaler = layrSize.height / printPageSize.height;

CGContextConcatCTM(currentContext, CGAffineTransformMakeScale(xScaler, yScaler) );


    [[[pdfView subviews] lastObject] setContentOffset:CGPointMake(0, 648 * i) animated:NO];
    [pdfView.layer renderInContext:currentContext];

CGContextRestoreGstate(currentContext);//added by jef
}

UIGraphicsEndPDFContext();

let me know how you go with that, There will undoubtedly be a bit of shuffling in the order of the transforms, maybe a translate needed either side of the scaling, but this should get you really close..

Jef
  • 4,728
  • 2
  • 25
  • 33