7

我想在 iOS 中创建一个 PDF 文件,PDF 中应该有一个表格,它是从一个数组中填充的。我已经在谷歌上搜索过,但没有成功。任何帮助表示赞赏

4

1 回答 1

1

像这样的例程来呈现文本:

- (CFRange)renderTextRange:(CFRange)currentRange andFrameSetter:(CTFramesetterRef)frameSetter intoRect:(CGRect)frameRect {
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
CTFrameRef frameRef = CTFramesetterCreateFrame(frameSetter, currentRange, framePath, NULL);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(currentContext);
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);  
CGContextTranslateCTM(currentContext, 0, 792); 
CGContextScaleCTM(currentContext, 1.0, -1.0);
CTFrameDraw(frameRef, currentContext);
CGContextRestoreGState(currentContext);
CGPathRelease(framePath);
currentRange = CTFrameGetVisibleStringRange(frameRef);
currentRange.location += currentRange.length;
currentRange.length = 0;
CFRelease(frameRef);
return currentRange;
}

以下代码片段调用它,假设您创建了上下文和任何字体等并在适当的变量中。以下循环只是将文本逐行构建成一个NSMutableAttributedString您可以渲染的文本:

CTFontRef splainFont = CTFontCreateWithName(CFSTR("Helvetica"), 10.0f, NULL);
CGFloat margin = 32.0f;
CGFloat sink = 8.0f;

NSMutableAttributedString *mainAttributedString = [[NSMutableAttributedString alloc] init];
NSMutableString *mainString = [[NSMutableString alloc] init];

// Ingredients is an NSArray of NSDictionaries
// But yours could be anything, or just an array of text.
for (Ingredient *ingredient in ingredients) {
    NSString *ingredientText = [NSString stringWithFormat:@"%@\t%@
        \n",ingredient.amount,ingredient.name];
    [mainString appendString:ingredientText];
    NSMutableAttributedString *ingredientAttributedText =
        [[NSMutableAttributedString alloc] initWithString:ingredientText];
    [ingredientAttributedText addAttribute:(NSString *)(kCTFontAttributeName)
        value:(id)splainFont
        range:NSMakeRange(0, [ingredientText length])];
    [mainAttributedString appendAttributedString:ingredientAttributedText];
    [ingredientAttributedText release];
}

现在你已经用换行符写出了你的数组,NSMutableAttributedString你可以渲染它,这取决于你的文本,你可能想在一个循环中渲染它,直到渲染的位置与你的文本长度匹配。就像是:

// Render Main text.
CTFramesetterRef mainSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)mainAttributedString);
currentRange = [KookaDIS renderTextRange:currentRange 
    andFrameSetter:mainSetter 
    intoRect:pageRect];

// If not finished create new page and loop until we are.
while (!done) {
    UIGraphicsBeginPDFPageWithInfo(pageRect, nil);

    currentRange = [self renderTextRange:currentRange 
        andFrameSetter:mainSetter 
        intoRect:pageRect];

    if (currentRange.location >= [mainString length]) {
        done = TRUE;
    }
}

上面的代码需要相当多的调整我敢肯定,因为它是从我自己的项目中破解出来的,所以一些变量(如框架设置器)将不存在,你需要关闭 PDF 上下文并释放变量等. 注意 mainString 是如何用于确定文本何时被渲染出来的。

它应该足够清楚地指示如何循环数组或任何其他组以将任意长度的文本呈现到文档中。

对 while 循环和输入之前的一次渲染稍作修改,您也可以在多列中渲染文本。

于 2011-10-27T08:30:12.587 回答