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);
Related
I am working on a app which is highly dependent on saving images in document directory and retrieving it and displaying it on screen.
As soon as I display 5 -6 images in collection view the ap gets slowed up and suddenly receives memory warning and stopes functioning and app crashes.
I am using following code to display data
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
DocumentCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"DocumentCollectionViewCell"
forIndexPath:indexPath];
if(cell!=nil){
cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"DocumentCollectionViewCell" forIndexPath:indexPath];
}
Documents *documents = [arrTableData objectAtIndex:indexPath.row];
cell.imgView.contentMode = UIViewContentModeScaleAspectFit;
cell.imgContentView.layer.cornerRadius = 4.0f;
cell.imgContentView.layer.masksToBounds = YES;
cell.imgContentView.layer.borderColor = [UIColor lightGrayColor].CGColor;
cell.imgContentView.layer.borderWidth = .4f;
[cell.btnLockOrUnlock addTarget:self action:#selector(lockAction:) forControlEvents:UIControlEventTouchUpInside];
cell.btnLockOrUnlock.tag = indexPath.row;
// set count
cell.lblCount.text =[NSString stringWithFormat:#"%# Page",documents.imageCount];
cell.imgView.layer.cornerRadius = 6.0f;
cell.imgView.layer.masksToBounds = YES;
newDocDate = documents.issueDate;
// set image
NSString * passcode = documents.passcode;
if(passcode.length>3){
cell.bluredView.hidden = NO;
[cell.btnLockOrUnlock setImage:[UIImage imageNamed:#"lockWhite"] forState:UIControlStateNormal];
}
else{
[cell.btnLockOrUnlock setImage:[UIImage imageNamed:#"unlockWhite"] forState:UIControlStateNormal];
cell.bluredView.hidden = YES;
}
[cell.btnSelect addTarget:self action:#selector(cellSelectAction:) forControlEvents:UIControlEventTouchUpInside];
cell.btnSelect.tag = indexPath.row;
NSString *title = documents.title;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Fetch path for document directory
NSString * docDirectoryPath = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:title];
//-----------------path of document ------------------
NSString *filePath = [docDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"image%d.png",0]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
int i =0;
while (!fileExists) {
filePath = [docDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"image%d.png",i]];
fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
i++;
}
CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef) [NSURL fileURLWithPath:filePath], NULL);
// Create thumbnail options
CFDictionaryRef options = (__bridge CFDictionaryRef) #{
(id) kCGImageSourceCreateThumbnailWithTransform : #YES,
(id) kCGImageSourceCreateThumbnailFromImageAlways : #YES,
(id) kCGImageSourceThumbnailMaxPixelSize : #(cell.imgView.frame.size.height)
};
// Generate the thumbnail
CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options);
UIImage* uiImage = [[UIImage alloc] initWithCGImage:thumbnail]; //<--CRASH
cell.DocName.text = documents.docName;
//-----------------display image on cell------------------
cell.imgView.image = uiImage;
uiImage = nil;
uiImage = NULL;
documents = nil;
documents = nil;
title = nil;
thumbnail = nil;
src = nil;
options = nil;
filePath = nil;
paths = nil;
documentsDirectory = nil;
docDirectoryPath = nil;
return cell;
}
I am setting all the objects to nil.
I am using following code to save images
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Fetch path for document directory
folderName = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:folderName];
NSData *pngData = UIImagePNGRepresentation(arrImages[i]);
NSString *filePath = [folderName stringByAppendingPathComponent:[NSString stringWithFormat:#"image%d.png",i]]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
I save the original image from camera without any compression or resizing in document directory.
I am unable to understand the problem please help.
Thanks in advance.
It seems to be due to memory leaks, check your app using instruments and lacks tool.
CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef) [NSURL fileURLWithPath:filePath], NULL);
// Create thumbnail options
CFDictionaryRef options = (__bridge CFDictionaryRef) #{
(id) kCGImageSourceCreateThumbnailWithTransform : #YES,
(id) kCGImageSourceCreateThumbnailFromImageAlways : #YES,
(id) kCGImageSourceThumbnailMaxPixelSize : #(cell.imgView.frame.size.height)
};
// Generate the thumbnail
CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options);
UIImage* uiImage = [[UIImage alloc] initWithCGImage:thumbnail]; //<--CRASH
CFFoundation objects follow similar memory management rules (If you create or copy you need to release it) of Obj-C before ARC (ARC doesn't manage core foundation objects).
In the code you have shown I see that you aren't releasing the CGImageRef and the CGImageSourceRef, this create two leaks and probably the crash.
Collection view cells are recycled thus the number of image opened in memory are basically the number of cells you are seeing on screen they should be the cause of your crash.
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]];
}
Hi i need to generate a pdf file of multiple pages with array of multiple images can any one help me with sample code please?
I slightly changed the previous solution. This method accept the name for the new file and an array of images and returns the absolute path to the pdf.
- (NSString *)createPdfWithName: (NSString *)name array:(NSArray*)images {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSString *pdfFileName = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.pdf",name]];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
for (int index = 0; index <[images count] ; index++) {
UIImage *pngImage=[images objectAtIndex:index];;
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, (pngImage.size.width), (pngImage.size.height)), nil);
[pngImage drawInRect:CGRectMake(0, 0, (pngImage.size.width), (pngImage.size.height))];
}
UIGraphicsEndPDFContext();
return pdfFileName;
}
You can use these methods to generate a PDF file containing images:
- (void) generatePdfWithFilePath: (NSString *)thefilePath
{
NSArray *pathsImage = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [pathsImage objectAtIndex:0];
NSString *dataPath = [docspath stringByAppendingPathComponent:folder];
NSString *imagepath=[dataPath stringByAppendingPathComponent:imageName];
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
NSInteger currentPage = 0;
BOOL done = NO;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *folder=[NSString stringWithFormat:#"ImageFolder"];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:folder];
UIImage *imgBrush = [UIImage imageWithContentsOfFile:imagepath];
for (int i=0; i<directoryContent.count; i++) {
[self drawImage:imgBrush];
}
}
- (void) drawImage :(UIImage*) imgBrush
{
if (imgBrush.size.width > pdfpageSize.width || imgBrush.size.height > pdfpageSize.height) {
[imgBrush drawInRect:CGRectMake((pdfpageSize.width/2)-(imgBrush.size.width/4), (pdfpageSize.height/2)-(imgBrush.size.height/4), imgBrush.size.width/2, imgBrush.size.height/2)];
} else {
[imgBrush drawInRect:CGRectMake((pdfpageSize.width/2)-(imgBrush.size.width/2), (pdfpageSize.height/2)-(imgBrush.size.height/2), imgBrush.size.width, imgBrush.size.height)];
}
}
Hey here is another method that you can use to render images in a PDF through code:
-(void)drawImagesToPdf:(UIImageView *)button
{
CGSize pageSize = CGSizeMake(button.frame.size.width*5, button.frame.size.height*5+30);
NSLog(#"page size %#",NSStringFromCGSize(pageSize));
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectMake(0, 0, button.frame.size.width, button.frame.size.height*3), nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0.0, pageSize.width, pageSize.height), nil);
NSArray *arrImages = [NSArray arrayWithObjects:#"3.png", #"4.png", #"5.png", #"6.png", nil];
float y = 220.0;
for (int i=0; i<arrImages.count; i++) {
UIImage * myPNG = [UIImage imageNamed:[arrImages objectAtIndex:i]];
[myPNG drawInRect:CGRectMake(50.0, y, myPNG.size.width, myPNG.size.height)];
y += myPNG.size.height + 20;
}
UIGraphicsEndPDFContext();
}
Try my updated code...
Hope this is helpful to you...
All the best..!!!
Make an array of actual images not names.
NSMutableArray *arr=[[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:#"image1.png"],[UIImage imageNamed:#"image2.png"],nil];
use this and make sure your application bundle contain images with names image1.png and image2.png
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.
In my application there is a WebView with HTML contents. Contents is of 3 page in WebView .
Now i want to convert WebView content in PDF. I have created 3 image from the WebView content. Now i want to create pdf using these 3 image. Each image should one page of PDF. But it resulting as single page image. So when i am taking print then content is cut off.
I am using this,
CGSize pageSize = CGSizeMake(612, 2324);
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
double currentHeight = 0.0;
for (int index = 1; index <= imageName ; index++)
{
NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png", index]];
UIImage *pngImage = [UIImage imageWithContentsOfFile:pngPath];
[pngImage drawInRect:CGRectMake(0, currentHeight, pageSize.width, pngImage.size.height)];
currentHeight += pngImage.size.height;
}
UIGraphicsEndPDFContext();
What i am doing wrong with this code.
THanks
/*For call method*/
[self createPdfWithName:#"sam" array:[NSArray arrayWithObjects:[UIImage imageNamed:#"01.png"],[UIImage imageNamed:#"02.png"], nil]];
/*Create New Pdf*/
- (NSString *)createPdfWithName: (NSString *)name array:(NSArray*)images
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSString *pdfFileName = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.pdf",name]];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
for (int index = 0; index <[images count] ; index++)
{
UIImage *pngImage=[images objectAtIndex:index];;
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, (pngImage.size.width), (pngImage.size.height)), nil);
[pngImage drawInRect:CGRectMake(0, 0, (pngImage.size.width), (pngImage.size.height))];
}
UIGraphicsEndPDFContext();
return pdfFileName;
}
func createPDFS(arrImages: [UIImage]) -> NSData? {
var pageHeight = 0.0
var pageWidth = 0.0
for img in arrImages
{
pageHeight = pageHeight+Double(img.size.height)
if Double(img.size.width) > pageWidth
{
pageWidth = Double(img.size.width)
}
}
let pdfData = NSMutableData()
let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!
var mediaBox = CGRect.init(x: 0, y: 0, width: pageWidth, height: pageHeight)
let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!
for img in arrImages
{
var mediaBox2 = CGRect.init(x: 0, y: 0, width: img.size.width, height: img.size.height)
pdfContext.beginPage(mediaBox: &mediaBox2)
pdfContext.draw(img.cgImage!, in: CGRect.init(x: 0.0, y: 0, width: pageWidth, height: Double(img.size.height)))
pdfContext.endPage()
}
return pdfData
}
CGSize pageSize = CGSizeMake(612, 2324);
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
double currentHeight = 0.0;
for (int index = 1; index <= imageName ; index++)
{
NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png", index]];
UIImage *pngImage = [UIImage imageWithContentsOfFile:pngPath];
// TODO: See Here
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pngImage.size.height), nil);
[pngImage drawInRect:CGRectMake(0, currentHeight, pageSize.width, pngImage.size.height)];
//currentHeight += pngImage.size.height;
}
UIGraphicsEndPDFContext();