How to set text on uiimage center? - ios

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];
}

Related

How to get CALayer to be clear?

I have this code that returns a CATextLayer to place over a video and it is returning blurry text. I have searched online and most people recommended adding textLayer.contentsScale but this did not work for me.
- (CATextLayer *)buildTextLayerWithText:(NSString *)text atPosition:(WatermarkPosition)position forVideoSize:(CGSize)videoSize
{
CATextLayer *textLayer = [[CATextLayer alloc] init];
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
CGFloat fontSize = videoSize.height / 20.0;
[attributes setObject:(__bridge id)(__bridge CFTypeRef)([ChannelsInterface mediumFontOfSize:fontSize]) forKey:(NSString*)kCTFontAttributeName];
[attributes setObject:(__bridge id)[[UIColor whiteColor] CGColor] forKey:(NSString*)kCTForegroundColorAttributeName];
[attributes setObject:[NSNumber numberWithFloat:fontSize] forKey:(NSString*)kCTFontSizeAttribute];;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text attributes:attributes];
textLayer.string = attributedString;
CGSize textLayerSize = [text sizeWithAttributes:attributes];
textLayer.contentsScale = [UIScreen mainScreen].scale;
[textLayer setFrame:getFrameForPosition(textLayerSize, videoSize, position)];
textLayer.shadowColor = [UIColor blackColor].CGColor;
textLayer.shadowRadius = 1.0f;
textLayer.shadowOpacity = 0.5f;
textLayer.shadowOffset = CGSizeMake(0.0f, 0.0f);
[textLayer setRasterizationScale:[UIScreen mainScreen].scale];
[textLayer setShouldRasterize:YES];
return textLayer;
}

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];
}

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

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;}

How do I make a multiple page PDF from a textView?

I generated a PDF file from my iPhone app and while most of the documents are only one page, I want to be able detect if the text is going to go outside of the "margins" and if so, add it to the next page. I am new to this so not really sure how to do this.
Below is the code. Any suggestions?
- (void) drawBorder
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
UIColor *borderColor = [UIColor grayColor];
CGRect rectFrame = CGRectMake(kBorderInset, kBorderInset, pageSize.width-kBorderInset*2, pageSize.height-kBorderInset*2);
CGContextSetStrokeColorWithColor(currentContext, borderColor.CGColor);
CGContextSetLineWidth(currentContext, kBorderWidth);
CGContextStrokeRect(currentContext, rectFrame);
}
- (void)drawPageNumber:(NSInteger)pageNumber
{
NSString* pageNumberString = [NSString stringWithFormat:#"Page %d", pageNumber];
UIFont* theFont = [UIFont systemFontOfSize:12];
CGSize pageNumberStringSize = [pageNumberString sizeWithFont:theFont
constrainedToSize:pageSize
lineBreakMode:UILineBreakModeWordWrap];
CGRect stringRenderingRect = CGRectMake(kBorderInset,
pageSize.height - 40.0,
pageSize.width - 2*kBorderInset,
pageNumberStringSize.height);
[pageNumberString drawInRect:stringRenderingRect withFont:theFont lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentCenter];
}
- (void) drawHeader:(NSString *)header
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);
NSString *textToDraw = header;
UIFont *font = [UIFont systemFontOfSize:24.0];
CGSize stringSize = [textToDraw sizeWithFont:font constrainedToSize:CGSizeMake(pageSize.width - 2*kBorderInset-2*kMarginInset, pageSize.height - 2*kBorderInset - 2*kMarginInset) lineBreakMode:UILineBreakModeWordWrap];
CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);
[textToDraw drawInRect:renderingRect withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
}
- (void) drawText:(NSString *)bodyText
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);
NSString *textToDraw = bodyText;
UIFont *font = [UIFont systemFontOfSize:14.0];
CGSize stringSize = [textToDraw sizeWithFont:font
constrainedToSize:CGSizeMake(pageSize.width - 2*kBorderInset-2*kMarginInset, pageSize.height - 2*kBorderInset - 2*kMarginInset)
lineBreakMode:UILineBreakModeWordWrap];
CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 50.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);
[textToDraw drawInRect:renderingRect
withFont:font
lineBreakMode:UILineBreakModeWordWrap
alignment:UITextAlignmentLeft];
}
- (void) drawLine
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(currentContext, kLineWidth);
CGContextSetStrokeColorWithColor(currentContext, [UIColor blackColor].CGColor);
CGPoint startPoint = CGPointMake(kMarginInset + kBorderInset, kMarginInset + kBorderInset + 40.0);
CGPoint endPoint = CGPointMake(pageSize.width - 2*kMarginInset -2*kBorderInset, kMarginInset + kBorderInset + 40.0);
CGContextBeginPath(currentContext);
CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y);
CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y);
CGContextClosePath(currentContext);
CGContextDrawPath(currentContext, kCGPathFillStroke);
}
- (void) drawImage:(UIImage *)image
{
//UIImage * demoImage = [UIImage imageNamed:#"demo.png"];
[image drawInRect:CGRectMake( (pageSize.width - image.size.width/2)/2, 350, image.size.width/2, image.size.height/2)];
}
- (void) generatePdf: (NSString *)thefilePath :(NSString *) theHeader :(NSString *) theText :(UIImage *) theImage
{
pageSize = CGSizeMake(612, 792);
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
NSInteger currentPage = 0;
BOOL done = NO;
do
{
//Start a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
//Draw a page number at the bottom of each page.
currentPage++;
[self drawPageNumber:currentPage];
//Draw a border for each page.
[self drawBorder];
//Draw text fo our header.
[self drawHeader:theHeader];
//Draw a line below the header.
[self drawLine];
//Draw some text for the page.
[self drawText:theText];
//Draw an image
[self drawImage:theImage];
done = YES;
}
while (!done);
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)generatePdfWithFileName:(id)sender
{
pageSize = CGSizeMake(612, 792);
NSString *fileName = #"test.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
NSString *header = #"This is the bad ass header section!";
NSString *text = #"There is so much to say here I don't know where to begin....";
[self generatePdf : pdfFileName : header:text:nil];
}
#end
The concept can be seen here
[from http://spitzkoff.com/craig/?p=160]
When placing items, get the Height:
CGSize size = [name sizeWithFont:studentNameFont forWidth:maxWidth lineBreakMode:UILineBreakModeWordWrap];
[name drawAtPoint:CGPointMake(kMargin, currentPageY) forWidth:maxWidth withFont:studentNameFont lineBreakMode:UILineBreakModeWordWrap];
currentPageY += size.height;
At appropriate points, check the currentY and decide if you need to move to a new page:
if (size.height + currentPageY > maxHeight) {
// create a new page and reset the current page's Y value
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
currentPageY = kMargin;
}
I hope that helps.
I'm new to stackoverflow but I would like to suggest a brief answer to the "break into parts a long text view" problem.
The method I use is surely not the most efficient way to break a text into parts but it's the only way i found and it works.
Taking a part of a text, i just check in a loop, before drawing, word by word if the sub-text fit in my page, meaning height permitted. If the whole text doesn't fit then my code will only draw the part found. For instance, I could break a long text into four pages..., at least.
Sorry for my lack of experience and if my answer, that is just a glimpse, an idea of "how to", is not clear enough.
To clarify my answer. I added the method I use to check the height needed (found) for a "sub-text" (checking every time with a word added to the "sub-text"). Because "sizeWithFont:" is deprecated since IOS 7, I use "boundingRectWithSize:" method.
// Process, that can take long though, to find the next start of the part of a text that hasn't been drawned yet.
float widthRect;
widthRect = pageWidth - 2 * leftMargin;
- (unsigned int) findNextStartingPos:(NSString *)text withHeight:(float) height
{
NSString *character;
unsigned int pos = 0;
unsigned int posFound = 0;
unsigned int lastPosFound = 0;
BOOL found = NO;
NSString *textTest;
float heightFound;
while (pos <= [text length]-1)
{
character = [text substringWithRange:NSMakeRange(pos, 1)];
if ([character isEqualToString:#" "] || [character isEqualToString:#"\n"])
{
posFound = pos;
found = YES;
}
if (found)
{
textTest = [text substringWithRange:NSMakeRange(0, posFound)];
heightFound = lroundf([self heightFound:textTest withWidth:widthRect fontSize:fontSizeBody center:NO]);
if (heightFound > height)
{
if (lastPosFound == 0)
{
posFound = lastPosFound;
} else
{
posFound = lastPosFound + 1;
}
if (posFound > [text length]-1) posFound = lastPosFound;
break;
}
lastPosFound = posFound;
}
pos++;
}
return posFound;
} return posFound;
}
// Returns the height needed to draw a text (and to check for space in a page)
-(float) heightFound:(NSString *)text withWidth:(float)width fontSize:(CGFloat)fontSize center:(BOOL)center
{
if ([text length] != 0)
{
UIFont *font = [UIFont fontWithName:#"Helvetica" size:fontSize];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
if (center)
{
paragraphStyle.alignment = NSTextAlignmentCenter;
} else {
paragraphStyle.alignment = NSTextAlignmentLeft;
}
NSDictionary *attributes = #{NSFontAttributeName:font, NSParagraphStyleAttributeName: paragraphStyle};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text attributes:attributes];
CGRect newRect = [attributedString boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil];
return newRect.size.height;
} else {
return 0;
}
}

Resources