iOS Printing with image and text - iphone

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

Related

print nsmutable array using printer in ios

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

Create multi page PDF in objective-c

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

Button deletes in array but not in View

I'm having trouble removing image in my scrollView, i put my images in UIScrollView then add button, when clicked will prompt an alert view asking if you want to delete it. When yes, deletes in my NSDocumentDirectory but not in my View. My images is from NSDocumentDirectory picked from an ImagePicker.
- (void)addImage:(UIImage *)image {
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
[self createScrollView];
}
- (void) createScrollView {
[scrollView setNeedsDisplay];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 75);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(300, (row+1) * 60 + 10)];
}
- (IBAction)buttonClicked:(id)sender {
_clickedButton = (UIButton *)sender;
UIAlertView *saveMessage = [[UIAlertView alloc] initWithTitle:#""
message:#"DELETE?"
delegate:self
cancelButtonTitle:#"NO"
otherButtonTitles:#"YES", nil];
[saveMessage show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"YES"]) {
UIButton *button = _clickedButton;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"images%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
- (void)viewDidLoad
{
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 310, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,130.0f)];
[slotBg addSubview:self.scrollView];
}
- (void)viewDidAppear:(BOOL)animated
{
[_thumbs removeAllObjects];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
}
You are calling createScrollView each time you add an image to your array. What it seems to be doing is creating buttons containing the same image on top of each other. Your code seems to be removing it from the view, but it looks like there are similar buttons just below it. So call createScrollView only after you've added all the images and remove it from your addImage:.
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
[self createScrollView];
//after deleting the image from document directory just call viewDidAppear again...
[self viewDidAppear:yes];
Hope this will help you...
set tag value to button.then get the button in the following function by
(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIButton *btn = (UIButton*)[scrollview viewWithTag:button.tag];
//your button tag
[btn removeFromSuperView];
}
try this method :
- (void)removeObjectWithTag:(int)objectTag
{
[_thumbs removeObjectAtIndex:objectTag];
for (UIView *view in scrollView.subviews)
{
[view removeFromSuperview];
}
scrollView.contentSize = CGSizeZero;
[self createScrollView];
}

Edit RTF/DOC file programmatically in xcode/ios

I have a RTF file which I can view on iphone , Now I need to edit the file programmatically , please let me know how can I do it.
Example
RTF file content
"I am new to StackOverflow"
Now I need to change to below line programmatically.
"I regularly visit StackOverflow" and save as PDF file.
Please do help me :)
Thanks in advance :)
In your .h file add some objects and defines
#define kBorderInset 20.0
#define kBorderWidth 1.0
#define kMarginInset 10.0
#interface ViewController : UIViewController
{
CGSize pageSize;
NSString *pdfFileName;
NSString *contents_for_pdf;
}
- (void)generatePdfWithFilePath:(NSString *)thefilePath;
in .m file add this lines some where on button click to get contents of rtf file in string
NSString *rtf_path = [[NSBundle mainBundle] pathForResource:#"example" ofType:#"rtf"];
contents_for_pdf = [[NSString alloc] initWithContentsOfFile:rtf_path encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#",contents_for_pdf);
contents_for_pdf = [contents_for_pdf stringByReplacingOccurrencesOfString:#"I am new to StackOverflow" withString:#"I regularly visit StackOverflow"];
pageSize = CGSizeMake(612, 792);
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[self generatePdfWithFilePath:pdfFileName];
I didnt modify the text of rtf file,I just used same text in rtf file.you should do as you want(I noticed some encoding characters in text) and function that will generate pdf is here.
- (void) generatePdfWithFilePath: (NSString *)thefilePath
{
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
//Start a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
//Draw text fo our header.
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);
UIFont *font = [UIFont systemFontOfSize:14.0];
CGSize stringSize = [contents_for_pdf 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);
[contents_for_pdf drawInRect:renderingRect
withFont:font
lineBreakMode:UILineBreakModeWordWrap
alignment:UITextAlignmentLeft];
UIGraphicsEndPDFContext();
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:#"PDF Created" message:#"Sucessfull" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[Alert show];
}

How to take printout from my iPhone app?

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.