从iOS中的文本生成多页PDF

时间:2015-11-20 00:54:13

标签: ios objective-c pdf

我是以编程方式从带有标题和正文的详细视图创建PDF文件,如果文本对于一个页面来说太长,则需要对多个PDF页面执行此操作。

我到目前为止尝试的是在cleanText中创建一个单词数组,并通过每次检查高度循环,当页面足够大时,创建一个新页面。

这就是我所拥有的:

- (void) generatePdf: (NSString *)thefilePath :(NSString *) theHeader :(NSString *) theText :(UIImage *) theImage
{

    UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);

    int currentPage = 0;

    // maximum height and width of the content on the page, byt taking margins into account.
    CGFloat maxWidth = kDefaultPageWidth - 2*kBorderInset-2*kMarginInset;
    CGFloat maxHeight = kDefaultPageHeight - 2*kBorderInset - 2*kMarginInset;

    UIFont *font = [UIFont systemFontOfSize:14.0];
    CGFloat currentPageY = 0;

    NSString *cleanText;
    const char *utfString = [theText UTF8String];
    printf ("Converted string = %s\n", utfString);
    cleanText = [NSString stringWithUTF8String:utfString];

    // Mark the beginning of a new page.
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
    currentPageY = kMarginInset;

    // iterate through the words, adding to the pdf each time.
    NSArray *words = [cleanText componentsSeparatedByString:@" "];
    NSString *word;

    for (word in words)
    {
        // before we render any text to the PDF, we need to measure it, so we'll know where to render the next line.
        CGSize size = [word sizeWithFont:font constrainedToSize:CGSizeMake(maxWidth, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];

        // if the current text would render beyond the bounds of the page,
        // start a new page and render it there instead
        if (size.height + currentPageY > maxHeight) {

            // create a new page and reset the current page's Y value
            UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
            currentPageY = kMarginInset;
        }

        // render the text
        [word drawInRect:CGRectMake(kMarginInset, currentPageY, maxWidth, maxHeight) withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];

        currentPageY += size.height;
        // increment the page number.

    }
    currentPage++;

    // end and save the PDF.
    UIGraphicsEndPDFContext();

}

0 个答案:

没有答案