I have one image array and I am trying to create pdf with that images.how can i create multiple pages pdf file.
I checked one tutorial but its not working for me.
How to create a multiple page PDF in ios6?
Please help me
This works for me:
NSArray *pageArray = yourImageArray;
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0, 0, 595, 842), nil);
for (UIImage *theImage in pageArray) {
UIGraphicsBeginPDFPage();
NSData *jpegData = UIImageJPEGRepresentation(theImage, 0.5);
CGDataProviderRef dp = CGDataProviderCreateWithCFData((__bridge CFDataRef)jpegData);
CGImageRef cgImage = CGImageCreateWithJPEGDataProvider(dp, NULL, true, kCGRenderingIntentDefault);
[[UIImage imageWithCGImage:cgImage] drawInRect:CGRectMake(0, 0, theImage.size.width, theImage.size.height)];
}
UIGraphicsEndPDFContext();
return pdfData;
For starting each new page in the pdf, use
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageWidth, pageHeight), nil);
Related
I want to add the signature on existing pdf. I have done this in following way:
1) Load existing pdf on UIView say mainView.
2) Add a signature image on mainView.
3) Call a following function
-(NSMutableData *)getPDFDatafromUIView
{
DebugLog(#"");
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, mainView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
mainView.layer renderInContext:pdfContext];
// remove PDF rendering context
UIGraphicsEndPDFContext();
return pdfData;
}
4) This function block your UI for a while, so call it on new thread
[NSThread detachNewThreadSelector:#selector(launchExportViewForExportDrawing) toTarget:self withObject:nil];
Using above method I get a pdf data with signature which contain the old pdf data too.
But for above method I must need to show the pdf in UIView. If I want do the above thing without loading on UIView, without showing pdf to user, How do I do that?
I am able to add a Image on pdf with creating the new pdf page. How do I add a image on existing pdf?
I have solved by creating the new PDF and drawing the pdf data and signature on it. Please refer following code:
// For adding the Siganture we need to wite the content on new PDF
-(void) addSignature:(UIImage *) imgSignature onPDFData:(NSData *)pdfData {
NSMutableData* outputPDFData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)outputPDFData);
CFMutableDictionaryRef attrDictionary = NULL;
attrDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attrDictionary, kCGPDFContextTitle, CFSTR("My Doc"));
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, NULL, attrDictionary);
CFRelease(dataConsumer);
CFRelease(attrDictionary);
CGRect pageRect;
// Draw the old "pdfData" on pdfContext
CFDataRef myPDFData = (__bridge CFDataRef) pdfData;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
CGDataProviderRelease(provider);
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);
pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGContextBeginPage(pdfContext, &pageRect);
CGContextDrawPDFPage(pdfContext, page);
// Draw the signature on pdfContext
pageRect = CGRectMake(0, 0,imgSignature.size.width , imgSignature.size.height);
CGImageRef pageImage = [imgSignature CGImage];
CGContextDrawImage(pdfContext, pageRect, pageImage);
// release the allocated memory
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);
// write new PDFData in "outPutPDF.pdf" file in document directory
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pdfFilePath =[NSString stringWithFormat:#"%#/outPutPDF.pdf",docsDirectory];
[outputPDFData writeToFile:pdfFilePath atomically:YES];
}
Rohit Answer is working perfectly,But it works only single page so i just Added some code for all pages displaying with image(image shown in single page reaming pages are looks same).Thanks #Rohit
NSString *path = [[NSBundle mainBundle] pathForResource:#"PartB" ofType:#"pdf"];
NSURL *docURL = [NSURL fileURLWithPath:path];
NSString *pdfName = [NSString stringWithFormat:#"%#",docURL];
NSLog(#"pdfName: %#", pdfName);
NSData *pdfData = [NSData dataWithContentsOfFile:path];
NSURL *pdfURL = [[NSBundle mainBundle] URLForResource:#"PartB.pdf" withExtension:nil];
CGPDFDocumentRef pdf1 = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
long pageCount = CGPDFDocumentGetNumberOfPages(pdf1);
NSLog(#"the page count %ld",pageCount);
NSMutableData* outputPDFData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)outputPDFData);
CFMutableDictionaryRef attrDictionary = NULL;
attrDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attrDictionary, kCGPDFContextTitle, CFSTR("My Doc"));
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, NULL, attrDictionary);
CFRelease(dataConsumer);
CFRelease(attrDictionary);
CGRect pageRect;
// Draw the old "pdfData" on pdfContext
CFDataRef myPDFData = (__bridge CFDataRef) pdfData;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
CGDataProviderRelease(provider);
for (int k=1; k<=pageCount; k++) {
CGPDFPageRef page3 = CGPDFDocumentGetPage(pdf, k);
pageRect = CGPDFPageGetBoxRect(page3, kCGPDFMediaBox);
CGContextBeginPage(pdfContext, &pageRect);
CGContextDrawPDFPage(pdfContext, page3);
if (k==pageSelect) {
pageRect = CGRectMake(0, 0,100 , 100);
CGImageRef pageImage = [mainImage.image CGImage];
CGContextDrawImage(pdfContext, pageRect, pageImage);
}
CGPDFContextEndPage(pdfContext);
}
CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);
// write new PDFData in "outPutPDF.pdf" file in document directory
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pdfFilePath =[NSString stringWithFormat:#"%#/outPutPDF.pdf",docsDirectory];
[outputPDFData writeToFile:pdfFilePath atomically:YES];
NSLog(#"save the pdf %#",pdfFilePath);
I'm not sure I understand your problem completely. From what I can tell you have a UIView that you're rendering onto a PDF document, and you want to add a signature image and not show it to the user.
If you're trying to add a "signature image" to your pdf, you can add a UIImageView to the UIView that you're rendering to the pdf.
If you don't want the user to see the UIView in the mean time, you could change it's origin to somewhere off bounds, for example:
CGRect originalFrame = mainView.frame;
CGRect newFrame = mainView.frame;
newFrame.origin.x = -newFrame.size.width;
newFrame.origin.y = -newFrame.size.height;
mainView.frame = newFrame;
//do all your PDF stuff here
mainView.frame = originalFrame;
I hope that helps. If it doesn't, please clarify the problem :)
I am successfully displaying text, but how can i display image in the pdf file ?
Actually I am new to pdf conversion
Thanks in advance.
i do it this way, my basic image is in a NSData object:
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0, 0, 2480, 3508), nil);
UIImage *aImg = [UIImage imageWithData:myImageData];
UIGraphicsBeginPDFPage();
NSData *jpegData = UIImageJPEGRepresentation(aImg, 0.5);
CGDataProviderRef dp = CGDataProviderCreateWithCFData((__bridge CFDataRef)jpegData);
CGImageRef cgImage = CGImageCreateWithJPEGDataProvider(dp, NULL, true, kCGRenderingIntentDefault);
[[UIImage imageWithCGImage:cgImage] drawInRect:CGRectMake(0, 0, aImg.size.width, aImg.size.height)];
UIGraphicsEndPDFContext();
return pdfData;
I have a NSMutableData which contains pdf data. I want to delete certain pages from the pdf and return the pdf. I have tried creating the CGPDFContext, CGPDFPageRef, etc, but nothing really worked out. I have the below code, Can someone help me to fill the 3 steps.
-(NSMutableData *)deletePagesofPDF:(NSMutableData *)data withStartPage:(int)startpage withEndPage:(int)endpage{
NSData *data1 = data;
CFDataRef myPDFData = (__bridge CFDataRef)data1;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
//step 1 delete pages from startpage to endpage.
//step 2 save pdf
//step 3 convert pdf back to NSMutabledata
return data;
}
Edit 1
I have decided to change my strategy. Instead of deleting the pages, i am now creating a new pdf with only the pages i require from another PDF. Please see the code below, somehow it crashes while creating the pdf context. error is : address doesn't contain a section that points to a section in a object file. I could not go past creating the context. Please correct me if there is something wrong after creating the context.
-(void)saveNSDataToPDFFile:(NSMutableData *)data{
NSData *data1 = data;
CFDataRef myPDFData = (__bridge CFDataRef)data1;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
CGPDFPageRef newPage = CGPDFDocumentGetPage(pdf, 2);
NSMutableData *pdfData = [[NSMutableData alloc] init];
CGRect mediaBox = CGRectMake(0, 0, 850, 1100);
CGContextRef pdfContext = CGPDFContextCreate((__bridge CGDataConsumerRef)(pdfData),&mediaBox,NULL);
CGPDFContextBeginPage (pdfContext,nil);
CGContextDrawPDFPage(pdfContext, newPage);
CGPDFContextClose(pdfContext);
[pdfData writeToFile:[self getDBPathPDf:#"Rajashekar.pdf"] atomically:YES];
}
EDIT 2
Sorry about my long post.
I can save the pdf file now without crashing but i cannot see the data inside the pdf. It just shows a medium sized box with "PDF" written inside it. Where am i going wrong?
-(void)saveNSDataToPDFFile:(NSMutableData *)data{
NSData *data1 = data;
CFDataRef myPDFData = (__bridge CFDataRef)data1;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
CGPDFPageRef newPage = CGPDFDocumentGetPage(pdf, 2);
NSMutableData *pdfData = [[NSMutableData alloc] init];
CGRect mediaBox = CGRectMake(0, 0, 850, 1100);
CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)pdfData);
CGContextRef pdfContext = CGPDFContextCreate(consumer,&mediaBox,NULL);
if (pdfContext)
{
CGPDFContextBeginPage (pdfContext,nil);
CGContextDrawPDFPage(pdfContext, newPage);
CGPDFContextClose(pdfContext);
[pdfData writeToFile:[self getDBPathPDf:#"Rajashekar.pdf"] atomically:YES];
}
}
EDIT 3
Its working....:) i forgot to CGPDFContextEndPage(pdfContext); before i closed the context.
I have a muti page pdf document stored on local storage. I want to extract any page out of that pdf doc and convert it into NSData to attach it with 'MFMailComposeViewController'. With the following lines of code, I can easily retrive the required page...
CGPDFDocumentRef pdfDoc=CGPDFDocumentCreateWithURL(pdfURL);
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, pageNumber);
But I am unable to find a way to convert pdfPage into NSData so that I can attach it with mail.
NOTE: The requirement is to attach page in PDF format, so please DON'T suggest converting PDF into PNG or JPEG.
CGPDF is primarily for drawing from and to PDF, not for converting PDF data. Therefore, if you want to extract a page, you'll have to draw it. Use for example:
// input
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)inputData);
CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(provider);
CGPDFPageRef page = CGPDFDocumentGetPage(document, pageIndex);
CGRect mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
// output
CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)outputData);
CGContextRef context = CGPDFContextCreate(consumer, &mediaBox, NULL);
// draw
CGContextBeginPage(context, &mediaBox);
CGContextDrawPDFPage(context, page);
CGContextEndPage(context);
// cleanup
CGDataProviderRelease(provider);
CGPDFDocumentRelease(document);
CGDataConsumerRelease(consumer);
CGContextRelease(context);
Here is what you do :
NSMutableData *pdfData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);
const CGRect mediaBox = CGRectMake(0.0f, 0.0f, drawingWidth, drawingHeight);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &mediaBox, NULL);
UIGraphicsPushContext(pdfContext);
CGContextBeginPage(pdfContext, &mediaBox);
CGContextDrawPDFPage(pdfcontext, pdfPage);
CGContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
UIGraphicsPopContext();
CGContextRelease(pdfContext);
CGDataConsumerRelease(dataConsumer);
// Mail part
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
mailViewController.mailComposeDelegate = self;
NSString *mime=#"application/pdf";
[mailViewController setSubject:#"Subject"];
[mailViewController setMessageBody:#"Message Body" isHTML:NO];
[mailViewController addAttachmentData:[pdfData copy] mimeType:mime fileName:#"page.pdf"];
[self presentModalViewController:mailViewController animated:YES];
i render Thumbnails of newly recieved PDF Document to the Documents-Directory.
I'm using the following code:
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("thedoc.pdf"), NULL, NULL);
CGPDFDocumentRef bookPDF = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
UIGraphicsBeginImageContext(CGSizeMake(100, 130));
NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(bookPDF);
CGContextRef context = UIGraphicsGetCurrentContext();
for(int i = 0; i < totalNum; i++ ) {
CGRect arect = CGRectMake(0,0,200,282);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, 141);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetGrayFillColor(context, 1.0, 1.0);
CGContextFillRect(context, arect);
// Grab the first PDF page
CGPDFPageRef page = CGPDFDocumentGetPage(bookPDF, i + 1);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, arect, 0, true);
// And apply the transform.
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, page);
// Create the new UIImage from the context
UIImage* thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
if (thumbnailImage == nil) {
NSLog(#"ERROR during creation of PNG");
}
// SAVE THE IMAGE TO DOCUMENTS-DIRECTORY
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"%#/thumbPage%i.png",theLocalFolder ,i]];
// Write image to PNG
BOOL writtenBool = [UIImagePNGRepresentation(thumbnailImage) writeToFile:pngPath atomically:YES];
// END SAVE THE IMAGE TO DOCUMENT-DIRECTORY
CGContextRestoreGState(context);
NSLog(#"Rendering PDF-Thumbnail %i (%i): %#", i, writtenBool, [NSString stringWithFormat:#"%#/thumbPage%i.png",theLocalFolder ,i]);
}
There is no error in Console, but the PNGs are not stored to the documents-Directory. The BOOL
writtenBool
is "0", what means that the write-action was not succuessful. I don't know why. I write the path in
pngPath
also to the console and the path is correct. If i open a terminal and write
open <<copyed path from console>>
it opens the correct path in finder.
What could cause this not to work? I had a look at the api but there seems to be no
error:
for UIImagePNGRepresentation: writeToFile:
Thanks for your help!
UIImagePNGRepresentation(thumbnailImage) return a NSData object
for NSData object, you can use these methods:
writeToFile:atomically:,
writeToFile:options:error:,
writeToURL:atomically:,
writeToURL:options:error:,
so, you can try use code like BOOL writtenBool = [UIImagePNGRepresentation(thumbnailImage) writeToFile:pngPath options:NSDataWritingAtomic error:&error]; to see what happened.