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.
Related
In xcode, how would I convert a UIImage into a PDF File? Once I figure this out, I will send it through an email. But everything I've found while researching, it results as a blank file or gives an error saying it's damaged. How should I convert it?
-(void)createPdf:(NSImage*)image
{
PDFDocument *pdf = [[PDFDocument alloc] init];
NSImage *image = [[NSImage alloc] initWithContentsOfFile:fileName];
PDFPage *page = [[PDFPage alloc] initWithImage:image];
[pdf insertPage:page atIndex: [pdf pageCount]];
[pdf writeToFile:path];
}
USE the above method as follow :
NSImage *image = [[NSImage alloc] initWithContentsOfFile:PATH_OF_YOUR_PNG_FILE];
[self createPdf:image];
PDFDocument Class conforms to NSObject. You can use this PDFDocument class in the PDFKit Framework.
1. Download Source File From Step 4
2. Import into your Project
3. Put This code into your action
NSData *pdfData = [[NSData alloc] init];
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
pdfData = [PDFImageConverter convertImageToPDF:chosenImage];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: #"Documents/image.pdf"];
[pdfData writeToFile:path atomically:NO];
4. Enjoy PDFImageConverter
First you need to create a PDF graphics context that is GraphicsBegin and GraphicsEndPDFContext. Your image from current view will capture and it will set on your PDF page.
Steps:
First call this method on any of your button tap event:
NSString *fileName = [NSString stringWithFormat:#“pdf file name here”];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
// This method will generate pdf file of your image. You can send that pdf file after this method.
[self generatePdfWithFilePath: pdfFileName];
Then set these methods in your view controller:
- (void) generatePdfWithFilePath: (NSString *)thefilePath
{
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 500, 810), nil);
[self drawImage:#“page number of pdf file”];
UIGraphicsEndPDFContext();
}
- (void) drawImage:(NSInteger)pageNumber
{
UIImage * demoImage1;
demoImage1 = [self captureView:#“Your image view”];
[demoImage1 drawInRect:CGRectMake(0, 0, 500, 810)];
}
- (UIImage *)captureView:(UIView *)view {
CGRect screenRect = view.frame;
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, screenRect);
[view.layer renderInContext:ctx];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to generate a pdf file with text that will change every time based on my server data. I want to create that pdf file using html in iOS. Any suggestions. Please help.
Thanks in advance.
Please check below link :
https://github.com/iclems/iOS-htmltopdf.
Its have methods for doing that with local html file as well as with URL also.
+ (id)createPDFWithHTML:(NSString*)HTML pathForPDF:(NSString*)PDFpath delegate:(id <NDHTMLtoPDFDelegate>)delegate pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins;
+ (id)createPDFWithHTML:(NSString*)HTML baseURL:(NSURL*)baseURL pathForPDF:(NSString*)PDFpath delegate:(id <NDHTMLtoPDFDelegate>)delegate pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins;
+ (id)createPDFWithHTML:(NSString*)HTML pathForPDF:(NSString*)PDFpath pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins successBlock:(NDHTMLtoPDFCompletionBlock)successBlock errorBlock:(NDHTMLtoPDFCompletionBlock)errorBlock;
+ (id)createPDFWithHTML:(NSString*)HTML baseURL:(NSURL*)baseURL pathForPDF:(NSString*)PDFpath pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins successBlock:(NDHTMLtoPDFCompletionBlock)successBlock errorBlock:(NDHTMLtoPDFCompletionBlock)errorBlock;
You can try this:
You need to show it on webview like this
-(IBAction)convertPDF:(id)sender {
webViewHeight = [[self.myWebView stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight;"] integerValue];
CGRect screenRect = self.myWebView.frame;
double currentWebViewHeight = webViewHeight;
while (currentWebViewHeight > 0)
{
imageName ++;
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, screenRect);
[self.myWebView.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 < 960)
{
CGRect lastImageRect = CGRectMake(0, 960 - currentWebViewHeight, self.myWebView.frame.size.width, currentWebViewHeight);
CGImageRef lastImageRef = CGImageCreateWithImageInRect([newImage CGImage], lastImageRect);
newImage = [UIImage imageWithCGImage:lastImageRef];
CGImageRelease(lastImageRef);
}
[UIImagePNGRepresentation(newImage) writeToFile:pngPath atomically:YES];
[self.myWebView stringByEvaluatingJavaScriptFromString:#"window.scrollBy(0,960);"];
currentWebViewHeight -= 960;
}
[self drawPdf];
}
then draw PDF from webview
- (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(); }
In viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path;
NSBundle *bundle = [NSBundle mainBundle];
path = [bundle pathForResource:#"Demo" ofType:#"html"];
NSURL *fileUrl = [NSURL URLWithString:#"https://www.google.com/sites/overview.html"];
[self.myWebView loadRequest:[NSURLRequest requestWithURL:fileUrl]];
}
I have open pdf file in uiwebview, add image and text in uiwebview subview.Then i tried created pdf file. Below sample i have used to generate pdf file. Multiple page writing in single page. How can i write sample quality and exact size.
Please check screen shots and below source
UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );
for (int i = 0; i < 10; i++) {
CGRect f = [pdfView frame];
[pdfView setFrame: f];
UIGraphicsBeginPDFPage();
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins
[[[pdfView subviews] lastObject] setContentOffset:CGPointMake(0, 648 * i) animated:NO];
[pdfView.layer renderInContext:currentContext];
}
UIGraphicsEndPDFContext();
and also i have tried this following link but i couldn't add uiwebview subview to write the pdf.
http://b2cloud.com.au/tutorial/drawing-over-a-pdf-in-ios-pdf-template/
You can use the following category on UIView to create a PDF file:
#import <QuartzCore/QuartzCore.h>
#implementation UIView(PDFWritingAdditions)
- (void)renderInPDFFile:(NSString*)path
{
CGRect mediaBox = self.bounds;
CGContextRef ctx = CGPDFContextCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], &mediaBox, NULL);
CGPDFContextBeginPage(ctx, NULL);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -mediaBox.size.height);
[self.layer renderInContext:ctx];
CGPDFContextEndPage(ctx);
CFRelease(ctx);
}
#end
Bad news: UIWebView does not create nice shapes and text in the PDF, but renders itself as an image into the PDF.
OR
How to Convert UIView to PDF within iOS?
OR
Creating PDF file from UIWebView
This might helps you :)
I have also used the same its working fine Hope this will be helpful for you.
Create a block:-
typedef void (^PdfCompletion)(BOOL status,NSString *filePath,NSArray *fbArr);
-(void)addData
{
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
NSMutableDictionary *contactDict = [[NSMutableDictionary alloc] init];
[contactDict setObject:contactTextField.text forKey:#"phonenumber"];
[contactDict setObject:emailTextField.text forKey:#"emailid"];
[contactDict setObject:userNameLabel.text forKey:#"displayname"];
[self drawPdf:contactDict completion:^(BOOL status,NSString *filePath,NSArray *fbArr)
{
if (status)
{
NSMutableArray *arr;
arr = [[NSMutableArray alloc] init];
NSData *filedata;
filedata = [NSData dataWithContentsOfFile:filePath];
double locaTotalFileSize = filedata.length +498;
totalFileSize += locaTotalFileSize;
NSMutableDictionary *fileDict = [[NSMutableDictionary alloc] init];
[fileDict setObject:userPicImageView.image forKey:#"image"];
[fileDict setObject:filePath forKey:#"filePath"];
[fileDict setObject:#"txt" forKey:#"fileType"];
[fileDict setObject:[NSString stringWithFormat:#"%#_%#_%#",#"contact",[self getFbID],[self CurrentSystemTime]] forKey:#"fileName"];
[fileDict setObject:#"1" forKey:#"uploadStatus"];
[fileDict setObject:#"0 KB/0 KB" forKey:#"fileSizeStatus"];
[fileDict setObject:#"0 KB/0 KB" forKey:#"ContentSize"];
[arr addObject:fileDict];
[self switchToReviewFiles:arr];
//////NSLog(#"pdf convrt successfull");
}
else
{
//////NSLog(#"Error to convert into pdf");
}
}];
}
// Then Call The DrawPDF Method::--
-(void)drawPdf:(NSMutableDictionary *)drawText completion:(PdfCompletion)callback
{
NSString* fileName = #"contact_card.txt";
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *path = [arrayPaths objectAtIndex:0];
NSString* txtFileName = [path stringByAppendingPathComponent:fileName];
NSData *data = [NSJSONSerialization dataWithJSONObject:drawText options:NSJSONWritingPrettyPrinted error:nil];
[data writeToFile:txtFileName atomically:YES];
callback(YES,txtFileName,nil);
}
It looks to me like you're just trying to add content to an existing PDF, right?
- (void) drawCustomPDFContent
{
// Put your drawing calls here
// Draw a red box
[[UIColor redColor] set];
UIRectFill(CGRectMake(20, 20, 100, 100));
// Example of drawing your view into PDF, note that this will be a rasterized bitmap, including the text.
// To get smoother text you'll need to use the NSString draw methods
CGContextRef ctx = UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
}
- (void) createCustomPDF
{
NSURL* pdfURL = ... /* URL to pdf file */;
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
const size_t numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);
NSMutableData* data = [NSMutableData data];
UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);
for(size_t page = 1; page <= numberOfPages; page++)
{
// Get the current page and page frame
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf, page);
const CGRect pageFrame = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);
// Draw the page (flipped)
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
CGContextDrawPDFPage(ctx, pdfPage);
CGContextRestoreGState(ctx);
if(page == 1)
{
[self drawCustomPDFContent];
}
}
UIGraphicsEndPDFContext();
CGPDFDocumentRelease(pdf);
pdf = nil;
// Do something with data here
[data writeToFile:... atomically:YES];
}
Parts referenced from:
http://b2cloud.com.au/tutorial/drawing-over-a-pdf-in-ios-pdf-template/
You can try this.It worked for me :)
https://github.com/iclems/iOS-htmltopdf/blob/master/NDHTMLtoPDF.h
NSString *html = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
self.PDFCreator = [NDHTMLtoPDF createPDFWithHTML:html
pathForPDF:[path stringByExpandingTildeInPath]
delegate:self
pageSize:CGSizeMake(595,847)
margins:UIEdgeInsetsMake(105, 0, 0, 0)];
Pass the webView like this
You are actually very close with the code you have. I have a feeling your biggest problem is grabbing a new CGContextRef with each loop iteration..
UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );
CGContextRef currentContext = UIGraphicsGetCurrentContext();//movedByJef
// default pdf..
// 8.5 X 11 inch
// 612 x 792
for (int i = 0; i < 10; i++) {
CGContextSaveGstate( currentContext ); //addedByJef
CGRect f = [pdfView frame];
[pdfView setFrame: f]; // hmm what does this even do??
UIGraphicsBeginPDFPage();
CGContextTranslateCTM(currentContext, -72, -72); // Translate for 1" margins ///editedByJef, you had it backwards..
//assuming you want a 72pt margin on right and bottom as well..
//we want to reduce our size (612 x 792) by 72pts on all four sides..
CGSize printPageSize = CGSizeMake( (612.0 - (72.0 * 2.0)), (792.0 -(72.0*2.0)) );
CGSize layrSize = self.layer.bounds.size;
//so we translate the context so our view fills it nicely..
CGFloat xScaler = layrSize.width / printPageSize.width;
CGFloat yScaler = layrSize.height / printPageSize.height;
CGContextConcatCTM(currentContext, CGAffineTransformMakeScale(xScaler, yScaler) );
[[[pdfView subviews] lastObject] setContentOffset:CGPointMake(0, 648 * i) animated:NO];
[pdfView.layer renderInContext:currentContext];
CGContextRestoreGstate(currentContext);//added by jef
}
UIGraphicsEndPDFContext();
let me know how you go with that, There will undoubtedly be a bit of shuffling in the order of the transforms, maybe a translate needed either side of the scaling, but this should get you really close..
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];
}
Updated I am able to create single PDF page of photo captured with comment in iPHone. On button click I am generating one single PDF page every time and I want those PDF page in single PDF bunch. I am not able to merge the single PDF files in to bunch.
http://mobile.tutsplus.com/tutorials/iphone/generating-pdf-documents/?search_index=3
I have followed the above URL code. Could you suggest some logic here. Thanks in advance.
*Edit in code * can you check below code.
- (IBAction)didClickOpenPDF {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.pdf",myPDFName]];
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:[NSString stringWithFormat:#"%#",myPDFName] Width:850 Height:1100];
[self beginPDFPage];
CGRect textRect = [self addText:question.text
withFrame:CGRectMake(kPadding, kPadding, 400, 200) fontSize:48.0f];
// dynamic image captured by camera,comment text, lines are added here
[self finishPDF];
}
- (void)setupPDFDocumentNamed:(NSString*)name Width:(float)width Height:(float)height {
_pageSize = CGSizeMake(width, height);
NSString *myPDFName = [NSString stringWithFormat:#"%#.pdf", name];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:myPDFName];
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
int count = [gotIndexString integerValue];
for (int pageNumber = 2; pageNumber <= count; pageNumber++)
{
//Open a pdf page context
UIGraphicsBeginPDFPageWithInfo(CGRectZero, nil);
//Get graphics context to draw the page
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//Flip and scale context to draw the pdf correctly
CGContextTranslateCTM(currentContext, 0, CGRectZero.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
NSURL *newUrl = [NSURL URLWithString:pdfPath];
NSLog(#" setupPDFDocumentNamed newUrl for loop %# ",newUrl);
//Get document access of the pdf from which you want a page
CGPDFDocumentRef newDocument = CGPDFDocumentCreateWithURL ((__bridge_retained CFURLRef) newUrl);
NSLog(#" setupPDFDocumentNamed newDocument for loop %# ",newDocument);
//Get the page you want
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, 1);
NSLog(#" setupPDFDocumentNamed newPage for loop %# ",newPage);
//Drawing the page
CGContextDrawPDFPage (currentContext, newPage);
NSLog(#"CGContextRef context %# ",currentContext);
//Clean up
newPage = nil;
CGPDFDocumentRelease(newDocument);
newDocument = nil;
newUrl = nil;
}
}
- (void)beginPDFPage {
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, _pageSize.width, _pageSize.height), nil);
}
- (void)finishPDF {
UIGraphicsEndPDFContext();
}
I managed to achieve this by following code with some complex logic :)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// File paths
NSString *pdfPath1 = [documentsDirectory stringByAppendingPathComponent:#"temp1.pdf"];
NSString *pdfPath2 = [documentsDirectory stringByAppendingPathComponent:#"temp2.pdf"];
NSString *pdfPathOutput = [documentsDirectory stringByAppendingPathComponent:#"out.pdf"];
// File URLs - bridge casting for ARC
CFURLRef pdfURL1 = (__bridge_retained CFURLRef)[[NSURL alloc] initFileURLWithPath: (NSString *)pdfPath1];//(CFURLRef) NSURL
CFURLRef pdfURL2 = (__bridge_retained CFURLRef)[[NSURL alloc] initFileURLWithPath: (NSString *)pdfPath2];//(CFURLRef)
CFURLRef pdfURLOutput =(__bridge_retained CFURLRef) [[NSURL alloc] initFileURLWithPath: (NSString *)pdfPathOutput];//(CFURLRef)
// File references
CGPDFDocumentRef pdfRef1 = CGPDFDocumentCreateWithURL((CFURLRef) pdfURL1);
CGPDFDocumentRef pdfRef2 = CGPDFDocumentCreateWithURL((CFURLRef) pdfURL2);
// Number of pages
NSInteger numberOfPages1 = CGPDFDocumentGetNumberOfPages(pdfRef1);
NSInteger numberOfPages2 = CGPDFDocumentGetNumberOfPages(pdfRef2);
// Create the output context
CGContextRef writeContext = CGPDFContextCreateWithURL(pdfURLOutput, NULL, NULL);
// Loop variables
CGPDFPageRef page;
CGRect mediaBox;
// Read the first PDF and generate the output pages
NSLog(#"GENERATING PAGES FROM PDF 1 (%i)...", numberOfPages1);
for (int i=1; i<=numberOfPages1; i++) {
page = CGPDFDocumentGetPage(pdfRef1, i);
mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGContextBeginPage(writeContext, &mediaBox);
CGContextDrawPDFPage(writeContext, page);
CGContextEndPage(writeContext);
}
// Read the second PDF and generate the output pages
NSLog(#"GENERATING PAGES FROM PDF 2 (%i)...", numberOfPages2);
for (int i=1; i<=numberOfPages2; i++) {
page = CGPDFDocumentGetPage(pdfRef2, i);
mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGContextBeginPage(writeContext, &mediaBox);
CGContextDrawPDFPage(writeContext, page);
CGContextEndPage(writeContext);
}
NSLog(#"DONE!");
// Finalize the output file
CGPDFContextClose(writeContext);
// Release from memory
CFRelease(pdfURL1);
CFRelease(pdfURL2);
CFRelease(pdfURLOutput);
CGPDFDocumentRelease(pdfRef1);
CGPDFDocumentRelease(pdfRef2);
CGContextRelease(writeContext);