Помогите создать PDF в Кварце - PullRequest
0 голосов
/ 26 сентября 2011

Я читаю Руководство по рисованию и печати для iOS (http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GeneratingPDF/GeneratingPDF.html#//apple_ref/doc/uid/TP40010156-CH10-SW1). Я пытаюсь немного его изменить, чтобы получить то, что мне нужно. Я в основном пытаюсь нарисовать цветной прямоугольник, текст из NSString другой цветной прямоугольник, второй блок текста из NSString. Я создаю два установщика фреймов, по одному для каждой строки, и дважды вызываю метод renderPage :. Однако он рисует мой текст в перевернутом виде, внизу экрана, и Я не уверен, почему. (Я поставил некоторые вопросы в комментариях //, чтобы понять, почему код работает так, как он работает, и чего мне не хватает, чтобы понять, почему он не работает). Спасибо!

 CFAttributedStringRef overviewText = CFAttributedStringCreate(NULL, (CFStringRef)overview, NULL);
    CFAttributedStringRef resultText = CFAttributedStringCreate(NULL, (CFStringRef)result, NULL);
    if (overviewText != NULL || resultText != NULL) {
        CTFramesetterRef overviewFramesetter = CTFramesetterCreateWithAttributedString(overviewText);
        CTFramesetterRef resultFramesetter = CTFramesetterCreateWithAttributedString(resultText);
        if (overviewFramesetter != NULL  || resultFramesetter != NULL) {
            // Create the PDF context using the default page size of 612 x 792.
            UIGraphicsBeginPDFContextToFile(filePath, CGRectZero, nil);

            CFRange currentRange = CFRangeMake(0, 0);
            NSInteger currentPage = 0;
            BOOL done = NO;

            do {
                // Mark the beginning of a new page.
                UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, PDF_WIDTH, PDF_HEIGHT), nil);

                [self drawPDFTitle:fileName];
                [self drawRectangleAtPosition:CGPointMake(MARGIN, 50)];

                // Draw a page number at the bottom of each page
                currentPage++;
                [self drawPageNumber:currentPage];

                // Render the current page and update the current range to
                // point to the beginning of the next page.
                currentRange = [self renderPage:currentPage withTextRange:currentRange andFramesetter:overviewFramesetter];
                NSLog(@"%ld, %ld", currentRange.location, currentRange.length);

            // at first I tried doing this, but would get an error at the CFRelease in renderPage method.  I'm not sure as to why I get the error since the function renderPage: seems to be the method to write the data to the PDF context.
currentRange = [self renderPage:currentPage withTextRange:currentRange andFramesetter:resultFramesetter];

                // If we're at the end of the text, exit the loop.
                if (currentRange.location == CFAttributedStringGetLength((CFAttributedStringRef)overviewText))
                    done = YES;
            } 
            while (!done);

            do {
                // I do not know why I would need to flip the context again since the method renderPage: already does this for me right?
                //CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, PDF_HEIGHT);
                //CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
                currentRange = [self renderPage:currentPage withTextRange:currentRange andFramesetter:resultFramesetter];
                NSLog(@"2nd loop: %ld, %ld", currentRange.location, currentRange.length);
                if (currentRange.location == CFAttributedStringGetLength((CFAttributedStringRef)overviewText))
                    done = YES;
            }
            while (!done);

            // Close the PDF context and write the contents out.
            UIGraphicsEndPDFContext();

            // Release the framewetter.
            CFRelease(overviewFramesetter);

        } 

1 Ответ

0 голосов
/ 27 сентября 2011

Вам придется преобразовать координаты PDF, потому что система координат PDF отличается от системы координат кварца (ось Y перевернута). Подробнее см. В http://developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_overview/dq_overview.html ( Кварцевые 2D системы координат ).

Вы можете перевести, используя следующий код-

CGContextTranslateCTM(pdfContext, 0.0, pageRect.size.height);
CGContextScaleCTM(pdfContext, 1.0, -1.0);
...