how can i write a text on the image and save it - ios

im trying to first upload an image then write a text on it and after that save both items as one image.
im new in objective c so my code might be not the best way to get to my goal any help and suggestion wil help me.
thank you all
this is my code :
some how this editor is not allowing me to put my method declaration on
enter code here
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *data = UIImagePNGRepresentation(image);
NSString *mijnImage =#"mijnImage.png";
NSArray *route = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *imageRoute = [route objectAtIndex:0];
NSString *routeNaarDeBestaand = [imageRoute stringByAppendingPathComponent:mijnImage];
[data writeToFile:routeNaarDeBestaand atomically:YES];
[[self imageView]setImage:image];
[self dismissViewControllerAnimated:YES completion:Nil];
self.imageView.image = [self drawText:#"Test String" inImage:image atPoint:CGPointMake(10, 20)];
this is another methode declaration same problem the editor is not allowing me to put it on
UIFont *font = [UIFont boldSystemFontOfSize:100];
UIGraphicsBeginImageContext(self.view.frame.size);
[originalImage drawInRect:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height)];
CGRect rect = CGRectMake(point.x, point.y,lblText.frame.size.width, lblText.frame.size.height);
rect.size = [text sizeWithAttributes:#{NSFontAttributeName:[UIFont systemFontOfSize:150.0f]}];
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:font forKey:NSFontAttributeName];
[attributes setObject:[NSNumber numberWithFloat:4] forKey:NSStrokeWidthAttributeName];
[attributes setObject:[UIColor whiteColor] forKey:NSStrokeColorAttributeName];
[text drawInRect:rect withAttributes:attributes];
[attributes removeObjectForKey:NSStrokeWidthAttributeName];
[attributes removeObjectForKey:NSStrokeColorAttributeName];
[attributes setObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
[text drawInRect:rect withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;

I don't really know what problem is, but I did this.. let me know if it works for you
- (void)viewDidLoad
{
UIImage *image = [UIImage imageNamed:#"image"];
UIImage *newImage = [self image:image withText:#"Hello World" atPoint:CGPointMake(20, 20)];
[self saveImage:image withName:#"original"];
[self saveImage:newImage withName:#"new"];
}
- (UIImage*)image:(UIImage*)image withText:(NSString*)text atPoint:(CGPoint)point
{
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[image drawInRect:rect];
NSDictionary *attributes = #{NSFontAttributeName : [UIFont boldSystemFontOfSize:20],
NSStrokeWidthAttributeName : #(4),
NSStrokeColorAttributeName : [UIColor whiteColor]};
[text drawAtPoint:point withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (void)saveImage:(UIImage*)image withName:(NSString*)name
{
NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *imagePath = [documents stringByAppendingPathComponent:name];
[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
}

Try this
+(UIImage*) drawText:(NSString*) text
inImage:(UIImage*) image
atPoint:(CGPoint) point
{
UIFont *font = [UIFont boldSystemFontOfSize:12];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
[[UIColor whiteColor] set];
[text drawInRect:CGRectIntegral(rect) withFont:font];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

This answer will make the text both aligned vertically and horizontally in the center of the UIImage.
Note: not my answer it is collected from several answers
- (UIImage*)image:(UIImage*)image withText:(NSString*)text{
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[image drawInRect:rect];
/// Make a copy of the default paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
/// Set text horizontal alignment
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = #{NSFontAttributeName : [UIFont boldSystemFontOfSize:16],
NSStrokeWidthAttributeName : #(4),
NSStrokeColorAttributeName : [UIColor whiteColor],
NSParagraphStyleAttributeName : paragraphStyle};
CGSize size = [text sizeWithAttributes:attributes];
CGRect newRect = CGRectMake(rect.origin.x,
rect.origin.y + (rect.size.height - size.height)/2.0,
rect.size.width,
size.height);
[text drawInRect:newRect withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;}

Related

Converting a UIWebView to PDF/Image gives only one inch wide output

I'm converting a UIWebView to pdf/image with the help of the following code:
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];
NSMutableArray *imageArray= [[NSMutableArray alloc]init];
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];
}
UIGraphicsBeginImageContext(frame.size);
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];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
[imageArray insertObject:viewImage atIndex:imageArray.count] ;
UIGraphicsEndImageContext();
}
UIGraphicsEndPDFContext();
[webView setFrame:frame];
//Send all images
NSData *imgData = [self blendImages:imageArray];
//Final Image
UIImage *finalImage = [UIImage imageWithData:imgData];
-(NSData*)blendImages:(NSMutableArray *)arrImage{
// get data from document
CGFloat height=0 ,width=0 ;
UIImage *tempImg = [arrImage objectAtIndex:0] ;
width =tempImg.size.width ;
for (int i = 0 ; i<arrImage.count ; i++){
UIImage *img= [arrImage objectAtIndex:i];
height = img.size.height +height;
}
CGSize size = CGSizeMake(width, height) ;
UIGraphicsBeginImageContext(size);
CGFloat h = 0;
for (int i=0; i<arrImage.count; i++) {
UIImage* uiimage = [arrImage objectAtIndex:i];
[uiimage drawAtPoint:CGPointMake(0, h) blendMode:kCGBlendModeNormal alpha:1.0];
h = uiimage.size.height +h ;
}
NSData *imageData = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext());
UIGraphicsEndImageContext();
return imageData;
}
But I'm getting only one inch wide output. Also the whole contains fits in one page and make it unreadable. How to make A4 sized output?
This creates a PDF of a screenshot of a webpage - might help get you started :)
- (IBAction)makePDF:(id)sender
{
UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize, webView.scrollView.opaque, 0.0);
webView.scrollView.contentOffset = CGPointZero;
webView.scrollView.frame = CGRectMake(0, 0, webView.scrollView.contentSize.width, webView.scrollView.contentSize.height);
[webView.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect imageFrame = CGRectMake(0, 0, image.size.width, image.size.height);
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, imageFrame, nil);
//full screenshot
UIGraphicsBeginPDFPage();
UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageFrame];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
[imageView setImage:image];
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndPDFContext();
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentDirectory = [documentDirectories objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#.pdf",[NSDate date]];
NSString *path = [documentDirectory stringByAppendingPathComponent:fileName];
// save to disk
[pdfData writeToFile:path atomically:YES];
NSLog(#"pdf in %#", path);
}

How to set text on uiimage center?

UIGraphicsBeginImageContext(targetSize);
NSString *txt = #"my String";
UIColor *txtColor = [UIColor whiteColor];
UIFont *txtFont = [UIFont systemFontOfSize:30];
NSDictionary *attributes = #{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor};
[txt drawAtPoint:CGPointMake(0, 0) withAttributes:attributes];
UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I don't know how to fix it to make text to Center.
//Edit
I add your device but in vain
NSMutableParagraphStyle *styleCenter = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
styleCenter.alignment = kCTCenterTextAlignment;
NSDictionary *attributes = #{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor,NSParagraphStyleAttributeName:styleCenter};
[txt drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height) withAttributes:attributes];
the text show at right not center, so weird
Try this:
UIGraphicsBeginImageContext(targetSize);
NSString *txt = #"my String";
UIColor *txtColor = [UIColor whiteColor];
UIFont *txtFont = [UIFont systemFontOfSize:30];
NSDictionary *attributes = #{NSFontAttributeName:txtFont, NSForegroundColorAttributeName:txtColor};
CGRect txtRect = [txt boundingRectWithSize:CGSizeZero
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
[txt drawAtPoint:CGPointMake(targetSize.width/2 - txtRect.size.width/2, targetSize.height/2 - txtRect.size.height/2) withAttributes:attributes];
UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSMutableParagraphStyle *styleCenter = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
styleCenter.alignment = NSCenterTextAlignment;
NSDictionary *attributes = #{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor,NSParagraphStyleAttributeName:styleCenter};
[txt drawInRect:rect withAttributes:attributes];
This category on NSString will draw the centered text in rect with given below font:
#implementation NSString (Helpers)
- (void)drawCentredInRect:(CGRect)rect withFont:(nullable UIFont *)font andForegroundColor:(nullable UIColor *)foregroundColor {
NSMutableDictionary *attributes = [NSMutableDictionary new];
if (font) {
attributes[NSFontAttributeName] = font;
}
if (foregroundColor) {
attributes[NSForegroundColorAttributeName] = foregroundColor;
}
CGSize textSize = [self sizeWithAttributes:attributes];
CGPoint drawPoint = CGPointMake(
CGRectGetMidX(rect) - (int) (textSize.width / 2),
CGRectGetMidY(rect) - (int) (textSize.height / 2)
);
[self drawAtPoint:drawPoint withAttributes:attributes];
}
I tried the answer for your clever question,Now I got the solution
+(UIImage*) drawText:(NSString*)text inImage:(UIImage*)image atPoint:(CGPoint)point
{
UIGraphicsBeginImageContextWithOptions(image.size, YES, 0.0f);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
[[UIColor whiteColor] set];
if([text respondsToSelector:#selector(drawInRect:withAttributes:)])
{
//iOS 7 or above iOS 7
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
[text drawInRect:rect withAttributes:attr];
}
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Please call the above method in where you pick the image like below
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *imagePicked = info[UIImagePickerControllerEditedImage];
picker.delegate = self;
self.imageViewTextCenter.image = [ViewController drawText:#"WELCOME"
inImage:imagePicked
atPoint:CGPointMake(0, 0)];;
[picker dismissViewControllerAnimated:YES completion:nil];
}

Can't set font for drawInRect

I'm trying to draw text on a context, and it works.
I'm trying to set an UIfont to this text but it doesn't work. The text size remain the same.
Here my code
- (UIImage *)imageByDrawingCircleOnImage:(UIImage *)image
{
UIGraphicsBeginImageContextWithOptions((image.size), NO, [[UIScreen mainScreen]scale] );
[image drawAtPoint:CGPointZero];
CGContextRef context = UIGraphicsGetCurrentContext();
UIFont *font = [UIFont systemFontOfSize:30];;//[UIFont fontWithName: #"Helvetica" size:45.0];
CGContextSetRGBStrokeColor(context, 210.0/255.0f, 0.0f, 0.0f, 1.0f);
CGContextSetRGBFillColor(context, 192.0/255.0, 0.0/255.0 , 13.0/255.0, 1.0);
NSMutableParagraphStyle *textStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentRight;
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
[attributes setObject:textStyle forKey:#"NSParagraphStyleAttributeName"];
[attributes setObject:font forKey:#"NSFontAttributeName"];
NSString *string = #"Tour de poitrine : 95 cm";
CGSize string_len =[string sizeWithAttributes:attributes];
[string drawInRect:CGRectMake(245 - string_len.width, 100.0, string_len.width , 100) withAttributes:[NSDictionary dictionaryWithDictionary:attributes]];
UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return retImage;
}
Thanks
Alexandre
Do not use strings for your attributes dictionary keys, use the constants provided by the framework.
Replace #"NSFontAttributeName" by NSFontAttributeName and #"NSParagraphStyleAttributeName" by NSParagraphStyleAttributeName.
Replace your code by this. It's working for me.
- (UIImage *)imageByDrawingCircleOnImage:(UIImage *)image
{
UIGraphicsBeginImageContextWithOptions((image.size), NO, [[UIScreen mainScreen]scale] );
[image drawAtPoint:CGPointZero];
CGContextRef context = UIGraphicsGetCurrentContext();
UIFont *font = [UIFont fontWithName: #"Chalkduster" size:20.0];
CGContextSetRGBStrokeColor(context, 210.0/255.0f, 0.0f, 0.0f, 1.0f);
CGContextSetRGBFillColor(context, 192.0/255.0, 0.0/255.0 , 13.0/255.0, 1.0);
NSMutableParagraphStyle *textStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentRight;
NSString *string = #"Tour de poitrine : 95 cm";
NSDictionary* attributes = #{NSFontAttributeName: font,
NSForegroundColorAttributeName: [UIColor redColor],
NSParagraphStyleAttributeName: textStyle
};
CGSize string_len =[string sizeWithAttributes:attributes];
[string drawInRect:CGRectMake(245 - string_len.width, 100.0, string_len.width , 100) withAttributes:[NSDictionary dictionaryWithDictionary:attributes]];
UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return retImage;
}
Try this:
//// General Declarations
CGContextRef context = UIGraphicsGetCurrentContext();
//// Text Drawing
CGRect textRect = CGRectMake(CGRectGetMinX(frame) + 23, CGRectGetMinY(frame) + 28, 101, 27);
{
NSString* textContent = #"Hello, World!";
NSMutableParagraphStyle* textStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;
textStyle.alignment = NSTextAlignmentLeft;
NSDictionary* textFontAttributes = #{NSFontAttributeName: [UIFont systemFontOfSize: UIFont.labelFontSize], NSForegroundColorAttributeName: UIColor.blackColor, NSParagraphStyleAttributeName: textStyle};
CGFloat textTextHeight = [textContent boundingRectWithSize: CGSizeMake(textRect.size.width, INFINITY) options: NSStringDrawingUsesLineFragmentOrigin attributes: textFontAttributes context: nil].size.height;
CGContextSaveGState(context);
CGContextClipToRect(context, textRect);
[textContent drawInRect: CGRectMake(CGRectGetMinX(textRect), CGRectGetMinY(textRect) + (CGRectGetHeight(textRect) - textTextHeight) / 2, CGRectGetWidth(textRect), textTextHeight) withAttributes: textFontAttributes];
CGContextRestoreGState(context);
}

How to convert NSString to UIImage for appengine blobstore

when I do the following the resulting image is null
NSLog(#"string (%#) to base64NSData",object);
NSData *base64Data = [[object dataUsingEncoding:NSUTF8StringEncoding] base64EncodedDataWithOptions:0];
NSLog(#"NSData (%#) to UIImage",base64Data);
UIImage *image = [UIImage imageWithData:base64Data];
NSLog(#"my image is: %#",image);
How might I do this well?
Reason
I need to save an image from iOS to the Google blobstore. I need to include some metadata with the image. When I encode the string as base64 it does not work.
This is loosely a follow up to AFHTTPRequestOperationManager post multi-part request not working
Here is the code for generating image from NSString..
Implement this method....
+(UIImage *)imageFromText:(NSString *)text
{
UIFont *font = [UIFont systemFontOfSize:20.0];
CGSize size = [text sizeWithAttributes:
#{NSFontAttributeName:
[UIFont systemFontOfSize:20.0f]}];
if (UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
else
UIGraphicsBeginImageContext(size);
[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
// [text drawAtPoint:CGPointMake(0.0, 0.0) forWidth:CGPointMake(0, 0) withFont:font fontSize:nil lineBreakMode:NSLineBreakByWordWrapping baselineAdjustment:NSTextAlignmentCenter];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Call this method like...
UIImage *image;
image = [self imageFromText:#"Good Morning];
//Use this image as per your requirement
I hope it work for you..
Here is UIImage category I used to fix my problem
http://hasseg.org/blog/post/692/use-unicode-emoji-as-icons-in-native-ios-apps/
You can modify method to pass extra parameters like font, color, backgroundColor as follows :
+ (UIImage *) hg_imageFromString:(NSString *)string withFont:(UIFont*)font textColor:(UIColor*)color andBgColor:(UIColor*)bgColor;
{
UILabel *label = [[UILabel alloc] init];
label.text = string;
label.opaque = NO;
if(bgColor != nil)
label.backgroundColor = bgColor;
if(color != nil)
label.textColor = color;
if(font != nil)
label.font = font;
else
label.font = [UIFont systemFontOfSize:17.0];
CGSize size = [string sizeWithAttributes:#{NSFontAttributeName: label.font}];
CGSize measuredSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
label.frame = CGRectMake(0, 0, measuredSize.width, measuredSize.height);
return [UIImage hg_imageFromView:label];
}

adding link to pdf not working in ios?

I want functionality in which link should be generated in pdf file.When user clicks on that link it should be navigated to that file.For that i have used following code.It has generated the pdf but i am not able to genreate the link.How can i do that?
-(void)generatePDF
{
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString *pdfFileName = [documentDirectory stringByAppendingPathComponent:#"mypdf.pdf"];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
NSString *myString = #"My PDF Heading";
[myString drawInRect:CGRectMake(20, 100, 200, 34) withFont:[UIFont fontWithName:#"HelveticaNeue-Bold" size:13] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
UIGraphicsAddPDFContextDestinationAtPoint(#"Chapter1", CGPointMake(72, 72));
UIGraphicsSetPDFContextDestinationForRect(#"Chapter1", CGRectMake(72, 528, 400, 40));
UIGraphicsEndPDFContext();
[self showPDFFile];
}
Using following code i was able to generate links in pdf and navigate to other page in pdf
-(void)generatePDF
{
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
/// Set text alignment
paragraphStyle.alignment = NSTextAlignmentLeft;
NSDictionary *attributes = #{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue-Bold" size:13],NSParagraphStyleAttributeName:paragraphStyle};
NSDictionary *attributes2 = #{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue-Bold" size:13],NSParagraphStyleAttributeName:paragraphStyle,NSBackgroundColorAttributeName:[UIColor yellowColor]};
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString *pdfFileName = [documentDirectory stringByAppendingPathComponent:#"mypdf.pdf"];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
NSString *myString = #"Page1";
[myString drawInRect:CGRectMake(20, 100, 200, 34) withAttributes:attributes];
UIGraphicsAddPDFContextDestinationAtPoint(#"NavigateToPage1", CGPointMake(0, 0));
[self drawTextLink2:#"NavigateToPage3" inFrame:CGRectMake(20, 400, 200, 34)];
[#"Navigate to Page3" drawInRect:CGRectMake(20, 400, 200, 34) withAttributes:attributes];
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
[#"Page 2" drawInRect:CGRectMake(20, 100, 200, 34)withAttributes:attributes];
[self drawTextLink2:#"NavigateToPage1" inFrame:CGRectMake(20, 400, 200, 34)];
UIGraphicsAddPDFContextDestinationAtPoint(#"NavigateToPage2", CGPointMake(0, 0));
[#"Navigate to Page1" drawInRect:CGRectMake(20, 400, 200, 34) withAttributes:attributes];
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
[#"Page3" drawInRect:CGRectMake(20, 100, 200, 34) withAttributes:attributes];
[#"Navigate to Page2" drawInRect:CGRectMake(20, 400, 200, 34) withAttributes:attributes];
UIGraphicsAddPDFContextDestinationAtPoint(#"NavigateToPage3", CGPointMake(0, 0));
[self drawTextLink2:#"NavigateToPage2" inFrame:CGRectMake(20, 400, 200, 34)];
UIGraphicsEndPDFContext();
[self showPDFFile];
}
- (void) drawTextLink:(NSString *) text inFrame:(CGRect) frameRect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform ctm = CGContextGetCTM(context);
// Translate the origin to the bottom left.
// Notice that 842 is the size of the PDF page.
CGAffineTransformTranslate(ctm, 0.0, 842);
// Flip the handedness of the coordinate system back to right handed.
CGAffineTransformScale(ctm, 1.0, -1.0);
// Convert the update rectangle to the new coordiante system.
CGRect xformRect = CGRectApplyAffineTransform(frameRect, ctm);
NSLog(#"xformrect is %#",NSStringFromCGRect(xformRect));
NSURL *url = [NSURL URLWithString:text];
UIGraphicsSetPDFContextURLForRect( url, xformRect );
CGContextSaveGState(context);
NSDictionary *attributesDict;
NSMutableAttributedString *attString;
NSNumber *underline = [NSNumber numberWithInt:NSUnderlineStyleSingle];
attributesDict = #{NSUnderlineStyleAttributeName : underline, NSForegroundColorAttributeName : [UIColor blueColor]};
attString = [[NSMutableAttributedString alloc] initWithString:url.absoluteString attributes:attributesDict];
[attString drawInRect:frameRect];
CGContextRestoreGState(context);
}
- (void) drawTextLink2:(NSString *) text inFrame:(CGRect) frameRect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform ctm = CGContextGetCTM(context);
// Translate the origin to the bottom left.
// Notice that 842 is the size of the PDF page.
CGAffineTransformTranslate(ctm, 0.0, 842);
// Flip the handedness of the coordinate system back to right handed.
CGAffineTransformScale(ctm, 1.0, -1.0);
// Convert the update rectangle to the new coordiante system.
CGRect xformRect = CGRectApplyAffineTransform(frameRect, ctm);
// NSURL *url = [NSURL URLWithString:text];
UIGraphicsSetPDFContextDestinationForRect(text, xformRect);
NSLog(#"xfrom rect is %#",NSStringFromCGRect(xformRect));
// UIGraphicsAddPDFContextDestinationAtPoint(text, CGPointMake(0,0));
// UIGraphicsSetPDFContextURLForRect( url, xformRect );
CGContextSaveGState(context);
NSDictionary *attributesDict;
NSMutableAttributedString *attString;
NSNumber *underline = [NSNumber numberWithInt:NSUnderlineStyleSingle];
attributesDict = #{NSUnderlineStyleAttributeName : underline, NSForegroundColorAttributeName : [UIColor blueColor]};
attString = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDict];
[attString drawInRect:frameRect];
CGContextRestoreGState(context);
}
-(void)showPDFFile
{
NSString* fileName = #"mypdf.pdf";
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *path = [arrayPaths objectAtIndex:0];
NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
NSURL *url = [NSURL fileURLWithPath:pdfFileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
webView.delegate=self;
[webView loadRequest:request];
[self.view addSubview:webView];
}

Resources