I want functionality in which link should be generated in pdf file.When user clicks on that link it should be navigated to that file.For that i have used following code.It has generated the pdf but i am not able to genreate the link.How can i do that?
-(void)generatePDF
{
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString *pdfFileName = [documentDirectory stringByAppendingPathComponent:#"mypdf.pdf"];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
NSString *myString = #"My PDF Heading";
[myString drawInRect:CGRectMake(20, 100, 200, 34) withFont:[UIFont fontWithName:#"HelveticaNeue-Bold" size:13] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
UIGraphicsAddPDFContextDestinationAtPoint(#"Chapter1", CGPointMake(72, 72));
UIGraphicsSetPDFContextDestinationForRect(#"Chapter1", CGRectMake(72, 528, 400, 40));
UIGraphicsEndPDFContext();
[self showPDFFile];
}
Using following code i was able to generate links in pdf and navigate to other page in pdf
-(void)generatePDF
{
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
/// Set text alignment
paragraphStyle.alignment = NSTextAlignmentLeft;
NSDictionary *attributes = #{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue-Bold" size:13],NSParagraphStyleAttributeName:paragraphStyle};
NSDictionary *attributes2 = #{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue-Bold" size:13],NSParagraphStyleAttributeName:paragraphStyle,NSBackgroundColorAttributeName:[UIColor yellowColor]};
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString *pdfFileName = [documentDirectory stringByAppendingPathComponent:#"mypdf.pdf"];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
NSString *myString = #"Page1";
[myString drawInRect:CGRectMake(20, 100, 200, 34) withAttributes:attributes];
UIGraphicsAddPDFContextDestinationAtPoint(#"NavigateToPage1", CGPointMake(0, 0));
[self drawTextLink2:#"NavigateToPage3" inFrame:CGRectMake(20, 400, 200, 34)];
[#"Navigate to Page3" drawInRect:CGRectMake(20, 400, 200, 34) withAttributes:attributes];
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
[#"Page 2" drawInRect:CGRectMake(20, 100, 200, 34)withAttributes:attributes];
[self drawTextLink2:#"NavigateToPage1" inFrame:CGRectMake(20, 400, 200, 34)];
UIGraphicsAddPDFContextDestinationAtPoint(#"NavigateToPage2", CGPointMake(0, 0));
[#"Navigate to Page1" drawInRect:CGRectMake(20, 400, 200, 34) withAttributes:attributes];
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
[#"Page3" drawInRect:CGRectMake(20, 100, 200, 34) withAttributes:attributes];
[#"Navigate to Page2" drawInRect:CGRectMake(20, 400, 200, 34) withAttributes:attributes];
UIGraphicsAddPDFContextDestinationAtPoint(#"NavigateToPage3", CGPointMake(0, 0));
[self drawTextLink2:#"NavigateToPage2" inFrame:CGRectMake(20, 400, 200, 34)];
UIGraphicsEndPDFContext();
[self showPDFFile];
}
- (void) drawTextLink:(NSString *) text inFrame:(CGRect) frameRect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform ctm = CGContextGetCTM(context);
// Translate the origin to the bottom left.
// Notice that 842 is the size of the PDF page.
CGAffineTransformTranslate(ctm, 0.0, 842);
// Flip the handedness of the coordinate system back to right handed.
CGAffineTransformScale(ctm, 1.0, -1.0);
// Convert the update rectangle to the new coordiante system.
CGRect xformRect = CGRectApplyAffineTransform(frameRect, ctm);
NSLog(#"xformrect is %#",NSStringFromCGRect(xformRect));
NSURL *url = [NSURL URLWithString:text];
UIGraphicsSetPDFContextURLForRect( url, xformRect );
CGContextSaveGState(context);
NSDictionary *attributesDict;
NSMutableAttributedString *attString;
NSNumber *underline = [NSNumber numberWithInt:NSUnderlineStyleSingle];
attributesDict = #{NSUnderlineStyleAttributeName : underline, NSForegroundColorAttributeName : [UIColor blueColor]};
attString = [[NSMutableAttributedString alloc] initWithString:url.absoluteString attributes:attributesDict];
[attString drawInRect:frameRect];
CGContextRestoreGState(context);
}
- (void) drawTextLink2:(NSString *) text inFrame:(CGRect) frameRect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform ctm = CGContextGetCTM(context);
// Translate the origin to the bottom left.
// Notice that 842 is the size of the PDF page.
CGAffineTransformTranslate(ctm, 0.0, 842);
// Flip the handedness of the coordinate system back to right handed.
CGAffineTransformScale(ctm, 1.0, -1.0);
// Convert the update rectangle to the new coordiante system.
CGRect xformRect = CGRectApplyAffineTransform(frameRect, ctm);
// NSURL *url = [NSURL URLWithString:text];
UIGraphicsSetPDFContextDestinationForRect(text, xformRect);
NSLog(#"xfrom rect is %#",NSStringFromCGRect(xformRect));
// UIGraphicsAddPDFContextDestinationAtPoint(text, CGPointMake(0,0));
// UIGraphicsSetPDFContextURLForRect( url, xformRect );
CGContextSaveGState(context);
NSDictionary *attributesDict;
NSMutableAttributedString *attString;
NSNumber *underline = [NSNumber numberWithInt:NSUnderlineStyleSingle];
attributesDict = #{NSUnderlineStyleAttributeName : underline, NSForegroundColorAttributeName : [UIColor blueColor]};
attString = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDict];
[attString drawInRect:frameRect];
CGContextRestoreGState(context);
}
-(void)showPDFFile
{
NSString* fileName = #"mypdf.pdf";
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *path = [arrayPaths objectAtIndex:0];
NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
NSURL *url = [NSURL fileURLWithPath:pdfFileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
webView.delegate=self;
[webView loadRequest:request];
[self.view addSubview:webView];
}
Related
I am a new iOS developer. I want to complete create a PDF file but problem is that the PDF file does not save in device. When I open the PDF in click open button rather than than display, it is not stored in the original device.
Here is my code.
#import "MTViewController.h"
#define kPadding 20
#interface MTViewController ()
{
CGSize _pageSize;
}
#end
#implementation MTViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)didClickOpenPDF {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"NewPDF.pdf"];
if([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) {
ReaderDocument *document = [ReaderDocument withDocumentFilePath:pdfPath password:nil];
if (document != nil)
{
ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
readerViewController.delegate = self;
readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentModalViewController:readerViewController animated:YES];
}
}
}
- (IBAction)didClickMakePDF {
[self setupPDFDocumentNamed:#"NewPDF" Width:850 Height:1100];
[self beginPDFPage];
NSString *test=#"jigar";
NSString *test1=#"ravi";
CGRect textRect = [self addText:[NSString stringWithFormat:#"%#%#",test,test1]
withFrame:CGRectMake(kPadding, kPadding, 400, 200) fontSize:48.0f];
CGRect blueLineRect = [self addLineWithFrame:CGRectMake(kPadding, textRect.origin.y + textRect.size.height + kPadding, _pageSize.width - kPadding*2, 4)
withColor:[UIColor blueColor]];
UIImage *anImage = [UIImage imageNamed:#"tree.jpg"];
CGRect imageRect = [self addImage:anImage
atPoint:CGPointMake((_pageSize.width/2)-(anImage.size.width/2), blueLineRect.origin.y + blueLineRect.size.height + kPadding)];
[self addLineWithFrame:CGRectMake(kPadding, imageRect.origin.y + imageRect.size.height + kPadding, _pageSize.width - kPadding*2, 4)
withColor:[UIColor redColor]];
[self finishPDF];
}
- (void)setupPDFDocumentNamed:(NSString*)name Width:(float)width Height:(float)height {
_pageSize = CGSizeMake(width, height);
NSString *newPDFName = [NSString stringWithFormat:#"%#.pdf", name];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
// NSString *resourceDocPath = [[NSString alloc] initWithString:[
// [[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
// stringByAppendingPathComponent:#"Documents"]];
//
// NSString *filePath = [resourceDocPath
// stringByAppendingPathComponent:#"myPDF.pdf"];
// [newPDFName writeToFile:filePath atomically:YES];
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
}
- (void)beginPDFPage {
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, _pageSize.width, _pageSize.height), nil);
}
- (void)finishPDF {
UIGraphicsEndPDFContext();
}
- (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];
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:UILineBreakModeWordWrap
alignment:UITextAlignmentLeft];
frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);
return frame;
}
- (CGRect)addLineWithFrame:(CGRect)frame withColor:(UIColor*)color {
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);
[image drawInRect:imageFrame];
return imageFrame;
}
- (void)dismissReaderViewController:(ReaderViewController *)viewController {
[self dismissModalViewControllerAnimated:YES];
}
I'm converting a UIWebView to pdf/image with the help of the following code:
NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight;"];
int height = [heightStr intValue];
CGFloat screenHeight = webView.bounds.size.height;
int pages = ceil(height / screenHeight);
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil);
CGRect frame = [webView frame];
NSMutableArray *imageArray= [[NSMutableArray alloc]init];
for (int i = 0; i < pages; i++)
{
// Check to screenHeight if page draws more than the height of the UIWebView
if ((i+1) * screenHeight > height)
{
CGRect f = [webView frame];
f.size.height -= (((i+1) * screenHeight) - height);
[webView setFrame: f];
}
UIGraphicsBeginImageContext(frame.size);
UIGraphicsBeginPDFPage();
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins
[[[webView subviews] lastObject] setContentOffset:CGPointMake(0, screenHeight * i) animated:NO];
[webView.layer renderInContext:currentContext];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
[imageArray insertObject:viewImage atIndex:imageArray.count] ;
UIGraphicsEndImageContext();
}
UIGraphicsEndPDFContext();
[webView setFrame:frame];
//Send all images
NSData *imgData = [self blendImages:imageArray];
//Final Image
UIImage *finalImage = [UIImage imageWithData:imgData];
-(NSData*)blendImages:(NSMutableArray *)arrImage{
// get data from document
CGFloat height=0 ,width=0 ;
UIImage *tempImg = [arrImage objectAtIndex:0] ;
width =tempImg.size.width ;
for (int i = 0 ; i<arrImage.count ; i++){
UIImage *img= [arrImage objectAtIndex:i];
height = img.size.height +height;
}
CGSize size = CGSizeMake(width, height) ;
UIGraphicsBeginImageContext(size);
CGFloat h = 0;
for (int i=0; i<arrImage.count; i++) {
UIImage* uiimage = [arrImage objectAtIndex:i];
[uiimage drawAtPoint:CGPointMake(0, h) blendMode:kCGBlendModeNormal alpha:1.0];
h = uiimage.size.height +h ;
}
NSData *imageData = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext());
UIGraphicsEndImageContext();
return imageData;
}
But I'm getting only one inch wide output. Also the whole contains fits in one page and make it unreadable. How to make A4 sized output?
This creates a PDF of a screenshot of a webpage - might help get you started :)
- (IBAction)makePDF:(id)sender
{
UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize, webView.scrollView.opaque, 0.0);
webView.scrollView.contentOffset = CGPointZero;
webView.scrollView.frame = CGRectMake(0, 0, webView.scrollView.contentSize.width, webView.scrollView.contentSize.height);
[webView.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect imageFrame = CGRectMake(0, 0, image.size.width, image.size.height);
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, imageFrame, nil);
//full screenshot
UIGraphicsBeginPDFPage();
UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageFrame];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
[imageView setImage:image];
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndPDFContext();
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentDirectory = [documentDirectories objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#.pdf",[NSDate date]];
NSString *path = [documentDirectory stringByAppendingPathComponent:fileName];
// save to disk
[pdfData writeToFile:path atomically:YES];
NSLog(#"pdf in %#", path);
}
Today i searched a while for a way to programmatically pasting text in a PDF file in an iOS 7 app. Unfortunately there is no easy way to edit a PDF form. You can use a paid library but that was not an option for me. So i did it by pasting text at specified coordinates by using CGPDF.
This is the way i did it:
- (void)editPDF
{
NSString* fileName = #"new.pdf";
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *path = [arrayPaths objectAtIndex:0];
NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];
NSString *templatePath = [[NSBundle mainBundle] pathForResource:#"mytemplate" ofType:#"pdf"];
//create empty pdf file;
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectMake(0, 0, 792, 612), nil);
CFURLRef url = CFURLCreateWithFileSystemPath (NULL, (CFStringRef)templatePath, kCFURLPOSIXPathStyle, 0);
//open template file
CGPDFDocumentRef templateDocument = CGPDFDocumentCreateWithURL(url);
CFRelease(url);
//get amount of pages in template
size_t count = CGPDFDocumentGetNumberOfPages(templateDocument);
//for each page in template
for (size_t pageNumber = 1; pageNumber <= count; pageNumber++) {
//get bounds of template page
CGPDFPageRef templatePage = CGPDFDocumentGetPage(templateDocument, pageNumber);
CGRect templatePageBounds = CGPDFPageGetBoxRect(templatePage, kCGPDFCropBox);
//create empty page with corresponding bounds in new document
UIGraphicsBeginPDFPageWithInfo(templatePageBounds, nil);
CGContextRef context = UIGraphicsGetCurrentContext();
//flip context due to different origins
CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
//copy content of template page on the corresponding page in new file
CGContextDrawPDFPage(context, templatePage);
//flip context back
CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
//create dictionary for font
UIFont *font = [UIFont fontWithName: #"Courier" size:12];
NSDictionary *attribdict = [[NSDictionary alloc] initWithObjectsAndKeys: font, NSFontAttributeName, nil];
/* Here you can do any drawings */
[#"Test" drawAtPoint:CGPointMake(200, 300) withAttributes:attribdict];
}
CGPDFDocumentRelease(templateDocument);
UIGraphicsEndPDFContext();
[self showPDFFile];
}
-(void)showPDFFile
{
NSString* fileName = #"new.pdf";
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *path = [arrayPaths objectAtIndex:0];
NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
NSURL *url = [NSURL fileURLWithPath:pdfFileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[webView loadRequest:request];
[self.view addSubview:webView];
}
You only have to find out the CGPoint(s) of the point where you want to paste the text and paste a line for each text.
Very helpful was this link: how to edit a PDF in objective-c?
If anybody has a better solution for this i would appreciate if he/she can answer and post it.
im trying to first upload an image then write a text on it and after that save both items as one image.
im new in objective c so my code might be not the best way to get to my goal any help and suggestion wil help me.
thank you all
this is my code :
some how this editor is not allowing me to put my method declaration on
enter code here
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *data = UIImagePNGRepresentation(image);
NSString *mijnImage =#"mijnImage.png";
NSArray *route = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *imageRoute = [route objectAtIndex:0];
NSString *routeNaarDeBestaand = [imageRoute stringByAppendingPathComponent:mijnImage];
[data writeToFile:routeNaarDeBestaand atomically:YES];
[[self imageView]setImage:image];
[self dismissViewControllerAnimated:YES completion:Nil];
self.imageView.image = [self drawText:#"Test String" inImage:image atPoint:CGPointMake(10, 20)];
this is another methode declaration same problem the editor is not allowing me to put it on
UIFont *font = [UIFont boldSystemFontOfSize:100];
UIGraphicsBeginImageContext(self.view.frame.size);
[originalImage drawInRect:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height)];
CGRect rect = CGRectMake(point.x, point.y,lblText.frame.size.width, lblText.frame.size.height);
rect.size = [text sizeWithAttributes:#{NSFontAttributeName:[UIFont systemFontOfSize:150.0f]}];
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:font forKey:NSFontAttributeName];
[attributes setObject:[NSNumber numberWithFloat:4] forKey:NSStrokeWidthAttributeName];
[attributes setObject:[UIColor whiteColor] forKey:NSStrokeColorAttributeName];
[text drawInRect:rect withAttributes:attributes];
[attributes removeObjectForKey:NSStrokeWidthAttributeName];
[attributes removeObjectForKey:NSStrokeColorAttributeName];
[attributes setObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
[text drawInRect:rect withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
I don't really know what problem is, but I did this.. let me know if it works for you
- (void)viewDidLoad
{
UIImage *image = [UIImage imageNamed:#"image"];
UIImage *newImage = [self image:image withText:#"Hello World" atPoint:CGPointMake(20, 20)];
[self saveImage:image withName:#"original"];
[self saveImage:newImage withName:#"new"];
}
- (UIImage*)image:(UIImage*)image withText:(NSString*)text atPoint:(CGPoint)point
{
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[image drawInRect:rect];
NSDictionary *attributes = #{NSFontAttributeName : [UIFont boldSystemFontOfSize:20],
NSStrokeWidthAttributeName : #(4),
NSStrokeColorAttributeName : [UIColor whiteColor]};
[text drawAtPoint:point withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (void)saveImage:(UIImage*)image withName:(NSString*)name
{
NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *imagePath = [documents stringByAppendingPathComponent:name];
[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
}
Try this
+(UIImage*) drawText:(NSString*) text
inImage:(UIImage*) image
atPoint:(CGPoint) point
{
UIFont *font = [UIFont boldSystemFontOfSize:12];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
[[UIColor whiteColor] set];
[text drawInRect:CGRectIntegral(rect) withFont:font];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
This answer will make the text both aligned vertically and horizontally in the center of the UIImage.
Note: not my answer it is collected from several answers
- (UIImage*)image:(UIImage*)image withText:(NSString*)text{
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[image drawInRect:rect];
/// Make a copy of the default paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
/// Set text horizontal alignment
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = #{NSFontAttributeName : [UIFont boldSystemFontOfSize:16],
NSStrokeWidthAttributeName : #(4),
NSStrokeColorAttributeName : [UIColor whiteColor],
NSParagraphStyleAttributeName : paragraphStyle};
CGSize size = [text sizeWithAttributes:attributes];
CGRect newRect = CGRectMake(rect.origin.x,
rect.origin.y + (rect.size.height - size.height)/2.0,
rect.size.width,
size.height);
[text drawInRect:newRect withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;}
In my application there is a WebView with HTML contents. Contents is of 3 page in WebView .
Now i want to convert WebView content in PDF. I have created 3 image from the WebView content. Now i want to create pdf using these 3 image. Each image should one page of PDF. But it resulting as single page image. So when i am taking print then content is cut off.
I am using this,
CGSize pageSize = CGSizeMake(612, 2324);
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();
What i am doing wrong with this code.
THanks
/*For call method*/
[self createPdfWithName:#"sam" array:[NSArray arrayWithObjects:[UIImage imageNamed:#"01.png"],[UIImage imageNamed:#"02.png"], nil]];
/*Create New Pdf*/
- (NSString *)createPdfWithName: (NSString *)name array:(NSArray*)images
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSString *pdfFileName = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.pdf",name]];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
for (int index = 0; index <[images count] ; index++)
{
UIImage *pngImage=[images objectAtIndex:index];;
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, (pngImage.size.width), (pngImage.size.height)), nil);
[pngImage drawInRect:CGRectMake(0, 0, (pngImage.size.width), (pngImage.size.height))];
}
UIGraphicsEndPDFContext();
return pdfFileName;
}
func createPDFS(arrImages: [UIImage]) -> NSData? {
var pageHeight = 0.0
var pageWidth = 0.0
for img in arrImages
{
pageHeight = pageHeight+Double(img.size.height)
if Double(img.size.width) > pageWidth
{
pageWidth = Double(img.size.width)
}
}
let pdfData = NSMutableData()
let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!
var mediaBox = CGRect.init(x: 0, y: 0, width: pageWidth, height: pageHeight)
let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!
for img in arrImages
{
var mediaBox2 = CGRect.init(x: 0, y: 0, width: img.size.width, height: img.size.height)
pdfContext.beginPage(mediaBox: &mediaBox2)
pdfContext.draw(img.cgImage!, in: CGRect.init(x: 0.0, y: 0, width: pageWidth, height: Double(img.size.height)))
pdfContext.endPage()
}
return pdfData
}
CGSize pageSize = CGSizeMake(612, 2324);
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, 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];
// TODO: See Here
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pngImage.size.height), nil);
[pngImage drawInRect:CGRectMake(0, currentHeight, pageSize.width, pngImage.size.height)];
//currentHeight += pngImage.size.height;
}
UIGraphicsEndPDFContext();