使用CGContext以编程方式创建PDF - 无法获得换行符+ iPhone

时间:2010-07-30 10:29:49

标签: iphone quartz-2d

我正在使用CGContext和CGContextShowTextAtPoint在我的iPhone应用程序中以编程方式创建PDF。虽然这适用于较小的文本,但每当我在文本中使用换行符(\ n)或希望文本在到达页面末尾时自动换行到下一行时,就不会发生这种情况。

文本中的任何换行符都会被空格替换,文本不会换行。真的很欣赏如何实现这一目标。这是我用来创建PDF的代码。

void CreatePDFFile (CGRect pageRect, const char *filename, NSString *fromFile) {
    CGContextRef pdfContext;
    CFStringRef path = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);
    CGURLRef url = CFURLCreateWithFileSystemPath (NULL, path, kCFURLPOSIXPathStyle, 0);
    CFRelease (path);
    CFMutableDictionaryRef myDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File"));
    CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name"));
    pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary);
    CFRelease(myDictionary);
    CFRelease(url);

    CGContextBeginPage (pdfContext, &pageRect);
    CGContextSelectFont (pdfContext, "Helvetica", 14, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode (pdfContext, kCGTextFill);
    CGContextSetRGBFillColor (pdfContext, 0, 0, 150, 1);
    /* This works
    const char *text = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem";
    CGContextShowTextAtPoint (pdfContext, 50, 760, text, strlen(text));*/
    //This doesn't print line breaks in the PDF
    const char *text = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem\n accusantium doloremque laudantium, totam rem aperiam, eaque ipsa";
    CGContextShowTextAtPoint (pdfContext, 50, 760, text, strlen(text));
    //This doesn't wrap text to the next line
    const char *text = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa";
    CGContextShowTextAtPoint (pdfContext, 50, 760, text, strlen(text));

    CGContextEndPage (pdfContext);
    CGContextRelease (pdfContext);
}

1 个答案:

答案 0 :(得分:1)

CGContextShowTextAtPoint仅进行基本文字绘制。您应该可以使用UIKit additions to NSString来进行包装等操作。例如:

NSString* text = @"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa";
[text drawInRect:CGRectMake(50,760,200,200) withFont:[UIFont fontWithName:@"Helvetica" size:14]];

但请注意,NSString方法会对当前上下文起作用,因此您需要将上下文设置为当前状态才能使用它们。如果您在后台线程中执行此操作,我想可能会出现问题。