2016-03-15 2 views
0

Я ранее размещал related question на SO, но безрезультатно. Затем я изменил свой подход и создал PDF-файлы, все из которых имеют одинаковые размеры и т. Д. Все эти PDF-файлы также состоят только из одной страницы.Создать многостраничный PDF-файл из других PDF-файлов

Теперь я хотел бы объединить эти одностраничные PDF-файлы в один многостраничный PDF-файл. От here Я думаю, что я понял, какие шаги при создании многостраничного PDF-файла.

После выполнения приведенного ниже кода создается PDF-файл с ожидаемым именем файла, но PDF-файл состоит только из одной страницы и полностью пустой.

Я нахожусь здесь в уединении ... Пожалуйста, скажите мне, что я делаю неправильно! Да, я считаю, какой-то цикл будет работать здесь, но, честно говоря, LOOPS всегда получали лучше меня .... :(

Любая помощь будет принята с благодарностью!

О, и я ! едва Swift - пожалуйста, не бросайте Obj-C у меня;)

Вот мой код:

func CreateCombinedPDF() { 

    let pdf01 = String("\(newDetailsLogIdentifier)_PAGE01.pdf") 
    let pdf02 = String("\(newDetailsLogIdentifier)_PAGE02.pdf") 

    //STEPS IN CREATING A COMBINED PDF 

    // 1. CGPDFDocumentCreateWithURL 
    // 2. CGContextBeginPage 
    // 3. CGPDFDocumentGetPage 
    // 4. CGPDFContextCreateWithURL 
    // 5. CGContextDrawPDFPage 
    // 6. CGContextEndPage 
    // 7. CGPDFContextClose 

    var mediaBox:CGRect = CGRectMake(0, 0, 820, 1170) 
    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] 
    let combinedDocumentFileName = documentsURL.URLByAppendingPathComponent("\(newDetailsLogIdentifier)_COMBINED.pdf") 
    let fullPathCombinedDocument = combinedDocumentFileName.path! 
    let myCombinedDocumentURL = NSURL(fileURLWithPath: fullPathCombinedDocument) 
    let myContextCombinedDocument = CGPDFContextCreateWithURL(myCombinedDocumentURL, &mediaBox, nil) 

    let fileNamePDF01 = documentsURL.URLByAppendingPathComponent(pdf01) 
    let fullPathPDF01 = fileNamePDF01.path! 
    let urlPDF01 = NSURL(fileURLWithPath: fullPathPDF01) 
    let myContextPDF01 = CGPDFContextCreateWithURL(urlPDF01, &mediaBox, nil) 
    CGPDFContextBeginPage(myContextPDF01, nil) 
    //Here's my problem - I think... 
    CGContextDrawPDFPage(myContextPDF01, nil) 
    CGPDFContextEndPage(myContextPDF01) 

    let fileNamePDF02 = documentsURL.URLByAppendingPathComponent(pdf02) 
    let fullPathPDF02 = fileNamePDF02.path! 
    let urlPDF02 = NSURL(fileURLWithPath: fullPathPDF02) 
    let myContextPDF02 = CGPDFContextCreateWithURL(urlPDF02, &mediaBox, nil) 
    CGPDFContextBeginPage(myContextPDF02, nil) 
    //Here's my problem - I think... 
    CGContextDrawPDFPage(myContextPDF02, nil) 
    CGPDFContextEndPage(myContextPDF02) 

    CGPDFContextClose(myContextCombinedDocument) 

} 
+0

Ну, оказывается, что приведенный выше код не выполняет ничего, кроме перезаписи оригинальных одностраничных PDF-файлов - на пустые страницы! Мне здесь очень нужна помощь! –

ответ

1

Как уже упоминалось в предыдущих комментариях, код я отправил было дерьмо. Теперь я разобрался - создается многостраничный PDF-файл.

я до сих пор работать на этом цикле я уже упоминал, но сейчас это работает для меня (без петли):

func CreateCombinedPDF() { 

    //Set all constants and variables needed 
    var mediaBox:CGRect = CGRectMake(0, 0, 820, 1170) 
    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] 
    let combinedDocumentFileName = documentsURL.URLByAppendingPathComponent("\(newDetailsLogIdentifier)_COMBINED.pdf") 
    let fullPathCombinedDocument = combinedDocumentFileName.path! 
    let myCombinedDocumentURL = NSURL(fileURLWithPath: fullPathCombinedDocument) 

    let pdf01 = String("\(newDetailsLogIdentifier)_PAGE01.pdf") 
    let fileNamePDF01 = documentsURL.URLByAppendingPathComponent(pdf01) 
    let fullPathPDF01 = fileNamePDF01.path! 
    let urlPDF01 = NSURL(fileURLWithPath: fullPathPDF01) 
    let contextPDF01 = CGPDFDocumentCreateWithURL(urlPDF01) 
    let pdf01Page = CGPDFDocumentGetPage(contextPDF01,1) 

    let pdf02 = String("\(newDetailsLogIdentifier)_PAGE02.pdf") 
    let fileNamePDF02 = documentsURL.URLByAppendingPathComponent(pdf02) 
    let fullPathPDF02 = fileNamePDF02.path! 
    let urlPDF02 = NSURL(fileURLWithPath: fullPathPDF02) 
    let contextPDF02 = CGPDFDocumentCreateWithURL(urlPDF02) 
    let pdf02Page = CGPDFDocumentGetPage(contextPDF02,1) 

    // 1. Create the PDF context that will become the new PDF file 
    let myContextCombinedDocument = CGPDFContextCreateWithURL(myCombinedDocumentURL, &mediaBox, nil) 

    // 2. Insert pages 

    //Draw PAGE01.pdf 
    CGPDFContextBeginPage(myContextCombinedDocument, nil); 
    CGContextDrawPDFPage(myContextCombinedDocument, pdf01Page) 
    CGPDFContextEndPage(myContextCombinedDocument) 

    //Draw PAGE02.pdf 
    CGPDFContextBeginPage(myContextCombinedDocument, nil); 
    CGContextDrawPDFPage(myContextCombinedDocument, pdf02Page) 
    CGPDFContextEndPage(myContextCombinedDocument) 

    // 3. All pages inserted. Now close and save the new document. 
    CGPDFContextClose(myContextCombinedDocument) 
} 

Это не может быть элегантным, но он уверен, как ад работает!

Престижность в информации, которую я нашел here!

0

Быстродействующий код выше не работал для меня, поэтому я обратился к Objective-C для заинтересованных.

+(void) CreateCombinedPDF { 
    NSString *newDetailsLogIdentifier = @"filename"; 

    // Set all constants and variables needed 
    CGRect mediaBox = CGRectMake(0, 0, 820, 1170); 
    NSFileManager *fm = [NSFileManager defaultManager]; 
    NSURL *documentsURL = [fm URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0]; 
    NSURL *combinedDocumentFileName = [documentsURL URLByAppendingPathComponent:[NSString stringWithFormat:@"%@_COMBINED.pdf", newDetailsLogIdentifier]]; 
    NSString *fullPathCombinedDocument = combinedDocumentFileName.path; 
    NSURL *myCombinedDocumentURL = [NSURL fileURLWithPath:fullPathCombinedDocument]; 

    NSString *pdf01 = [NSString stringWithFormat:@"%@_PAGE01.pdf", newDetailsLogIdentifier]; 
    NSURL *fileNamePdf01 = [documentsURL URLByAppendingPathComponent:pdf01]; 
    NSString *fullPathPdf01 = fileNamePdf01.path; 
    NSURL *urlPDF01 = [NSURL fileURLWithPath:fullPathPdf01]; 
    CFURLRef cfurl = CFBridgingRetain(urlPDF01); 
    CGPDFDocumentRef contextPDF01 = CGPDFDocumentCreateWithURL(cfurl); 
    CGPDFPageRef pdf01Page = CGPDFDocumentGetPage(contextPDF01, 1); 

    NSString *pdf02 = [NSString stringWithFormat:@"%@_PAGE02.pdf", newDetailsLogIdentifier]; 
    NSURL *fileNamePdf02 = [documentsURL URLByAppendingPathComponent:pdf02]; 
    NSString *fullPathPdf02 = fileNamePdf02.path; 
    NSURL *urlPDF02 = [NSURL fileURLWithPath:fullPathPdf02]; 
    CFURLRef cfurl2 = CFBridgingRetain(urlPDF02); 
    CGPDFDocumentRef contextPDF02 = CGPDFDocumentCreateWithURL(cfurl2); 
    CGPDFPageRef pdf02Page = CGPDFDocumentGetPage(contextPDF02, 1); 

    // 1. Create the PDF context that will become the new PDF file 
    CGContextRef myContextCombinedDocument = CGPDFContextCreateWithURL(CFBridgingRetain(myCombinedDocumentURL), &mediaBox, nil); 

    // 2. Insert pages 

    // Draw PAGE01.pdf 
    CGPDFContextBeginPage(myContextCombinedDocument, nil); 
    CGContextDrawPDFPage(myContextCombinedDocument, pdf01Page); 
    CGPDFContextEndPage(myContextCombinedDocument); 

    // Draw PAGE02.pdf 
    CGPDFContextBeginPage(myContextCombinedDocument, nil); 
    CGContextDrawPDFPage(myContextCombinedDocument, pdf02Page); 
    CGPDFContextEndPage(myContextCombinedDocument); 

    // 3. All pages inserted. Now close and save the new document. 
    CGPDFContextClose(myContextCombinedDocument); 
}