объединение нескольких документов PDF в один документ не работает - PullRequest
2 голосов
/ 12 марта 2012

Я пытаюсь объединить 11 PDF-файлов в один PDF-файл. Следующий код, который я использую, но в окончательном PDF-файле отображается только первый PDF-файл. не все время ноль (в цикле). По какой причине в итоговом документе отображается только первая страница

-(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];
    }

Ответы [ 2 ]

3 голосов
/ 12 марта 2012

Похоже, ваш код предполагает, что в каждом документе есть только одна страница, однако он запрашивает страницу pageNumber для каждого файла при его открытии, и поэтому запрашивает страницу 1 из page_1.pdf, страница 2.из page_2.pdf, стр. 3 из page_3.pdf и т. д. *

Если вы хотите, чтобы первая страница каждого документа была изменена, то:

CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, pageNumber);

на:

CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, 1);

Для чего бы это ни стоило, я переписал вашу рутину, прежде чем заметил ее на основе того, что у меня уже есть (извините, но это в проекте ARC, так что вам придется заново выполнять управление памятью) следующим образом:

(ПРИМЕЧАНИЕ. Проверка ошибок была удалена, чтобы сделать код более читабельным!)

-(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);
}
1 голос
/ 13 марта 2012

Если вам нужны все страницы всех исходных PDF-файлов, ваш цикл for неверен.

Счетчик цикла 'pageNumber' работает от 1 до 11. Вы используете ту же переменную, чтобы открытьсоответствующий файл, а также получить страницу из этого PDF.Таким образом, ваш цикл for создаст PDF с

1-я страница 1-го PDF, 2-я страница 2-го PDF, ...., 11-я страница 11-го PDF

Если ваши 2-11 файлы PDF не имеют столько страниц, конечный вывод, очевидно, будет иметь только первую страницу первого pdf.

Вам нужно 2 для циклов.Один для перебора файлов PDF, а другой для перебора каждой страницы каждого файла PDF.

    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];            
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...