How to Save Created PDF in Document Folder and Merge in iOS

How to save created PDF in document folder and merge in iOS

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);

Where to store a created PDF File?

You should read about the various places on the file system that you can create files. One of these is the documents path, an example is below.

- (NSString *)documentPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return documentPath;
}

NSString * newFilePath = [[self documentPath] stringByAppendingPathComponent:@"name.pdf"];

combining multiple pdf documents into single document not working

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);
}

Download PDF file and save in document directory

You need to move the file to your custom location after the download. Implement URLSessionDownloadDelegate and you will receive the location of your downloaded file.

Delegate method:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)

Code to move the file:

do {
let documentsURL = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)

let savedURL = documentsURL.appendingPathComponent("yourCustomName.pdf")
try FileManager.default.moveItem(at: location, to: savedURL)
} catch {
print ("file error: \(error)")
}

To learn more refer to this repo.

Is it possible to combine multiple pdf files into a single pdf file programmatically in iphone?

Yes you can do that. Please follow the below code

//Open a pdf context for the single file
UIGraphicsBeginPDFContextToFile(oldFile, paperSize, nil);

//Run a loop to the number of pages you want
for (pageNumber = 1; pageNumber <= count; pageNumber++)
{
//Open a pdf page context
UIGraphicsBeginPDFPageWithInfo(paperSize, nil);

//Get graphics context to draw the page
CGContextRef currentContext = UIGraphicsGetCurrentContext();

//Flip and scale context to draw the pdf correctly
CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);

//Get document access of the pdf from which you want a page
CGPDFDocumentRef newDocument = CGPDFDocumentCreateWithURL ((CFURLRef) newUrl);

//Get the page you want
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, pageNumber);

//Drawing the page
CGContextDrawPDFPage (currentContext, newPage);

//Clean up
newPage = nil;
CGPDFDocumentRelease(newDocument);
newDocument = nil;
newUrl = nil;

}

UIGraphicsEndPDFContext();

So you have to write necessary condition of taking appropriate pages from appropriate pdf before draw the page. You have created a pdf from multiple sources!



Related Topics



Leave a reply



Submit