如何从textView创建多页PDF?

4

我从我的 iPhone 应用程序生成了一个 PDF 文件,虽然大多数文档只有一页,但我想能够检测文本是否将超出“边距”,如果是,则将其添加到下一页。 我是新手,不太确定如何做到这一点。

以下是代码。 有什么建议吗?

- (void) drawBorder
{
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    UIColor *borderColor = [UIColor grayColor];

    CGRect rectFrame = CGRectMake(kBorderInset, kBorderInset, pageSize.width-kBorderInset*2, pageSize.height-kBorderInset*2);

    CGContextSetStrokeColorWithColor(currentContext, borderColor.CGColor);
    CGContextSetLineWidth(currentContext, kBorderWidth);
    CGContextStrokeRect(currentContext, rectFrame);
}

- (void)drawPageNumber:(NSInteger)pageNumber
{
    NSString* pageNumberString = [NSString stringWithFormat:@"Page %d", pageNumber];
    UIFont* theFont = [UIFont systemFontOfSize:12];

    CGSize pageNumberStringSize = [pageNumberString sizeWithFont:theFont
                                               constrainedToSize:pageSize
                                                   lineBreakMode:UILineBreakModeWordWrap];

    CGRect stringRenderingRect = CGRectMake(kBorderInset,
                                            pageSize.height - 40.0,
                                            pageSize.width - 2*kBorderInset,
                                            pageNumberStringSize.height);

    [pageNumberString drawInRect:stringRenderingRect withFont:theFont lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentCenter];
}

- (void) drawHeader:(NSString *)header
{
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);

    NSString *textToDraw = header;

    UIFont *font = [UIFont systemFontOfSize:24.0];

    CGSize stringSize = [textToDraw sizeWithFont:font constrainedToSize:CGSizeMake(pageSize.width - 2*kBorderInset-2*kMarginInset, pageSize.height - 2*kBorderInset - 2*kMarginInset) lineBreakMode:UILineBreakModeWordWrap];

    CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);

    [textToDraw drawInRect:renderingRect withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
}

- (void) drawText:(NSString *)bodyText
{
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);

    NSString *textToDraw = bodyText;

    UIFont *font = [UIFont systemFontOfSize:14.0];

    CGSize stringSize = [textToDraw sizeWithFont:font
                               constrainedToSize:CGSizeMake(pageSize.width - 2*kBorderInset-2*kMarginInset, pageSize.height - 2*kBorderInset - 2*kMarginInset) 
                                   lineBreakMode:UILineBreakModeWordWrap];

    CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 50.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);

    [textToDraw drawInRect:renderingRect 
                  withFont:font
             lineBreakMode:UILineBreakModeWordWrap
                 alignment:UITextAlignmentLeft];

}

- (void) drawLine
{
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(currentContext, kLineWidth);

    CGContextSetStrokeColorWithColor(currentContext, [UIColor blackColor].CGColor);

    CGPoint startPoint = CGPointMake(kMarginInset + kBorderInset, kMarginInset + kBorderInset + 40.0);
    CGPoint endPoint = CGPointMake(pageSize.width - 2*kMarginInset -2*kBorderInset, kMarginInset + kBorderInset + 40.0);

    CGContextBeginPath(currentContext);
    CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y);
    CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y);

    CGContextClosePath(currentContext);    
    CGContextDrawPath(currentContext, kCGPathFillStroke);
}

- (void) drawImage:(UIImage *)image
{
    //UIImage * demoImage = [UIImage imageNamed:@"demo.png"];
    [image drawInRect:CGRectMake( (pageSize.width - image.size.width/2)/2, 350, image.size.width/2, image.size.height/2)];
}


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

    pageSize = CGSizeMake(612, 792);
    UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);

    NSInteger currentPage = 0;
    BOOL done = NO;
    do 
    {
        //Start a new page.
        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);

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

        //Draw a border for each page.
        [self drawBorder];

        //Draw text fo our header.
        [self drawHeader:theHeader];

        //Draw a line below the header.
        [self drawLine];

        //Draw some text for the page.
        [self drawText:theText];

        //Draw an image
        [self drawImage:theImage];
        done = YES;
    } 
    while (!done);

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

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (IBAction)generatePdfWithFileName:(id)sender
{
    pageSize = CGSizeMake(612, 792);
    NSString *fileName = @"test.pdf";
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

    NSString *header = @"This is the bad ass header section!";
    NSString *text = @"There is so much to say here I don't know where to begin....";

    [self generatePdf : pdfFileName : header:text:nil];
}

@end

2
据我所知,您必须跟踪当前的Y坐标,并在添加每个项目时进行更新。当您接近或到达边缘时,您将开始一个新页面。如果使用云服务是一种选择,您可以尝试像Docmosis这样的东西,它可以自己管理页面布局。如果您已经致力于像这样的代码布局文档,则无法帮助您。 - Paul Jowett
你能给我一个关于如何处理这个的想法吗? - jroyce
我会将其作为答案添加,因为它太长了无法作为评论。 - Paul Jowett
2个回答

9

这里可以看到概念:

[来源于http://spitzkoff.com/craig/?p=160]

在放置物品时,获取高度:

CGSize size = [name sizeWithFont:studentNameFont forWidth:maxWidth lineBreakMode:UILineBreakModeWordWrap];
[name drawAtPoint:CGPointMake(kMargin, currentPageY) forWidth:maxWidth withFont:studentNameFont lineBreakMode:UILineBreakModeWordWrap];
currentPageY += size.height;

在适当的时候,检查currentY,并决定是否需要移动到新页面:

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 = kMargin;
}

我希望你能够从中受益。

这个答案并没有说明如何判断一个字符串是否太长,以及如何将其分成几部分。 - Saad

1

我是新手stackoverflow用户,但我想为“分解长文本视图”问题提供一个简短的答案。

我使用的方法肯定不是将文本分解为部分的最有效方式,但它是我找到并且可行的唯一方式。我只是在绘制之前循环检查每个单词的子文本是否适合我的页面高度(允许的高度)。如果整个文本不适合,则我的代码将仅绘制找到的部分。例如,我可以将长文本分成四页......至少如此。 对于我的缺乏经验和我的回答,即“如何”的想法,如果不够清晰,我表示抱歉。

为了澄清我的回答。我添加了使用的方法来检查所需高度(发现)的“子文本”(每次添加一个单词与“子文本”一起检查)。因为“sizeWithFont:”自IOS 7以来已被弃用,所以我使用“boundingRectWithSize:”方法。

// Process, that can take long though, to find the next start of the part of a text that hasn't been drawned yet.

float widthRect;
widthRect = pageWidth - 2 * leftMargin;

    - (unsigned int) findNextStartingPos:(NSString *)text withHeight:(float) height
    {
        NSString *character;
        unsigned int pos = 0;
        unsigned int posFound = 0;
        unsigned int lastPosFound = 0;
        BOOL found = NO;
        NSString *textTest;
        float heightFound;

        while (pos <= [text length]-1)
        {
            character = [text substringWithRange:NSMakeRange(pos, 1)];
            if ([character isEqualToString:@" "] || [character isEqualToString:@"\n"])
            {
                posFound = pos;
                found = YES;
            }

            if (found)
            {
                textTest = [text substringWithRange:NSMakeRange(0, posFound)];
                heightFound = lroundf([self heightFound:textTest withWidth:widthRect fontSize:fontSizeBody center:NO]);

                if (heightFound > height)
                {
                    if (lastPosFound == 0)
                    {
                        posFound = lastPosFound;
                    } else
                    {
                        posFound = lastPosFound + 1;
                    }
                    if (posFound > [text length]-1) posFound = lastPosFound;
                    break;
                }
                lastPosFound = posFound;
            }
            pos++;
        }

        return posFound;

    }  return posFound;

    }


// Returns the height needed to draw a text (and to check for space in a page)
-(float) heightFound:(NSString *)text withWidth:(float)width fontSize:(CGFloat)fontSize center:(BOOL)center
{
    if ([text length] != 0)
    {
        UIFont *font = [UIFont fontWithName:@"Helvetica" size:fontSize];

        NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        if (center)
        {
            paragraphStyle.alignment = NSTextAlignmentCenter;
        } else {
            paragraphStyle.alignment = NSTextAlignmentLeft;
        }
        NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName: paragraphStyle};

        NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text attributes:attributes];

        CGRect newRect = [attributedString boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil];

        return newRect.size.height;

    } else {
        return 0;
    }
}

抱歉,如果我的代码不够精确,那是因为它会变得太长。 - Patrick Samson
注意页面结尾可能会有 "\n",这会需要更多的编码。 - Patrick Samson
我并不是特别追求“声望积分”,但因为我在Stackoverflow上很新,一些鼓励会受到欣赏。 - Patrick Samson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接