I am creating pdf from UIView to pdf it works fine but i have scrollView with content which i want to convert to pdf but it only show visible part in pdf not the whole scrollView content. here is my code
-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
NSMutableData *pdfData = [NSMutableData data];
// Get Scrollview size
CGRect scrollSize = CGRectMake(1018,76,scrollView.contentSize.width,scrollView.contentSize.height);
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, scrollSize, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView.layer renderInContext:pdfContext];
// 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);
}
THis gives you the visible portion of the UIScrollView
CGRect visibleRect;
visibleRect.origin = scrollView.contentOffset;
visibleRect.size = scrollView.bounds.size;
float theScale = 1.0 / scale;
visibleRect.origin.x *= theScale;
visibleRect.origin.y *= theScale;
visibleRect.size.width *= theScale;
visibleRect.size.height *= theScale;
so you can use this in UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
by some minor changes in the parameters.
(void)createPDFfromUIView:(UIScrollView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Get Scrollview size
CGRect scrollSize = CGRectMake(aView.origin.x,aView.origin.y,aView.contentSize.width,aView.contentSize.height);
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, scrollSize, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView.layer renderInContext:pdfContext];
// 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);
}
This code i used to make pdf from uiscrollview and it does help but it will not be as good as if we draw on pdf -- please have look -- Pdf from UIScrollView
- (void) createPDF
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *directroyPath = nil;
directroyPath = [documentsDirectory stringByAppendingPathComponent:#"temp"];
NSString *filePath = [directroyPath stringByAppendingPathComponent:#"test.pdf"];
// check for the "PDF" directory
NSError *error;
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
} else {
[[NSFileManager defaultManager] createDirectoryAtPath:directroyPath
withIntermediateDirectories:NO
attributes:nil
error:&error];
}
CGContextRef pdfContext = [self createPDFContext:_scrollView2.bounds path:(CFStringRef)filePath];
NSLog(#"PDF Context created");
/*
Here limit of i is no of pages in your uiscrollview or
you can use hit and trial here because there is a
length of page is going to be equal to
the visible size of uiscrollView in your application
*/
for (int i = 0 ; i< 2 ; i++)
{
// page 1
CGContextBeginPage (pdfContext,nil);
//turn PDF upsidedown
CGAffineTransform transform = CGAffineTransformIdentity;
//here 365 is equal to the height of myScrollView.frame.size.height
transform = CGAffineTransformMakeTranslation(0, (i+1) * 365);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
CGContextConcatCTM(pdfContext, transform);
//Draw view into PDF
[_scrollView2.layer renderInContext:pdfContext];
CGContextEndPage (pdfContext);
[_scrollView2 setContentOffset:CGPointMake(0, (i+1) * 365) animated:NO];
}
CGContextRelease (pdfContext);
}
- (CGContextRef) createPDFContext:(CGRect)inMediaBox path:(CFStringRef) path
{
CGContextRef myOutContext = NULL;
CFURLRef url;
url = CFURLCreateWithFileSystemPath (NULL, path,
kCFURLPOSIXPathStyle,
false);
if (url != NULL) {
myOutContext = CGPDFContextCreateWithURL (url,
&inMediaBox,
NULL);
CFRelease(url);
}
return myOutContext;
}
The easiest way to convert the scrollview content into a PDF file is to have a content view as the first subview of the scrollview and using that view to take a snapshot of the scrollview. The code in Swift would look like this:
func generatePDFdata(withView view: UIView) -> NSData {
let pageDimensions = view.bounds
let outputData = NSMutableData()
UIGraphicsBeginPDFContextToData(outputData, pageDimensions, nil)
if let context = UIGraphicsGetCurrentContext() {
UIGraphicsBeginPDFPage()
view.layer.render(in: context)
}
UIGraphicsEndPDFContext()
return outputData
}
You can then use the outputData to write into a PDF file:
outputData.write(to: pdfFileUrl, atomically: true)
Related
Using iOS-htmltopdf, i am able to convert DOC to PDF but i want single page PDF from doc file.
The reason is some content of one page gets into another page so only one page.
In NDHTMLtoPDF.m i use these 2 line of code then PDF page size becomes double
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if (webView.isLoading) return;
long pageHeight = [[webView stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight;"]longLongValue];
self.pageSize = CGSizeMake(595, webView.scrollView.contentSize.height/2);
.........
.........
.........
}
Firstly convert DOC to PDF using NDHTMLtoPDF.
Below delegate method will be called
- (void)HTMLtoPDFDidSucceed:(NDHTMLtoPDF*)htmlToPDF
{
NSLog(#"HTMLtoPDF did succeed (%# / %#)", htmlToPDF, htmlToPDF.PDFpath);
NSURL *pptURL = [NSURL fileURLWithPath:htmlToPDF.PDFpath];
NSURLRequest *request = [NSURLRequest requestWithURL:pptURL];
[myWebView loadRequest:request];
//now merge whole pages to one PDF
[self MergeToOnePagePDF:pptURL];
}
Now add these method:
-(void)MergeToOnePagePDF:(NSURL *)pdfURL
{
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfURL);
int pageCount = CGPDFDocumentGetNumberOfPages(pdf);
CGPDFPageRef pageRef = CGPDFDocumentGetPage(pdf, 1);
CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFMediaBox);
float pageHeight = pageRect.size.height;
pageRect.size.height = pageRect.size.height * pageCount;
NSMutableData* pdfData = [[NSMutableData alloc] init];
CGDataConsumerRef pdfConsumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)pdfData);
CGContextRef pdfContext = CGPDFContextCreate(pdfConsumer, &pageRect, NULL);
CGPDFContextBeginPage(pdfContext, NULL);
CGContextTranslateCTM(pdfContext, 0, pageRect.size.height);
for (int i = 1; i <= pageCount; i++)
{
pageRef = CGPDFDocumentGetPage(pdf, i);
CGContextTranslateCTM(pdfContext, 0, -pageHeight);
CGContextDrawPDFPage(pdfContext, pageRef);
}
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFile = [documentsDirectory stringByAppendingPathComponent:#"destination.pdf"];
[pdfData writeToFile: pdfFile atomically: NO];
}
EDIT : Merging pages into one page PDF credit goes to #iPDFDev
I have three options for you probably you might get your answer in any one of them.
1)check this link.MonkeyBread
2) With Pdflab you can split, combine, reorganize Pdf's.
3) All you have to do is open the doc file in preview, apple + c copies the page that you are on, apple + n., apple + v and you have the single page pdf.
I hope these help you to some extent.
I have a little flow problem with my UICollectionView. I want to display PDF's thumbnails just like in Apple's iBook app, when I scroll my collection view I can see it's not really smooth. Here is the way I use to load my pictures :
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath: (NSIndexPath *)indexPath
{
GridCell *cell = [cv dequeueReusableCellWithReuseIdentifier:#"gridCell" forIndexPath:indexPath];
...
// Set Thumbnail
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if ([Tools checkIfLocalFileExist:cell.pdfDoc])
{
UIImage *thumbnail = [Tools generateThumbnailForFile:((PDFDocument *)[self.pdfList objectAtIndex:indexPath.row]).title];
dispatch_async( dispatch_get_main_queue(), ^{
[cell.imageView setImage:thumbnail];
});
}
});
...
return cell;
}
Method to get thumbnail :
+ (UIImage *)generateThumbnailForFile:(NSString *) fileName
{
// ----- Check if thumbnail already exist
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* thumbnailAddress = [documentsPath stringByAppendingPathComponent:[[fileName stringByDeletingPathExtension] stringByAppendingString:#".png"]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:thumbnailAddress];
if (fileExists)
return [UIImage imageWithContentsOfFile:thumbnailAddress];
// ----- Generate Thumbnail
NSString* filePath = [documentsPath stringByAppendingPathComponent:fileName];
CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:filePath];
CGPDFDocumentRef documentRef = CGPDFDocumentCreateWithURL(url);
CGPDFPageRef pageRef = CGPDFDocumentGetPage(documentRef, 1);
CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox);
UIGraphicsBeginImageContext(pageRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, CGRectGetMinX(pageRect),CGRectGetMaxY(pageRect));
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, -(pageRect.origin.x), -(pageRect.origin.y));
CGContextDrawPDFPage(context, pageRef);
// ----- Save Image
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(finalImage)];
[imageData writeToFile:thumbnailAddress atomically:YES];
UIGraphicsEndImageContext();
return finalImage;
}
Do you have any suggestion ?
Take a look at https://github.com/rs/SDWebImage. The library works great for async image loading particularly the method setImageWithURL:placeholderImage:
You can call that method and set a place holder with a loading image or blank png and once the image you are trying to retrieve is loaded it will fill in the place holder. This should speed up your app quite a bit.
I'm working on a pdf annotations application and i need to save the annotation so when i tried to save the annotations and the pdf content to a new pdf , the annotations are saved but the content of the pdf is not ? here is my function :
-(void)save_doc_as_pdf:(ReaderMainToolbar *)toolbar BackButton:(UIButton *)button
{
NSError *error;
NSString *PdfPath = [document.fileURL absoluteString];
NSString *newPath = [PdfPath stringByReplacingOccurrencesOfString:#"file://localhost" withString:#""];
NSString *NewPdfPath = [thenewPath stringByReplacingOccurrencesOfString:#".pdf" withString:#"_1.pdf"];
NSData *pdfData = [NSData dataWithContentsOfFile:[document.fileURL path] options:NSDataReadingUncached error:&error];
if (pdfData == nil) {
NSLog(#"data is nil !!!!");
}
if (error)
{
NSLog(#"%#", [error localizedDescription]);
return;
}
else
NSLog(#"Data has loaded successfully.");
//If fails to create the new file, returns
if (![[NSFileManager defaultManager] createFileAtPath:NewPdfPath contents:pdfData attributes:nil])
{
return;
}
NSURL *url = [NSURL fileURLWithPath:newPath];
CGPDFDocumentRef pdf_document = CGPDFDocumentCreateWithURL ((__bridge_retained CFURLRef) url);
size_t count = CGPDFDocumentGetNumberOfPages(pdf_document);
if (count == 0)
{
NSLog(#"PDF needs at least one page");
return;
}
CGRect paperSize = CGRectMake(0, 0,842, 1190);
UIGraphicsBeginPDFContextToFile(NewPdfPath , paperSize, nil);
// CGPDFPageRef page = CGPDFDocumentGetPage(document, 1);
UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// flip context so page is right way (landscape app)
CGContextScaleCTM(currentContext, 1, -1);
// Rotate the coordinate system (rotation = M_PI or -M_PI for landscape)
//CGContextRotateCTM(currentContext, rotation/ 2);
CGPDFPageRef page = CGPDFDocumentGetPage (pdf_document, 1); // grab page 1 of the PDF
CGContextDrawPDFPage (currentContext, page); // draw page 1 into graphics context
//flip context so annotations are right way
CGContextScaleCTM(currentContext, 1, -1);
//CGContextRotateCTM(currentContext, rotation / 2);
//Render the layer of the annotations view in the context
[startdraw.layer renderInContext:currentContext];
UIGraphicsEndPDFContext();
CGPDFDocumentRelease (pdf_document);
}
hello i find a solution for saving an annotaion on a pdf document and i want to shar it with you so here is the code :
-(void)save_the_pdf:(ReaderMainToolbar *)toolbar BackButton:(UIButton *)button{
NSMutableArray *URLsTableObject=[[NSMutableArray alloc] init];
NSMutableArray *URLsTable=[[NSMutableArray alloc] init];
NSUserDefaults *DataStoreUrls;
NSString *OriginalPdfName = [document.fileName stringByReplacingOccurrencesOfString:#".pdf" withString:#""];
NSString *OriginalPdfPath = [document.fileName stringByReplacingOccurrencesOfString:#".pdf" withString:#""];
NSString* thenewPath = [[NSBundle mainBundle] pathForResource:OriginalPdfPath ofType:#"pdf"];
NSString *NewPdfPath = [thenewPath stringByReplacingOccurrencesOfString:#".pdf" withString:#"_1.pdf"];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[[NSBundle mainBundle] URLForResource:OriginalPdfName withExtension:#"pdf"]);
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 == currentPage) {
[startdraw.layer renderInContext:ctx];
}
}
UIGraphicsEndPDFContext();
CGPDFDocumentRelease(pdf);
//pdf = nil;
if (![[NSFileManager defaultManager] createFileAtPath:NewPdfPath contents:data attributes:nil])
{
return;
}
// Do something with the 'data'...
DataStoreUrls=[NSUserDefaults standardUserDefaults];
if([DataStoreUrls objectForKey:#"ALLURLS"]!=NULL){
URLsTableObject=[DataStoreUrls objectForKey:#"ALLURLS"];
int index=[URLsTableObject count];
URLsTable=[[NSMutableArray alloc] initWithArray:URLsTableObject];
[URLsTable insertObject:NewPdfPath atIndex:index];
[DataStoreUrls setObject:URLsTable forKey:#"ALLURLS"];
}else{
[URLsTable addObject:NewPdfPath];
[DataStoreUrls setObject:URLsTable forKey:#"ALLURLS"];
}
[DataStoreUrls synchronize];
}
My client wants to share an image on Instagram. I have implemeted sharing image on instagram.But i could not share it with a special hashtag. Here is my code so far.
- (IBAction)sharePhotoOnInstagram:(id)sender {
UIImagePickerController *imgpicker=[[UIImagePickerController alloc] init];
imgpicker.delegate=self;
[self storeimage];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
CGRect rect = CGRectMake(0 ,0 , 612, 612);
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/15717.ig"];
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"file://%#", jpgPath]];
dic.UTI = #"com.instagram.photo";
dic.delegate = self;
dic = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
dic = [UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
dic.delegate = self;
[dic presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
// [[UIApplication sharedApplication] openURL:instagramURL];
}
else
{
// NSLog(#"instagramImageShare");
UIAlertView *errorToShare = [[UIAlertView alloc] initWithTitle:#"Instagram unavailable " message:#"You need to install Instagram in your device in order to share this image" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
errorToShare.tag=3010;
[errorToShare show];
}
}
- (void) storeimage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"15717.ig"];
UIImage *NewImg = [self resizedImage:picTaken :CGRectMake(0, 0, 612, 612) ];
NSData *imageData = UIImagePNGRepresentation(NewImg);
[imageData writeToFile:savedImagePath atomically:NO];
}
-(UIImage*) resizedImage:(UIImage *)inImage: (CGRect) thumbRect
{
CGImageRef imageRef = [inImage CGImage];
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
// There's a wierdness with kCGImageAlphaNone and CGBitmapContextCreate
// see Supported Pixel Formats in the Quartz 2D Programming Guide
// Creating a Bitmap Graphics Context section
// only RGB 8 bit images with alpha of kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst,
// and kCGImageAlphaPremultipliedLast, with a few other oddball image kinds are supported
// The images on input here are likely to be png or jpeg files
if (alphaInfo == kCGImageAlphaNone)
alphaInfo = kCGImageAlphaNoneSkipLast;
// Build a bitmap context that's the size of the thumbRect
CGContextRef bitmap = CGBitmapContextCreate(
NULL,
thumbRect.size.width, // width
thumbRect.size.height, // height
CGImageGetBitsPerComponent(imageRef), // really needs to always be 8
4 * thumbRect.size.width, // rowbytes
CGImageGetColorSpace(imageRef),
alphaInfo
);
// Draw into the context, this scales the image
CGContextDrawImage(bitmap, thumbRect, imageRef);
// Get an image from the context and a UIImage
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage* result = [UIImage imageWithCGImage:ref];
CGContextRelease(bitmap); // ok if NULL
CGImageRelease(ref);
return result;
}
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate
{
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
interactionController.delegate = self;
return interactionController;
}
- (void)documentInteractionControllerWillPresentOpenInMenu:(UIDocumentInteractionController *)controller
{
}
- (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller canPerformAction:(SEL)action
{
// NSLog(#"5dsklfjkljas");
return YES;
}
- (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller performAction:(SEL)action
{
// NSLog(#"dsfa");
return YES;
}
- (void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application
{
// NSLog(#"fsafasd;");
}
Note : This is working fine.
I have followed their documentation on http://instagram.com/developer/iphone-hooks/ but couldn't get better idea from it!. Now don't know what to do next step for sharing an image with hashtag and other information.
Secondly I want to retrieve all the images shared with a particular hashtag into the application.
Please guide me! Thanks in advance!
First, from iPhone Hooks, under 'Document Interaction':
To include a pre-filled caption with your photo, you can set the annotation property on the document interaction request to an NSDictionary containing an NSString under the key "InstagramCaption". Note: this feature will be available on Instagram 2.1 and later.
You'll need to add something like:
dic.annotation = [NSDictionary dictionaryWithObject:#"#yourTagHere" forKey:#"InstagramCaption"];
Second, you'll need to take a look at Tag Endpoints if you want to pull down images with a specific tag.
I am trying to combine 11 pdf files into a single pdf file.The following code i am using ,but in the final pdf only the first pdf is shown ...i nslogged the pdfurls and CGPDFDocumentRef in the loop and they are not nil all the time(in the loop).What may be the reason why only the first page is displayed in the final document
-(void)mergeDocuments
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *oldFile=[documentsDirectory stringByAppendingPathComponent:#"finalPdf.pdf"];
NSMutableData *data=[[NSMutableData alloc] init];
CGRect paperSize=CGRectMake(0,0,kDefaultPageWidth,kDefaultPageHeight);
UIGraphicsBeginPDFContextToData(data, paperSize, nil);
for (int pageNumber = 1; pageNumber <= 11; pageNumber++)
{
NSString *pdfPath = [[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"page_%d.pdf",pageNumber]] retain];
NSURL *pdfUrl = [[NSURL fileURLWithPath:pdfPath] retain];
UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGPDFDocumentRef newDocument = CGPDFDocumentCreateWithURL ((CFURLRef) pdfUrl);
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, pageNumber);
CGContextDrawPDFPage (currentContext, newPage);
newPage = nil;
CGPDFDocumentRelease(newDocument);
newDocument = nil;
[pdfUrl release];
}
NSURL *finalUrl=[NSURL URLWithString:oldFile];
UIGraphicsEndPDFContext();
[data writeToURL:finalUrl atomically:YES];
}
It looks like your code assumes that there is only one page in each document, however it is asking for page pageNumber from each file as it opens it, and is therefore asking for page 1 from page_1.pdf, page 2 from page_2.pdf, page 3 from page_3.pdf, etc...
If you just want the first page from each document change this:
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, pageNumber);
to this:
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, 1);
For what it's worth, I re-wrote your routine before I spotted this based on one that I already have (forgive me but it is in an ARC project so you'll have to re-do your memory management) as follows:
(NOTE: Error checking has been removed to make the code more readable!)
-(void)mergeDocuments {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *oldFilePath=[documentsDirectory stringByAppendingPathComponent:#"finalPdf.pdf"];
NSURL *oldFileUrl = [NSURL fileURLWithPath:oldFilePath];
CGContextRef context = CGPDFContextCreateWithURL((__bridge_retained CFURLRef)oldFileUrl, NULL, NULL);
for (int docNumber = 1; docNumber <= 11; docNumber++)
{
// Get the first page from each source document
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"page_%d.pdf",docNumber]];
NSURL *pdfUrl = [NSURL fileURLWithPath:pdfPath];
CGPDFDocumentRef pdfDoc = CGPDFDocumentCreateWithURL((__bridge_retained CFURLRef)pdfUrl);
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, 1);
CGRect pdfCropBoxRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
// Copy the page to the new document
CGContextBeginPage(context, &pdfCropBoxRect);
CGContextDrawPDFPage(context, pdfPage);
// Close the source files
CGContextEndPage(context);
CGPDFDocumentRelease(pdfDoc);
}
// Cleanup
CGContextRelease(context);
}
If what you want is all pages of all the source PDF files, your for loop is wrong.
You loop counter 'pageNumber' runs from 1 to 11. You are using the same variable to open the corresponding file as well as to fetch a page from that pdf.
So, your for loop will produce a pdf with
1st page of 1st pdf, 2nd page of 2nd pdf,....,11th page of 11th pdf
If your 2nd - 11th pdf files do not have as many pages, the final output will obviously have only the first page of first pdf.
You need 2 for loops. One to iterate through pdf files and the other to iterate through each page of every pdf file.
for (int documentNumber = 1; documentNumber <= 11; documentNumber++)
{
NSString *pdfPath = [[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"page_%d.pdf",documentNumber]] retain];
NSURL *pdfUrl = [[NSURL fileURLWithPath:pdfPath] retain];
UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGPDFDocumentRef newDocument = CGPDFDocumentCreateWithURL ((CFURLRef) pdfUrl);
int numberOfPages = CGPDFDocumentGetNumberOfPages(newDocument);
for (int pageNumber = 1; pageNumber <= numberOfPages; pageNumber++)
{
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, pageNumber);
CGContextDrawPDFPage (currentContext, newPage);
//any other page rendering
newPage = nil;
}
CGPDFDocumentRelease(newDocument);
newDocument = nil;
[pdfUrl release];
}