I have a print button in my app. If I click the button it should print the screen.
My problem is if the screen has a scrollview and it has contents more than screen size. It should print the whole content of the screen. the printout may take 2 or 3 pages. Is there any sample code or project for print the screen not by taking photos or screen shots.
You need to convert your whole data into HTML format and use a WebView to display data. For taking printout from iPhone app, you need to create a Pdf file from your webview content then take print out of this pdf file. Here I am giving you sample code, its properly working in my app.
1) include QuartzCore framework and import "QuartzCore/QuartzCore.h" in ViewController.h file.
2) In ViewController.h file use following code
#interface ViewController : UIViewController<UIScrollViewDelegate, UIPrintInteractionControllerDelegate>
{
UIWebView *theWebView;
int imageName;
double webViewHeight;
}
-(void) takeSnapshot;
- (void) drawPdf;
-(void) printContent:(NSData *) data;
3) On viewDidLoad method use following code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *htmlString=#"<html><body><img src=\"blue.png\" alt=\"Blue Image\" /> <h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p><h1>Hi, himanshu mahajan</h1><p> I am from Vinove Software service</p></body></html>";
UIBarButtonItem *generate=[[UIBarButtonItem alloc] initWithTitle:#"Print" style:UIBarButtonItemStylePlain target:self action:#selector(printBtnPressed)];
[self.navigationItem setRightBarButtonItem:generate];
theWebView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)];
[theWebView loadHTMLString:htmlString baseURL:nil];
theWebView.scrollView.bounces=NO;
[self.view addSubview:theWebView];
imageName=0;
webViewHeight=0.0;
}
4) method definitions
-(void) printBtnPressed
{
[self takeSnapshot];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
NSString *filePath=[documentDir stringByAppendingPathComponent:#"Demo.pdf"];
NSData *data=[[NSData alloc] initWithContentsOfFile:filePath];
[self printContent:data];
}
-(void) takeSnapshot
{
webViewHeight=[[theWebView stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight;"] integerValue];
CGRect screenRect=theWebView.frame;
double currentWebViewHeight = webViewHeight;
while (currentWebViewHeight > 0)
{
imageName ++;
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, screenRect);
[theWebView.layer renderInContext:ctx];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png",imageName]];
if(currentWebViewHeight < 416)
{
CGRect lastImageRect = CGRectMake(0, 416 - currentWebViewHeight, theWebView.frame.size.width, currentWebViewHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([newImage CGImage], lastImageRect);
newImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
}
[UIImagePNGRepresentation(newImage) writeToFile:pngPath atomically:YES];
[theWebView stringByEvaluatingJavaScriptFromString:#"window.scrollBy(0,416);"];
currentWebViewHeight -= 416;
}
[self drawPdf];
}
- (void) drawPdf
{
CGSize pageSize = CGSizeMake(612, webViewHeight);
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
double currentHeight = 0.0;
for (int index = 1; index <= imageName ; index++)
{
NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png", index]];
UIImage *pngImage = [UIImage imageWithContentsOfFile:pngPath];
[pngImage drawInRect:CGRectMake(0, currentHeight, pageSize.width, pngImage.size.height)];
currentHeight += pngImage.size.height;
}
UIGraphicsEndPDFContext();
}
-(void) printContent:(NSData *) data
{
UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];
print.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
//printInfo.jobName = #"Information";
printInfo.duplex = UIPrintInfoDuplexLongEdge;
print.printInfo = printInfo;
print.showsPageRange = YES;
print.printingItem = data;
UIViewPrintFormatter *viewFormatter = [self.view viewPrintFormatter];
viewFormatter.startPage = 0;
print.printFormatter = viewFormatter;
UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {};
[print presentAnimated:YES completionHandler:completionHandler];
}
You can convert all data into HTML and print it,
- (void) didPressPrintExpenseButton {
UIPrintInteractionController *printController = [UIPrintInteractionController sharedPrintController];
printController.delegate = self;
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
if (!completed && error) NSLog(#"Print error: %#", error);
};
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = #"Expense";
printController.printInfo = printInfo;
UIMarkupTextPrintFormatter *htmlFormatter = [[UIMarkupTextPrintFormatter alloc]
initWithMarkupText:[self getHtmlInvoiceDescription]];
htmlFormatter.startPage = 0;
htmlFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0); // 1 inch margins
htmlFormatter.maximumContentWidth = 6 * 72.0;
printController.printFormatter = htmlFormatter;
[htmlFormatter release];
printController.showsPageRange = YES;
[printController presentAnimated:YES completionHandler:completionHandler];
}
- (NSString *) getHtmlInvoiceDescription {
NSMutableString *htmlString = [[NSMutableString alloc]init];
[htmlString appendString:#"<html> \n"];
[htmlString appendString:#"<body> \n"];
[htmlString appendString:#"<table border='0' cellpadding='5' width='100%' >\n"];
[htmlString appendString:#"<tr>\n"];
[htmlString appendFormat:#"<td style=\"width='50%%'\"> %# </td>", [self.addressString stringByReplacingOccurrencesOfString:#"\n" withString:#"<br>"]];
//TODO change the image url here
UIImage * image = [UIImage imageNamed:#"iTunesArtwork.png"];
NSData *data = UIImagePNGRepresentation(image);
NSString * dataString = [data base64EncodedString]; // Your own base 64 converter
[htmlString appendFormat:#"<td style=\"width='50%%'\" align=\"right\"> <img src=\"data:image/png;base64,%#\" width='%.0f' height='%.0f' > </td>", dataString,
verifyHeader.frame.size.height * image.size.width/image.size.height, verifyHeader.frame.size.height];
[htmlString appendString:#"\n</tr> \n </table>"];
[htmlString appendFormat:#"\n<h2> %# </h2>", NSLocalizedString(#"Expense", #"")];
[htmlString appendString:#"\n<table border='1' cellpadding='5' width='100%'>"];
[htmlString appendString:#"\n<tr>"];
[htmlString appendFormat:#"<td style=\"width='50%%' \"> %# </td>", NSLocalizedString(#"Date: ", #"")];
[htmlString appendFormat:#"<td width='50%%'> %# </td>", [self getFormattedDateString:self.expense.date]];
[htmlString appendString:#"</tr>"];
[htmlString appendString:#"\n<tr>"];
[htmlString appendFormat:#"<td> %# </td>", NSLocalizedString(#"Reference no: ", #"")];
[htmlString appendFormat:#"<td> %# </td>", self.expense.referenceNo];
[htmlString appendString:#"</tr>"];
[htmlString appendString:#"\n<tr>"];
[htmlString appendFormat:#"<td> %# </td>", NSLocalizedString(#"Customer name: ", #"")];
[htmlString appendFormat:#"<td> %# </td>", self.expense.customerName];
[htmlString appendString:#"</tr>"];
[htmlString appendString:#"\n<tr>"];
[htmlString appendFormat:#"<td> %# </td>", NSLocalizedString(#"Product description: ", #"")];
[htmlString appendFormat:#"<td> %# </td>", self.expense.productDescription];
[htmlString appendString:#"</tr>"];
[htmlString appendString:#"\n</table>"];
[htmlString appendString:#"\n</body> \n</html>"];
NSString * tempString = [NSString stringWithString:htmlString];
[htmlString release];
return tempString;
}
Also, there is a way to convert your info in PDF and then you can print that.
Find apple documentation iPhone print API guidelines.
It would be possible to take a screenshot programmatically, and print that. In that case you would just print the screenshot.
Related
I have three nsmutable array in ios. I have to print data as below example using printer , How should i do it?
example:--
0.5 1 10
1 10 11
2 5 22
3 4 6
For example these are arrays :
NSArray *arr = [NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6", nil];
NSArray *arr1 = [NSArray arrayWithObjects:#"17",#"27",#"37",#"47",#"57",#"67", nil];
NSArray *arr2 = [NSArray arrayWithObjects:#"171",#"271",#"371",#"471",#"571",#"671", nil];
Now get all data in NSString
NSMutableString *str = [NSMutableString string];
for (int i=0; i<[arr count]; i++)
{
str = [str stringByAppendingFormat:[NSString stringWithFormat:#"%# %# %#\n",[arr objectAtIndex:i],[arr1 objectAtIndex:i],[arr2 objectAtIndex:i]]];
}
NSLog(#"%#",str);
Use toPdfData method to get NSData to print.
NSData *data = [self toPdfData:str];
Add these method:
- (NSData *) toPdfData :(NSMutableString *)str
{
//calculate size
CGSize stringSize = [str sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320 , 999) lineBreakMode:UILineBreakModeWordWrap];
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0, 0, stringSize.width, stringSize.height), nil);
UIGraphicsBeginPDFPage();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[str drawInRect:CGRectMake(0, 0, stringSize.width, stringSize.height) withFont:[UIFont systemFontOfSize:15]];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
return pdfData;
}
EDIT : Now you have PDF Data and PDF file also store in NSDocument Directory so print using UIPrintInteractionController
You can use the UIPrintInteractionController for doing this.
Please check the below code:
NSMutableString *stringToPrint = [[NSMutableString alloc] initWithString:#""];
for(int i = 0;i<[array count];i++)
{
[stringToPrint appendFormat:#"%#",[array objectAtIndex:i]];
if(i%2 == 0)
{
[stringToPrint appendFormat:#"\n"];
}
else
{
[stringToPrint appendFormat:#"\t"];
}
}
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = #"Midhun";
pic.printInfo = printInfo;
UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc]
initWithText:stringToPrint];
textFormatter.startPage = 0;
textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0); // 1 inch margins
textFormatter.maximumContentWidth = 6 * 72.0;
pic.printFormatter = textFormatter;
pic.showsPageRange = YES;
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *printController, BOOL completed, NSError *error)
{
if (!completed && error)
{
NSLog(#"Printing could not complete because of error: %#", error);
}
};
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
[pic presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
}
else
{
[pic presentAnimated:YES completionHandler:completionHandler];
}
Please read Printing and Drawing in iOS for more details.
Use following code to traverse and print.
for (int i=0; i<[array count]; i++) {
NSLog(#"%#",[array objectAtIndex:i]);
}
I'm new to iPhone development, I have used UIImagePickerController to capture the image manually, but i want to capture the image automatically, Is it possible to do that.
please help me.
Thanks in advance
Try This. In this I have saved the screen shot in photos album
-(void)screenShotCapture
{
//-- Screen Capture --------------------------------------------------------------------//
UIImage *image = nil;
UIGraphicsBeginImageContext(loginBgImgVw.frame.size);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy hh:mm:ss"];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(375, 0, 600, 44)];
[label setText:dateToday];
NSString *fileNameStr = [NSString stringWithFormat:#"%#_Login_%#",providerIdStr,dateToday];
[label setText:fileNameStr];
label.backgroundColor = [UIColor clearColor];
[loginBgImgVw addSubview:label];
[formatter release];
loginBgImgVw.frame = CGRectMake(10, 0, 1006, 669);
[loginBgImgVw.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[label removeFromSuperview];
//=--
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSLog(#"path=--%#",paths);
NSString *dataPath = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *savedImagePath = [dataPath stringByAppendingPathComponent:#"Login_Provider.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.2);
if ([screenCapturNameAry count] != 0)
{
if ([screenCapturNameAry containsObject:#"Login"])
{
[imageData writeToFile:savedImagePath atomically:NO];
}
}
UIImageWriteToSavedPhotosAlbum([self loadImage:#"Login_Provider"],self,#selector(image:didFinishSavingWithError:contextInfo:),NULL);
//--------------------------------------------------------------------------------------//
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
if (error == nil)
{
NSLog(#"Login Image saved successfully.");
}
else
{
NSLog(#"Error occurred:%#",[error localizedDescription]);
}
}
You can get the saved image using following method
- (UIImage*)loadImage:(NSString*)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
NSString *fullPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",imageName]];
return [UIImage imageWithContentsOfFile:fullPath];
}
To take the screenshot you can use the following code.
UIGraphicsBeginImageContext(self.window.bounds.size);
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
[data writeToFile:#"screen.png" atomically:YES];
For Ratina display device you have to check:
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.window.bounds.size);
I want to display the image(which comes from webservice) the format such that the output in the screen appears like below image:-
Now the logic i had implemented is,i had added the image in uiscrollview.
with the below logic:-
for (int j=0;j<9;j++) {
for (int i=0; i<[mainRestaurantArray count];i++) {
if ([[[mainRestaurantArray objectAtIndex:i] valueForKey:#"Image"] isKindOfClass:[UIImage class]]) {
[CombineArray addObject:[mainRestaurantArray objectAtIndex:i]];
//NSLog(#"cnt=>%d array==>%#",cnt,[CombineArray objectAtIndex:cnt]);
UIButton* btn = [[UIButton alloc]init];
btn.tag = cnt;
btn.frame = CGRectMake(15+(cnt%5)*60, 15+(cnt/5)*60,Width,Height);
btn.backgroundColor = [UIColor greenColor];
[btn setBackgroundImage:[[CombineArray objectAtIndex:cnt] valueForKey:#"Image"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(Buttonclick:) forControlEvents:UIControlEventTouchUpInside];
[ScrlPhotos addSubview:btn];
[btn release];
cnt++;
}
}
[mainRestaurantArray release];
counter++;
[self urlcalled];//The function which calls the webservice
}
//}
ScrlPhotos.contentSize = CGSizeMake(320, ([CombineArray count]/5.0)*60+25);
The function which does the webservice is below:-
-(void)urlcalled{
#try
{
if (rangeDistance == nil) {
rangeDistance =#"100";
}
urlstring[0]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Gym&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[1]=[NSString stringWithFormat:#"http://www.google.com/maps?q=resort&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[2]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Tourist place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[3]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Hotels&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[4]=[NSString stringWithFormat:#"http://www.google.com/maps?q=shopping Mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[5]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Industries&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[6]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Shopping_mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[7]=[NSString stringWithFormat:#"http://www.google.com/maps?q=garden&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[8]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Religious Place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[9]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Restaurants&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
NSLog(#"conte==>%d urlstring[counter]==>%#",counter,urlstring[counter]);
NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlstring[counter]]];
str1 = [str substringFromIndex:9];
//NSLog(#"===>%#",str1);
NSArray *array = [str1 componentsSeparatedByString:#"overlays:"];
NSString *str2 = [array objectAtIndex:1];
NSString *finalUpperStr = [str2 substringFromIndex:21];
array1 = [finalUpperStr componentsSeparatedByString:#"},panel:"];
NSString *strF = [array1 objectAtIndex:0];
NSArray *arrayF = [strF componentsSeparatedByString:#"{id:"];
///////....................this object will change as require in for loop .............................//
mainRestaurantArray = [[NSMutableArray alloc] init];
for (int i=1; i<[arrayF count]-5; i++) {
NSString *strF12 = [arrayF objectAtIndex:i];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *aryF23 = [strF12 componentsSeparatedByString:#"latlng:{"];
//NSLog(#"%#",[aryF23 objectAtIndex:1]);
NSString *strF23 = [aryF23 objectAtIndex:1];
NSArray *ar = [strF23 componentsSeparatedByString:#"},image:"];
//NSLog(#"%#",[ar objectAtIndex:0]);
NSString *strLat = [ar objectAtIndex:0];
NSArray *arrayLat = [strLat componentsSeparatedByString:#","];
NSString *strFLat = [[arrayLat objectAtIndex:0] substringFromIndex:4];
NSString *strLong = [[arrayLat objectAtIndex:1] substringFromIndex:4];
//NSLog(#"Lati = %# Longi = %#" , strFLat , strLong);
[dic setValue:strFLat forKey:#"Latitude"];
[dic setValue:strLong forKey:#"Longitude"];
NSString *strLAdd = [ar objectAtIndex:1];
NSArray *arrayLAdd = [strLAdd componentsSeparatedByString:#"laddr:"];
//NSLog(#"%#",[arrayLAdd objectAtIndex:1]);
NSString *strLAdd1 = [arrayLAdd objectAtIndex:1];
NSArray *arrayLAdd1 = [strLAdd1 componentsSeparatedByString:#"geocode:"];
// NSLog(#"%#",[arrayLAdd1 objectAtIndex:0]);
NSString *strAddres = [[arrayLAdd1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
//NSLog(#"%#",strAddres);
[dic setValue:strAddres forKey:#"Address"];
NSString *strName = [arrayLAdd1 objectAtIndex:1];
NSArray *arrayName = [strName componentsSeparatedByString:#"name:"];
NSString *strName1 = [[arrayName objectAtIndex:1]stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *arrayName1 = [strName1 componentsSeparatedByString:#"infoWindow:"];
[dic setValue:[arrayName1 objectAtIndex:0] forKey:#"Name"];
// for image load .. 07Dec..
NSString *strImage= [arrayF objectAtIndex:i];
NSRange range = [strImage rangeOfString:#"photoUrl"];
if(range.location == NSNotFound){
NSLog(#"Not found");
[dic setValue:#"" forKey:#"Image"];
}else{
NSArray *arrayImage = [strImage componentsSeparatedByString:#"photoUrl:"];
NSString *strImage1 = [arrayImage objectAtIndex:1];
NSArray *arrayImage1 = [strImage1 componentsSeparatedByString:#",photoType:"];
NSString *strfindImage = [[arrayImage1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strfindImage]]];
[dic setValue:myImage forKey:#"Image"];
}
[mainRestaurantArray addObject:dic];
if (i==20) {
break;
}
}
}
#catch (NSException * e)
{
NSLog(#"NSException==>%#",e);
}
}
But the problem i am facing is the image is displayed after completing the loop at 10 times.
I want to display the image parallely as it comes from webservice,so that time taken should be less..
Is there any way out..
Please help me.
Use UIImageView+cacheWeb.. it makes lazy loading a lot easier
http://hackemist.com/SDWebImage/doc/Categories/UIImageView+WebCache.html
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();}
I attached a file to the mail I am using this code.
[mail addAttachmentData:[myView PDFData] mimeType:#"application/pdf" fileName:#"name.pdf"];
How can I do the same thing for printing a file, I need to print this [myView PDFData].
I found only this for printing:
NSString *PDFFileWithName = [[NSBundle mainBundle] pathForResource:#"name" ofType:#"pdf"];
NSData *dataFromPath = [NSData dataWithContentsOfFile:PDFFileWithName];
Thanks
You should read through the Drawing and Printing Guide for iOS. The printingItem property of UIPrintInteractionController can be set to the NSData of a PDF.
Update for added code
The value of dataFromPath should be equal to [myView PDFData] although I would recommend changing the variable name once you get it working.
NSData *dataFromPath = [myView PDFData];
Full code to print pdf
UIPrintInteractionController *pc = [UIPrintInteractionController
sharedPrintController];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.orientation = UIPrintInfoOrientationPortrait;
printInfo.jobName =#"Report";
pc.printInfo = printInfo;
pc.showsPageRange = YES;
pc.printingItem = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://test.com/Print_for_Client_Name.pdf"]];
// You can use here image or any data type to print.
UIPrintInteractionCompletionHandler completionHandler =
^(UIPrintInteractionController *printController, BOOL completed,
NSError *error) {
if(!completed && error){
NSLog(#"Print failed - domain: %# error code %ld", error.domain,
(long)error.code);
}
};
[pc presentFromRect:CGRectMake(0, 0, 300, 300) inView:self.view animated:YES completionHandler:completionHandler];
write below code and check it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathFolder = [NSString stringWithFormat:#"%#",pdfFileName];
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:pathFolder];
NSURL *targetURL = [NSURL fileURLWithPath:path];
UIPrintInteractionController *pc = [UIPrintInteractionController sharedPrintController];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.orientation = UIPrintInfoOrientationPortrait;
printInfo.jobName =#“Print”;
printInfo.duplex = UIPrintInfoDuplexLongEdge;
pc.printInfo = printInfo;
pc.showsPageRange = YES;
pc.printingItem = targetURL;
UIPrintInteractionCompletionHandler completionHandler =
^(UIPrintInteractionController *printController, BOOL completed,
NSError *error) {
if(!completed && error){
NSLog(#"Print failed - domain: %# error code %ld", error.domain, (long)error.code);
}
};
[pc presentFromRect:shareButton.frame inView:self.view animated:YES completionHandler:completionHandler];
Posted the wrong link earlier - this one should help!
Blog - Printing in iOS - Goes into great detail and includes a tutorial on Printing PDFs