Create multi page PDF in objective-c - iphone

I am trying to create a multipage PDF. I have followed this tutorial.
This is working with a XIB file for static text and then adds a table from code. But the problem I'm having ATM is that when the table is bigger then one page. When the table has more then 9 rows. It should continue on the next page.
This is what I'm doing in code.
+(void)drawPDF:(NSString*)fileName
{
NSMutableDictionary *mutDictValues = [[[NSUserDefaults standardUserDefaults] objectForKey:#"dicValues"] mutableCopy];
NSMutableArray *arrSelectedCities = [[mutDictValues objectForKey:#"cities"]mutableCopy ];
if(arrSelectedCities.count <= 8){
// If there are only 8 rows --> we can fit everyting on one page !
// Create the PDF context using the default page size of 612 x 792.
UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
[self drawLabels];
[self drawLogo];
int xOrigin = 50;
int yOrigin = 350;
int rowHeight = 50;
int columnWidth = 240;
int numberOfRows = 9;
int numberOfColumns = 2;
[self drawTableAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns];
[self drawTableDataAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns withArray:arrSelectedCities];
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();
}else{
// When we have more then 8 rows we should have 2 pages.
NSLog(#"Create 2 pages");
// Create the PDF context using the default page size of 612 x 792.
UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
[self drawLabels];
[self drawLogo];
int xOrigin = 50;
int yOrigin = 350;
int rowHeight = 50;
int columnWidth = 240;
int numberOfRows = 9;
int numberOfColumns = 2;
[self drawTableAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns];
[self drawTableDataAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns withArray:arrSelectedCities];
// Create the PDF context using the default page size of 612 x 792.
UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
int xOrigin2 = 50;
int yOrigin2 = 60;
int numberOfRows2 = ((arrSelectedCities.count+1)-9);
[self drawTableAt:CGPointMake(xOrigin2, yOrigin2) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows2 andColumnCount:numberOfColumns];
[self drawTableDataAt:CGPointMake(xOrigin2, yOrigin2) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows2 andColumnCount:numberOfColumns withArray:arrSelectedCities];
}
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();
}
Let me explain what I'm doing here. I have an array that should fill up my tableview. If the array is bigger then 8 then I should use 2 pages. Else everything works with one page.
What this does is, it's creating only the second page....
Can anybody help me?

You should not call UIGraphicsBeginPDFContextToFile() again when creating the second page,
only UIGraphicsBeginPDFPageWithInfo():
UIGraphicsBeginPDFContextToFile(...);
UIGraphicsBeginPDFPageWithInfo(...); // start first page
// ...
UIGraphicsBeginPDFPageWithInfo(...); // start second page
// ...
UIGraphicsEndPDFContext();

NSArray *imageArray = [NSArray arrayWithObjects:[UIImage imageNamed:#"3.png"], [UIImage imageNamed:#"4.png"], [UIImage imageNamed:#"5.png"], [UIImage imageNamed:#"3.png"], nil];
NSMutableData *pdfFile = [[NSMutableData alloc] init];
double pageWidth = 0.0;
double pageHeight = 0.0;
UIImage *image;
for (int i = 0; i < [imageArray count]; i++)
{
image =[UIImage imageWithCGImage:[imageArray[i] CGImage]];
pageWidth = pageWidth + image.size.width ;
pageHeight = pageHeight + image.size.height;
}
image =[UIImage imageWithCGImage:[imageArray[0] CGImage]];
CGRect rect;
rect = CGRectMake(0, 0,image.size.width ,image.size.height);
UIGraphicsBeginPDFContextToData(pdfFile, CGRectZero, nil);
for (int i = 0; i < [imageArray count] ; i++)
{
UIGraphicsBeginPDFPageWithInfo(rect, nil);
UIImage *contextImage = imageArray[i];
[contextImage drawInRect:rect];
}
UIGraphicsEndPDFContext();
// save PDF file
NSString *saveFileName = [NSString stringWithFormat:#"%#%fx%f.pdf", #"test", pageWidth, pageHeight];
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* savePath = [documentDirectory stringByAppendingPathComponent:saveFileName];
if([[NSFileManager defaultManager] fileExistsAtPath:savePath])
{
[[NSFileManager defaultManager] removeItemAtPath:savePath error:nil];
}
[pdfFile writeToFile: savePath atomically: YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"PDF File created and saved successfully." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];

You don't need to create context for second page (UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil)), you have to only create this page.
You should also remember about closing opened page using CGPDFContextEndPage().

- (void)viewDidLoad {
[super viewDidLoad];
[self createPDF];
}
- (void)createPDF {
[self setupPDFDocumentNamed:#"myPdf" Width:850 Height:1100];
[self beginPDFPage];
}
- (void)beginPDFPage {
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
// kPadding will make 20 points margin on both sides of pdf
CGRect textRect = [self addText:#"Line Text Testing" withFrame:CGRectMake(PdfPadding, PdfPadding, 400, 200) fontSize:48.0f];
textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height +PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor blueColor]];
UIImage *anImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://www.phantompeer.com/sitefiles/osx.png"]]];
textRect = [self addImage:anImage atPoint:CGPointMake((pageSize.width/2)-(anImage.size.width/2),textRect.origin.y + textRect.size.height + PdfPadding)];
textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height + PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor redColor]];
textRect = [self addText:#"Line Text Testing" withFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height + PdfPadding, 400, 200) fontSize:48.0f];
textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height +PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor blueColor]];
anImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://www.w3schools.com/css/img_fjords.jpg"]]];
textRect = [self addImage:anImage atPoint:CGPointMake((pageSize.width/2)-(anImage.size.width/2),textRect.origin.y + textRect.size.height + PdfPadding)];
textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height + PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor redColor]];
UIGraphicsEndPDFContext();
[self loadRemotePdf];
}
-(CGRect)addText:(NSString*)text withFrame:(CGRect)frame fontSize:(float)fontSize {
UIFont *font = [UIFont systemFontOfSize:fontSize];
CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(pageSize.width - 2*20-2*20, pageSize.height - 2*20 - 2*20) lineBreakMode:UILineBreakModeWordWrap];
if((frame.origin.y + stringSize.height + PdfPadding) > pageSize.height) {
frame = CGRectMake(frame.origin.x, PdfPadding, frame.size.width, frame.size.height);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
}
float textWidth = frame.size.width;
if (textWidth < stringSize.width)
textWidth = stringSize.width;
if (textWidth > pageSize.width)
textWidth = pageSize.width - frame.origin.x;
CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);
[text drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];
frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);
return frame;
}
-(CGRect)addLineWithFrame:(CGRect)frame withColor:(UIColor*)color {
if((frame.origin.y + frame.size.height+PdfPadding) > pageSize.height) {
frame = CGRectMake(frame.origin.x, PdfPadding, frame.size.width, frame.size.height);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
}
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(currentContext, color.CGColor);
// this is the thickness of the line
CGContextSetLineWidth(currentContext, frame.size.height);
CGPoint startPoint = frame.origin;
CGPoint endPoint = CGPointMake(frame.origin.x + frame.size.width, frame.origin.y);
CGContextBeginPath(currentContext);
CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y);
CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y);
CGContextClosePath(currentContext);
CGContextDrawPath(currentContext, kCGPathFillStroke);
return frame;
}
-(CGRect)addImage:(UIImage*)image atPoint:(CGPoint)point {
CGRect imageFrame = CGRectMake(point.x, point.y, image.size.width, image.size.height);
if((imageFrame.origin.y + imageFrame.size.height + PdfPadding) > pageSize.height) {
imageFrame = CGRectMake(imageFrame.origin.x, PdfPadding, imageFrame.size.width, imageFrame.size.height);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
}
[image drawInRect:imageFrame];
return imageFrame;
}
- (void) loadRemotePdf
{
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
NSString *newPDFName = [NSString stringWithFormat:#"myPdf.pdf"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
UIWebView *myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
myWebView.autoresizesSubviews = YES;
myWebView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
NSURL *myUrl = [NSURL fileURLWithPath:pdfPath];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
[myWebView loadRequest:myRequest];
[self.view addSubview: myWebView];
}
For creating new page in the pdf, use
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);

Related

MapKit route over custom pin & callout

I have customized pins in my mapview with custom callout.
While drawing path on map, the route is coming over callout & pins. Image Attached.
I have used google API to get polylines and drawing it after decoding it.
Here is the code:
if(!routeView)
routeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.mapView.frame.origin.y, mapView.frame.size.width, self.mapView.frame.size.height)];
routeView.userInteractionEnabled = NO;
[mapView addSubview:routeView];
[self.lat1 resignFirstResponder];
[self.long1 resignFirstResponder];
[self.lat2 resignFirstResponder];
[self.long2 resignFirstResponder];
NSString* saddr = [NSString stringWithFormat:#"%#,%#",self.lat1.text,self.long1.text];
NSString* daddr = [NSString stringWithFormat:#"%#,%#",self.lat2.text,self.long2.text];
NSString* apiUrlStr = [NSString stringWithFormat:#"http://maps.apple.com/maps/api/directions/json?origin=%#&destination=%#&sensor=false", saddr, daddr];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSError *error;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:&error];
NSData *responseData = [apiResponse dataUsingEncoding:NSUTF8StringEncoding];
NSError* error1;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:&error1];
NSLog(#"Error: %#\n%#",[error1 localizedDescription],[error1 localizedFailureReason]);
if([[json objectForKey:#"status"] isEqualToString:#"OK"])
{
NSArray *routes1 = [json objectForKey:#"routes"];
NSDictionary *route = [routes1 lastObject];
if (route)
{
NSString *overviewPolyline = [[route objectForKey: #"overview_polyline"] objectForKey:#"points"];
routes = [self decodePolyLine:overviewPolyline];
//NSLog(#"%#",[routes objectAtIndex:0]);
[self updateRouteView];
[self centerMap];
}
}
-(void) updateRouteView
{
CGContextRef context = CGBitmapContextCreate(nil,
routeView.frame.size.width,
routeView.frame.size.height,
8,
4 * routeView.frame.size.width,
CGColorSpaceCreateDeviceRGB(),
kCGImageAlphaPremultipliedLast);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
CGContextSetLineWidth(context, 3.0);
for(int i = 0; i < routes.count; i++) {
CLLocation* location = [routes objectAtIndex:i];
CGPoint point = [mapView convertCoordinate:location.coordinate toPointToView:routeView];
if(i == 0) {
CGContextMoveToPoint(context, point.x, routeView.frame.size.height - point.y);
} else {
CGContextAddLineToPoint(context, point.x, routeView.frame.size.height - point.y);
}
}
CGContextStrokePath(context);
CGImageRef image = CGBitmapContextCreateImage(context);
UIImage* img = [UIImage imageWithCGImage:image];
routeView.image = img;
CGContextRelease(context);
}
I think your problem is that you add your routeView after adding your pin, so the routeview is the first subview. What happens if you try to add the routeView first, in your viewDidLoad method for example ?
Thanks for the responses. I have figure this out using MKPolylines. Refer code below
NSInteger numberOfSteps = routes.count;
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [routes objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coordinates[index] = coordinate;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[self.mapView addOverlay:polyLine];

scrolling image in UIScrollView in iphone

i m working one app .in this random number of time image is scroll..and then stop the image..here in my code first random number is generate which is store in n..for eg. random no is generate 12 then 12 times image is scroll after that it stop..
- (void)viewDidLoad
{
int n = 1 + arc4random() % 10 + 10;
NSString *string = [NSString stringWithFormat:#"%i",n];
//lbl.text = string;
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
// [kNumImages addObject:[NSNumber numberWithInt:i]];
NSString *imageName = [NSString stringWithFormat:#"%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i;
lbl.text = string;
[FirstScrollView addSubview:imageView];
[imageView release];
if(n == i){
break;
}
}
i want to stop scrolling when random no is match means n == i how can i do that ?
try this,
- (void)viewDidLoad
{
int n = 1 + arc4random() % 10 + 10;
NSString *string = [NSString stringWithFormat:#"%i",n];
//lbl.text = string;
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
if(n == i)
break;
else {
// [kNumImages addObject:[NSNumber numberWithInt:i]];
NSString *imageName = [NSString stringWithFormat:#"%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i;
lbl.text = string;
[FirstScrollView addSubview:imageView];
[imageView release];
}
}
}
[firstScrollView setContentOffset:CGRectMake(n*firstScrollView.frame.size.width,firstScrollView.frame.size.height)];
All you need is to set content offset of your scrollView.

iOS Printing with image and text

I am trying to print an image and some text above it. When I print the image it takes up the entire page I only want it in the center and about 320 x 480 pix. Someone told me I needed to use rects but I do not know how to do this. The code below is what I have so far, it just prints the image but it has no size constraints. Thank You.
-(void)sendToPrinter{
UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];
if(!print){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Print Unavailable!" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
pageSize = print.printPaper.paperSize;
pageSize = CGSizeMake(print.printFormatter.printPageRenderer.printableRect.size.width, print.printFormatter.printPageRenderer.printableRect.size.height);
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *projectTitle = [data stringForKey:#"pName1"];
NSString *fileName = [NSString stringWithFormat:#"%#.pdf", projectTitle];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *finalImageData = [NSData dataWithContentsOfFile:pdfFileName];
print.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [[(PageView *)[self view] representedPage] title];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
print.printInfo = printInfo;
print.showsPageRange = YES;
print.printingItem = finalImageData;
UIViewPrintFormatter *viewFormatter = [self.view viewPrintFormatter];
viewFormatter.startPage = 0;
print.printFormatter = viewFormatter;
UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {
if(!completed && error){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Print Unavailable!" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
};
[print presentAnimated:YES completionHandler:completionHandler];
}
- (void) drawText{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);
NSString *textToDraw = #"Lorem ipsum ";
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 + 350.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);
[textToDraw drawInRect:renderingRect
withFont:font
lineBreakMode:UILineBreakModeWordWrap
alignment:UITextAlignmentLeft];
}
- (void) drawImage{
//paint chart
UIImage* chartImage = [self getUIImageScreenShot];;
[chartImage drawInRect:CGRectMake( (pageSize.width - chartImage.size.width/2)/2, 70, chartImage.size.width/2, chartImage.size.height/2)];
//[chartImage drawInRect:CGRectMake( (pageSize.width - chartImage.size.width/2)/2, 70, chartImage.size.width/2, chartImage.size.height/2)];}
}
- (void) generatePdfWithFilePath: (NSString *)thefilePath{
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 some text for the page.
[self drawText];
//Draw an image
[self drawImage];
done = YES;
}
while (!done);
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();}
seems like you are only adding the picture to the printing item
print.printingItem = imageData;
have you tried creating the whole "picture" of what you want printed out (including the text and stuff) and sending that to the printer instead?
I use the following to insert a simple image into and text into PDF, might point you in the right direction
- (IBAction)generatePdfButtonPressed:(id)sender{
pageSize = CGSizeMake(612, 792);
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *projectTitle = [data stringForKey:#"pName1"];
NSString *fileName = [NSString stringWithFormat:#"%#.pdf", projectTitle];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[self generatePdfWithFilePath:pdfFileName];}
and then...
- (void) drawText{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);
NSString *textToDraw = #"Lorem ipsum ";
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 + 350.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);
[textToDraw drawInRect:renderingRect
withFont:font
lineBreakMode:UILineBreakModeWordWrap
alignment:UITextAlignmentLeft];
}
- (void) drawImage{
//paint chart
NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:#"chartImageP1"];
UIImage* chartImage = [UIImage imageWithData:imageData];
[chartImageBack drawInRect:CGRectMake( (pageSize.width - chartImageBack.size.width/2)/2, 70, chartImageBack.size.width/2, chartImageBack.size.height/2)];
[chartImage drawInRect:CGRectMake( (pageSize.width - chartImage.size.width/2)/2, 70, chartImage.size.width/2, chartImage.size.height/2)];}
- (void) generatePdfWithFilePath: (NSString *)thefilePath{
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 some text for the page.
[self drawText];
//Draw an image
[self drawImage];
done = YES;
}
while (!done);
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();}

How to next image in scroll view by next button in iphone

I have image in scroll view it is loading images from the array i also want this that when i press nextbutton next image should appear I have done following code for loading images in scrollview i want to go prevoius and next image by button click when i click next button it doesw not show next image
-(void) loadNews{
NSURL*myurl=url;
myurl = [myurl stringByReplacingOccurrencesOfString:#"\n" withString:#""];
myurl = [myurl stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSURL*urlloaded= [[NSURL alloc]initWithString:myurl];
//NSURL*url= [[NSURL alloc]initWithString:#"http://localhost:8888/RowOne.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:urlloaded];
//Initialize the delegate.
RowTwoParser *parser = [[RowTwoParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
int k=0;
for (int i=0; i < [appDelegate.articles count]; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView*subView=[[UIView alloc ]initWithFrame:frame];
[self.scrollView addSubview:subView];
RowTwo*aRowTwo=[appDelegate.articles objectAtIndex:i];
CGRect mywebframe=CGRectMake(20, 60, 728, 800);
UIImageView*imageView=[[UIImageView alloc] initWithFrame:mywebframe];
NSString*thumb2=aRowTwo.image;
thumb2 = [thumb2 stringByReplacingOccurrencesOfString:#"\n" withString:#""];
thumb2 = [thumb2 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSURL *url = [NSURL URLWithString:thumb2];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *image2 = [[UIImage alloc] initWithData:data];
imageView.image =image2 ;
[subView addSubview:imageView];
k++;
}
//NSInteger numberofPages=10-j;
NSInteger numberofPages=[appDelegate.articles count];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * numberofPages, self.scrollView.frame.size.height);
CGRect frame;
//frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.x = self.scrollView.frame.size.width * myindex;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
[pageControl setNumberOfPages:numberofPages];
[pageControl setActivePageColor:[UIColor clearColor]];
[pageControl setInactivePageColor:[UIColor clearColor]];
}
Next Button Code
-(IBAction)nextButton{
for (int nextIndex=[pageControl currentPage]; nextIndex < [appDelegate.articles count]; nextIndex++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * nextIndex;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView*subView=[[UIView alloc ]initWithFrame:frame];
[self.scrollView addSubview:subView];
RowTwo*aRowTwo=[appDelegate.articles objectAtIndex:nextIndex];
CGRect mywebframe=CGRectMake(20, 60, 728, 800);
UIImageView*imageView=[[UIImageView alloc] initWithFrame:mywebframe];
NSString*thumb2=aRowTwo.image;
thumb2 = [thumb2 stringByReplacingOccurrencesOfString:#"\n" withString:#""];
thumb2 = [thumb2 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSURL *url = [NSURL URLWithString:thumb2];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *image2 = [[UIImage alloc] initWithData:data];
imageView.image =image2 ;
[subView addSubview:imageView];
// k+\
}
//NSInteger numberofPages=10-j;
NSInteger numberofPages=[appDelegate.articles count];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * numberofPages, self.scrollView.frame.size.height);
CGRect frame;
//frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.x = self.scrollView.frame.size.width * myindex;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
[pageControl setNumberOfPages:numberofPages];
[pageControl setActivePageColor:[UIColor clearColor]];
[pageControl setInactivePageColor:[UIColor clearColor]];
}
If they are in scroll view, you use
CGPoint offset = CGPointMake(xPositionToScroll, yPositionToScroll);
[self.scrollView setContentOffset:topOffset animated:YES];
To some specific point.

How to draw lines on a google maps

I want to draw lines over google maps, the lines may be straight or curve, but i want to draw lines such that they connect two points, that may be at any geographical locations.
Thanks.
GuruPrasad R Gujjar.
Here is the example code, please try with this.
EDIT:Also you have to download "RegexKitLite" header file and class file.
// This method will calculate the routes and return an array with point
-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t {
NSString* saddr = [NSString stringWithFormat:#"%f,%f", f.latitude, f.longitude];
NSString* daddr = [NSString stringWithFormat:#"%f,%f", t.latitude, t.longitude];
NSString* apiUrlStr = [NSString stringWithFormat:#"http://maps.google.com/maps?output=dragdir&saddr=%#&daddr=%#", saddr, daddr];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSLog(#"api url: %#", apiUrl);
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl];
NSString* encodedPoints = [apiResponse stringByMatching:#"points:\\\"([^\\\"]*)\\\"" capture:1L];
return [self decodePolyLine:[encodedPoints mutableCopy]];
}
-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
[encoded replaceOccurrencesOfString:#"\\\\" withString:#"\\"
options:NSLiteralSearch
range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
NSInteger lat=0;
NSInteger lng=0;
while (index = 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) = 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitude = [[[NSNumber alloc] initWithFloat:lat * 1e-5] autorelease];
NSNumber *longitude = [[[NSNumber alloc] initWithFloat:lng * 1e-5] autorelease];
printf("[%f,", [latitude doubleValue]);
printf("%f]", [longitude doubleValue]);
CLLocation *loc = [[[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] autorelease];
[array addObject:loc];
}
return array;
}
// This method will draw the route with array of points.
-(void) updateRouteView
{
CGContextRef context = CGBitmapContextCreate(nil,
routeView.frame.size.width,
routeView.frame.size.height,
8,
4 * routeView.frame.size.width,
CGColorSpaceCreateDeviceRGB(),
kCGImageAlphaPremultipliedLast);
CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
CGContextSetLineWidth(context, 3.0);
for(int i = 0; i &ls; routes.count; i++) {
CLLocation* location = [routes objectAtIndex:i];
CGPoint point = [map convertCoordinate:location.coordinate toPointToView:routeView];
if(i == 0) {
CGContextMoveToPoint(context, point.x, routeView.frame.size.height - point.y);
} else {
CGContextAddLineToPoint(context, point.x, routeView.frame.size.height - point.y);
}
}
CGContextStrokePath(context);
CGImageRef image = CGBitmapContextCreateImage(context);
UIImage* img = [UIImage imageWithCGImage:image];
routeView.image = img;
//[self.view addSubview:routeView];
CGContextRelease(context);
//29-07-10
CGContextRef context2 = CGBitmapContextCreate(nil,
routeView2.frame.size.width,
routeView2.frame.size.height,
8,
4 * routeView2.frame.size.width,
CGColorSpaceCreateDeviceRGB(),
kCGImageAlphaPremultipliedLast);
CGContextSetStrokeColorWithColor(context2, lineColor2.CGColor);
CGContextSetRGBFillColor(context2, 0.0, 0.0, 1.0, 1.0);
CGContextSetLineWidth(context2, 3.0);
for(int i = 0; i &ls; routes2.count; i++) {
CLLocation* location2 = [routes2 objectAtIndex:i];
CGPoint point2 = [map convertCoordinate:location2.coordinate toPointToView:routeView2];
if(i == 0) {
CGContextMoveToPoint(context2, point2.x, routeView2.frame.size.height - point2.y);
} else {
CGContextAddLineToPoint(context2, point2.x, routeView2.frame.size.height - point2.y);
}
}
CGContextStrokePath(context2);
CGImageRef image2 = CGBitmapContextCreateImage(context2);
UIImage* img2 = [UIImage imageWithCGImage:image2];
routeView2.image = img2;
//[self.view addSubview:routeView];
CGContextRelease(context2);
}
I think it will help you to complete your task.
Refer this Link1 and Link2. It might be helpful for you.
You'll need to use JavaScript and the Google Maps API - Key is free if I remember right.
Everything else here:
http://code.google.com/apis/maps/documentation/javascript/v2/overlays.html#Drawing_Polylines