I'm trying to send a .pdf to my app, have it convent each page to a .png, edit photo, then convent them back into one .pdf. I can convert the .pdf to multiple .pngs but trying to convert them back into one .pdf is giving me problems it is exporting each page/image into its own pdf not one. This is just the quick and dirty code where i'm trying to send a .pdf, convert to .pngs, then back to a .pdf with out the editing of the .pngs right now. I've looked at http://code.tutsplus.com/tutorials/generating-pdf-documents--mobile-11265 and Creating a single page pdf file with array of images in iOS? but the images are not in an array... any help would be greatly appreciated.
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
NSLog(#"Open URL:\t%#\n"
"From source:\t%#\n"
"With annotation:%#",
url, sourceApplication, annotation);
CGPDFDocumentRef SourcePDFDocument = CGPDFDocumentCreateWithURL((__bridge CFURLRef)url);
size_t numberOfPages = CGPDFDocumentGetNumberOfPages(SourcePDFDocument);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathAndDirectory = [documentsDirectory stringByAppendingPathComponent:#"temp"];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
[[NSFileManager defaultManager] removeItemAtPath:filePathAndDirectory error:&error];
NSLog(#"other error: %#", error);
[[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
withIntermediateDirectories:NO
attributes:nil
error:&error];
}
NSMutableData *pdfFile = [[NSMutableData alloc] init];
CGDataConsumerRef pdfConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfFile);
for(int currentPage = 1; currentPage <= numberOfPages; currentPage ++ )
{
CGPDFPageRef SourcePDFPage = CGPDFDocumentGetPage(SourcePDFDocument, currentPage);
// CoreGraphics: MUST retain the Page-Refernce manually
CGPDFPageRetain(SourcePDFPage);
NSString *relativeOutputFilePath = [NSString stringWithFormat:#"%#/%#%d.png", #"temp", #"photo", currentPage];
NSString *ImageFileName = [documentsDirectory stringByAppendingPathComponent:relativeOutputFilePath];
CGRect sourceRect = CGPDFPageGetBoxRect(SourcePDFPage, kCGPDFCropBox);
UIGraphicsBeginPDFContextToFile(ImageFileName, sourceRect, nil);
UIGraphicsBeginImageContextWithOptions(sourceRect.size, NO, 3);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 0.0, sourceRect.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGContextDrawPDFPage (currentContext, SourcePDFPage); // draws the page in the graphics context
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent: relativeOutputFilePath];
CGDataConsumerRef pdfConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfFile);
// The page size matches the image, no white borders.
CGRect mediaBox = CGRectMake(0, 0, sourceRect.size.width, sourceRect.size.height);
CGContextRef pdfContext = CGPDFContextCreate(pdfConsumer, &mediaBox, NULL);
CGContextBeginPage(pdfContext, &mediaBox);
CGContextDrawImage(pdfContext, mediaBox, [image CGImage]);
CGContextEndPage(pdfContext);
CGContextRelease(pdfContext);
CGDataConsumerRelease(pdfConsumer);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
NSString *end = #".pdf";
NSString *start = #"Documents/image";
NSString * timestamp = [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970]];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:#"%#%#%#", start, timestamp, end]];
[pdfFile writeToFile:path atomically:YES];
NSLog([NSString stringWithFormat:#"%#%#%#", start, timestamp, end]);
}
return YES;
}
Your problem is that UIGraphicsBeginPDFContextToFile and CGContextRelease(pdfContext) statements should be outside your for loop.
Try this (assuming you've placed all images as a UIImageView on a UIScrollView):
/* CREATE PDF */
self.pdfData = [NSMutableData data];
NSInteger pageHeight = 800;
UIGraphicsBeginPDFContextToData(self.pdfData, CGRectMake(0,0,768,pageHeight), nil);//768*792/612
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
for (int page=0; pageHeight *page < scrollView.frame.size.height; page++)
{
UIGraphicsBeginPDFPage();
CGContextTranslateCTM(pdfContext, 0, -pageHeight * page);
[scrollView.layer renderInContext:pdfContext];
}
UIGraphicsEndPDFContext();
/* EXPORT PDF */
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* fileName = [self genRandStringLength:7];
fileName = [NSString stringWithFormat:#"%#.pdf", fileName];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:fileName];
// instructs the mutable data object to write its context to a file on disk
[self.pdfData writeToFile:documentDirectoryFilename atomically:YES];
Related
I have drawable text which is used for signature ,
I want this context save in png format with a specific path but I could not do this.I want my draw image save in png format and I can use any where
**Code for png format and path**
NSData *imageData = UIImagePNGRepresentation(_SignatureView.signatureImage);
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"/imageName.png"];
[imageData writeToFile:imagePath atomically:YES];
_SignatureView is a property and signatureImage is a method
**code of signature image method**
- (UIImage *)signatureImage
{
if (!self.hasSignature)
return nil;
UIImage *screenshot = [self snapshot];
return screenshot;
}
NSString *docPath= #"/Users/.../.../";
NSString *filePath=[docPath stringByAppendingPathComponent:#"PdfFileName.pdf"];
NSMutableData pdfData=[NSMutableData data];
CGRect bounds = CGRectMake(0, 0, 612, 792);
UIGraphicsBeginPDFContextToData(pdfData, bounds, nil);
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
UIGraphicsBeginPDFPage();
[YourSignature.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
[pdfData writeToFile:filePath atomically:YES];
Try like this
- (void)saveImage: (UIImage*)image
{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"test.png"] ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}
and to get the image use the following code
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"test.png"] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
I'm creating a PDF reader app.
When calling CGContextDrawPDFPage(context, sourcePDFPage);, xCode reports "FlateDecode: decoding error.".
On iOS7, even I have this error, I can extract each page of original PDF to a single PDF page.
But on iOS8 or later, the app crashes at this point.
Would anybody kindly help me?
Thank you in advance.
My codes are below.
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSString *fromPath = [location path];
NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *fileName = [NSString stringWithFormat:#"download.pdf"];
downloadDestinationPath = [docDir stringByAppendingPathComponent:fileName];
NSError *error;
NSFileManager *fileManage = [NSFileManager defaultManager];
// ファイル削除
if( [fileManage fileExistsAtPath:downloadDestinationPath])
{
NSError *error = nil;
[fileManage removeItemAtPath:downloadDestinationPath error:&error];
}
BOOL copyResult = [fileManage copyItemAtPath:fromPath toPath:downloadDestinationPath error:&error];
if( copyResult ) {
CFStringRef fullPathEscaped = CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)downloadDestinationPath, NULL, NULL,kCFStringEncodingUTF8);
CFURLRef pdfURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, fullPathEscaped, kCFURLPOSIXPathStyle, NO);
document_ = CGPDFDocumentCreateWithURL(pdfURL);
// ページ数取得
size_t num = CGPDFDocumentGetNumberOfPages( document_ );
_pageNumber = num;
_documentPath = [[NSString alloc]initWithString:docDir];
for( int i = 1; i <=num; i++)
{
NSString *pdfFileName = [docDir stringByAppendingFormat:#"/Page%d.pdf", i];
// ファイル削除
if( [fileManage fileExistsAtPath:pdfFileName])
{
NSError *error = nil;
[fileManage removeItemAtPath:pdfFileName error:&error];
}
CGPDFPageRef sourcePDFPage = CGPDFDocumentGetPage(document_, i);
CGPDFPageRetain(sourcePDFPage);
CGRect sourceRect = CGPDFPageGetBoxRect(sourcePDFPage, kCGPDFMediaBox);
UIGraphicsBeginPDFContextToFile(pdfFileName, sourceRect, nil);
UIGraphicsBeginPDFPage();
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, sourceRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawPDFPage(context, sourcePDFPage);
UIGraphicsEndPDFContext();
CGPDFPageRelease(sourcePDFPage);
}
CFRelease( pdfURL );
pdfURL = NULL;
CFRelease(fullPathEscaped);
CGPDFDocumentRelease(document_);
fullPathEscaped = NULL;
[_delegate didLoadPDF];
}
My question is what format the image is saved, if is dat or jpg. This is the code that i used:
NSString * urlImage = .....;
NSString * _folderPath = .....;
NSString * imageName = [[urlImage componentsSeparatedByString:#"/"] lastObject];
NSString * jpegPath = [NSString stringWithFormat:#"%#%#",_folderPath,imageName];
if (![[NSFileManager defaultManager] fileExistsAtPath:jpegPath])
{
NSURL *url = [NSURL URLWithString:urlImage];
//Download image
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];
//Save image
NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data writeToFile:jpegPath atomically:YES];
}
Following is piece of code for save .jpg image
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString* path = [docs stringByAppendingFormat:#"/image1.jpg"];
NSData* imageData = [NSData dataWithData:UIImageJPEGRepresentation(imageView.image, 80)];
NSError *writeError = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&writeError];
You should use
stringByAppendingPathComponent method to create or get exact valid path
Use this way:
NSString * jpegPath = [_folderPath stringByAppendingPathComponent:imageName];// [NSString stringWithFormat:#"%#%#",_folderPath,imageName];
I've created folder called "Image store" using the following code. my requirment is i want to save images to the folder "Image store" on api success and the images should be saved in application itself not in database or photo album.I want to know the mechanism by which i can store images in application
-(void) createFolder {
UIImage *image = [[UIImage alloc]init];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/ImageStore"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
else
{
}
}
//Make a method that has url (fileName) Param
NSArray *documentsDirectory =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSFileManager *fileManager =[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:textPath])
{
return YES;
}
else
{
return NO;
}
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage
imageNamed:#""]];//Placeholder image
if ([url isKindOfClass:[NSString class]])
{
imgView.image = [UIImage imageNamed:[url absoluteString]];
imgView.contentMode = UIViewContentModeScaleAspectFit;
}
else if ([fileManager fileExistsAtPath:url])
{
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfFile:textPath options:NSDataReadingMappedIfSafe error:&error];
if (error != nil)
{
DLog(#"There was an error: %#", [error description]);
imgView.image=nil;
}
else
{
imgView.image= [UIImage imageWithData:fileData]
}
}
else
{ UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint center = imgView.center;
// center.x = imgView.bounds.size.width / 2;
spinner.center = center;
[spinner startAnimating];
[imgView addSubview:spinner];
dispatch_queue_t downloadQueue = dispatch_queue_create("iamge downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner removeFromSuperview];
UIImage *image = [UIImage imageWithData:imgData];
NSError *error = nil;
[imgData writeToFile:url options:NSDataWritingFileProtectionNone error:&error];
if (error != nil)
{
}
else
{
}
imgView.image = image;
});
});
}
Thats UIImageView loading an image if it doesnot exist in document then it Save it , An Activity indicator is added to show image is loading to save,
u can do something like this
u can run a loop for images like this
//at this point u can get image data
for(int k = 0 ; k < imageCount; k++)
{
[self savePic:[NSString stringWithFormat:#"picName%d",k] withData:imageData];//hear data for each pic u can send
}
- (void)savePic:(NSString *)picName withData:(NSData *)imageData
{
if(imageData != nil)
{
NSString *path = [NSString stringWithFormat:#"/ImageStore/%#.png",pincName];
NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngPath = [NSString stringWithFormat:#"%#%#",Dir,path]; //path means ur destination contain's this format -> "/foldername/picname" pickname must be unique
if(![[NSFileManager defaultManager] fileExistsAtPath:[pngPath stringByDeletingLastPathComponent]])
{
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:[pngPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&error];
if(error)
{
NSLog(#"error in creating dir");
}
}
[imageData writeToFile:pngPath atomically:YES];
}
}
after successful download and saving u can retrieve images like below
- (UIImage *)checkForImageIn:(NSString *)InDestination
{
NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngPath = [NSString stringWithFormat:#"%#%#",Dir,InDestination];//hear "InDestination" format is like this "/yourFolderName/imagename" as i said imagename must be unique .. :)
UIImage *image = [UIImage imageWithContentsOfFile:pngPath];
if(image)
{
return image;
}
else
return nil;
}
link to find path
see this link to find the path ..
aganin do same this run loop like below
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
for(int k = 0 ; k < imageCount; k++)
{
UIImage *image = [self checkForImageIn:[NSString stringWithFormat: #"/yourFolderName/ImageName%d",k]];//get the image
[imagesArray addObject:image];//store to use it somewhere ..
}
Write this code after creating directory
NSString *path= [documentsDirectory stringByAppendingPathComponent:#"/ImageStore"];
UIImage *rainyImage =[UImage imageNamed:#"rainy.jpg"];
NSData *Data= UIImageJPEGRepresentation(rainyImage,0.0);
[data writeToFile:path atomically:YES]
The document directory is found like this:
// Let's save the file into Document folder.
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// If you go to the folder below, you will find those pictures
NSLog(#"%#",docDir);
NSLog(#"saving png");
NSString *pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
Thats just a sample of the code provided which tells you where the correct path is to save in your ipone device.
Check the below blog post,it's step by step guide with source code .
Download an Image and Save it as PNG or JPEG in iPhone SDK
Am trying to sign my pdf file which is multiple paged, by fetching the signature drawn in UIView to my pdf file, but the problem I face is, after signing the pdf, i could view only the single page of file which is signed, not rest of the pages in my webview.(for eg; if page 3 of my pdf file is signed, i could view only page 3 in my webview, and the pdf file is limited to only page number 3 in my document directory).
Codes used for fetching the signature from document directory to pdf file is,
- (void)viewWillAppear:(BOOL)animated
{
[webView reload];
UIWebView *webView;
webView= [[UIWebView alloc] initWithFrame:CGRectMake(0,44, 320, 460)];
NSString *path1;
path1 = [[NSBundle mainBundle] pathForResource:#"typo_tips" ofType:#"pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDirectoryPath;
NSURL *targetURL;
documentDirectoryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"typo_tips.pdf"];
[fileManager copyItemAtPath:path1 toPath:documentDirectoryPath error:&error];
NSLog(#"path1 value is %# \n",path1);
NSLog(#"docu dir path is %# \n",documentDirectoryPath);
if (entered==1)//"entered==1", after save button clicked in signviewcontroller
{
targetURL = [NSURL fileURLWithPath:documentDirectoryPath];
}
else targetURL = [NSURL fileURLWithPath:path1];
if (entered==1)
{
CFURLRef url;
url = (CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:documentDirectoryPath]);
CGPDFDocumentRef myDocument;
myDocument = CGPDFDocumentCreateWithURL(url);
// Create PDF context
CGContextRef pdfContext = CGPDFContextCreateWithURL(url, NULL, NULL); //(CFURLRef)outputURL
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);
int totalPages = (int)CGPDFDocumentGetNumberOfPages(myDocument);
NSLog(#"no. of pages in pdf is %d \n",totalPages);
CGContextDrawPDFPage(UIGraphicsGetCurrentContext(), CGPDFDocumentGetPage(myDocument, page));
//"page" is current pdf page to be signed
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];// "image.png" is the saved user's signature in document directory
image = [[UIImage alloc] initWithContentsOfFile:filePath];
CGRect imageRect = CGRectMake(50, 50, image.size.width, image.size.height);
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);
// Clean up
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
}
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
}
You have to re-render each page (even the ones not being altered).
CGContextRef pdfContext = CGPDFContextCreateWithURL(url, NULL, NULL); //(CFURLRef)outputURL
UIGraphicsPushContext(pdfContext);
int totalPages = (int)CGPDFDocumentGetNumberOfPages(myDocument);
NSLog(#"no. of pages in pdf is %d \n",totalPages);
for (int currentPage = 0; currentPage < totalPages; currentPage++)
{
CGPDFContextBeginPage(pdfContext, NULL);
CGContextDrawPDFPage(UIGraphicsGetCurrentContext(), CGPDFDocumentGetPage(myDocument, currentPage));
//"page" is current pdf page to be signed
if (page == currentPage)
{
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];// "image.png" is the saved user's signature in document directory
image = [[UIImage alloc] initWithContentsOfFile:filePath];
CGRect imageRect = CGRectMake(50, 50, image.size.width, image.size.height);
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);
}
}
// Clean up
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
Found the solution with the help of iPDFDev:
In the for loop have to create a new PDF page for each page in the source file. So move these lines inside the for loop:
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);
and also the corresponding cleanup code.
(void)viewWillAppear:(BOOL)animated
{
[webView reload];
UIWebView *webView;
webView= [[UIWebView alloc] initWithFrame:CGRectMake(0,44, 320, 460)];
NSString *path1;
path1 = [[NSBundle mainBundle] pathForResource:#"typo_tips" ofType:#"pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDirectoryPath;
NSURL *targetURL;
documentDirectoryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"typo_tips.pdf"];
[fileManager copyItemAtPath:path1 toPath:documentDirectoryPath error:&error];
NSLog(#"path1 value is %# \n",path1);
NSLog(#"docu dir path is %# \n",documentDirectoryPath);
if (entered==1)//"entered==1", after save button clicked in signviewcontroller
{
targetURL = [NSURL fileURLWithPath:documentDirectoryPath];
}
else targetURL = [NSURL fileURLWithPath:path1];
if (entered==1)
{
CFURLRef url;
url = (CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:documentDirectoryPath]);
CGPDFDocumentRef myDocument;
myDocument = CGPDFDocumentCreateWithURL(url);
// Create PDF context
CGContextRef pdfContext = CGPDFContextCreateWithURL(url, NULL, NULL);
int totalPages = (int)CGPDFDocumentGetNumberOfPages(myDocument);
NSLog(#"no. of pages in pdf is %d \n",totalPages);
for (int currentPage = 0; currentPage < totalPages; currentPage++)
{
//(CFURLRef)outputURL
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);
CGContextDrawPDFPage(UIGraphicsGetCurrentContext(), CGPDFDocumentGetPage(myDocument, page));
//"page" is current pdf page to be signed
if (page == currentPage)
{
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];// "image.png" is the saved user's signature in document directory
image = [[UIImage alloc] initWithContentsOfFile:filePath];
CGRect imageRect = CGRectMake(50, 50, image.size.width, image.size.height);
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);
}
// Clean up
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
}
CGPDFContextClose(pdfContext);
}
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
}