Programmatically create a high resolution PDF file

 

 

iOS SDK - Programmatically create a high resolution PDF file

There are so many ways to create PDF in IOS, but most of them which are easy create a low resolution PDF’s and one which creates high resolution PDF’s are very tough to handle for a guy like me. In this post, i am going to create PDF’s using drawInRect method. I know most of the guy’s give this idea a very poor programing to create PDF’s. But nevertheless, it solves my issue for the project on which i am working at that time. Let’s jump on to it

This method is very convenient if you have to create pdf’s from a view that contains label and images.
Below is the code that will create high resolution pdf’s.

 CGRect pageFrame = CGRectMake(0, 0, 768, 1500);

 UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);
 UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);
 
        for (UILabel *lb in [scroll  subviews])

        {
            if ([lb isKindOfClass:[UILabel class]])
            {

                NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];

                textStyle.lineBreakMode = lb.lineBreakMode;
                textStyle.alignment = lb.textAlignment;

                NSDictionary *dictionary = @{ NSFontAttributeName: lb.font, NSParagraphStyleAttributeName:textStyle};
                

                if (![lb isHidden])
                {
                    [lb.text drawInRect:lb.frame withAttributes:dictionary];
                }

                

            }

            

         }

 

        for (UIImageView *imgv in [scroll  subviews])
        {
            if ([imgv isKindOfClass:[UIImageView class]])
            {
                if (imgv.tag == 100)
                {
                      [imgv.image  drawInRect:CGRectMake(imgv.frame.origin.x, imgv.frame.origin.y, imgv.frame.size.width, imgv.frame.size.height)];
                } 
            }   
        }        
  }

 UIGraphicsEndPDFContext();
 

 NSString *fileName = @”Dummy.pdf”;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

 

    [pdfData writeToFile:pdfFileName atomically:NO];

Pdf generated by using this code is viewable here