问题是在PDF中创建两个文本列,如下所示: 为了生成PDF,我使用Apple的指南“iOS绘图和打印指南”,我用标签创建了两个列:
NSArray *stringList =
@[
@[string1, string2],
@[@"", string4],
@[string5, string6],
@[string7, string8]
];
resultString = [[NSMutableAttributedString alloc] init];
for (NSArray *row in stringList) {
int i = 0;
NSMutableAttributedString *subResult = [[NSMutableAttributedString alloc] init];
NSMutableArray *tabs = @[].mutableCopy;
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
for (NSString *tempString in row) {
NSTextTab *tab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft location:200 options:nil];
if ([tempString isKindOfClass:[NSAttributedString class]]) {
[subResult appendAttributedString:(NSAttributedString *)tempString];
[subResult appendAttributedString:[[NSAttributedString alloc] initWithString:@"\t"]];
} else {
[subResult appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\t", tempString]]];
}
[tabs addObject:tab];
i++;
}
[subResult appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
[style setTabStops:tabs];
[subResult addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, subResult.length)];
[resultString appendAttributedString:subResult];
}
作为输出,我得到了这个:
因此,我想要用红色箭头标记的字符串的行完全在第二列中看到,如图片№1。
答案 0 :(得分:0)
我们的想法是将文本分成块和单行,并用于每个部分
- (void)drawInRect:(CGRect)rect;
或
void CTLineDraw(CTLineRef line, CGContextRef context);
解决方案:
@import CoreText;
<...>
- (IBAction)createPDF:(id)sender {
PDFFileName = <yourString>;
PDFPath = <yourPath>;
[self generatePdfWithFilePath:PDFPath];
}
- (void)generatePdfWithFilePath:(NSString *)thefilePath {
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
BOOL done = NO;
do {
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 712), nil);
[self drawText];
done = YES;
}
while (!done);
UIGraphicsEndPDFContext();
}
- (void)drawText {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//Here you can set up attributes for your text
NSDictionary *attributesForText = @{
NSFontAttributeName:[UIFont fontWithName:@"Georgia" size:12]
};
//Drawing text in line
NSMutableAttributedString *stringOneAttributed = [[NSMutableAttributedString alloc] initWithString:stringOne attributes:attributesForText];
CTLineRef stringOneLine = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)(stringOneAttributed));
CGContextSetTextPosition(currentContext, x, y);
CTLineDraw(stringOneLine, currentContext);
CFRelease(stringOneLine);
//Drawing block of text in rectangle
NSMutableAttributedString *stringTwoAttributed = [[NSMutableAttributedString alloc] initWithString:stringTwo attributes:attributesForText];
[stringTwoAttributed drawInRect:CGRectMake(x, y, width, height)];
}