我正在使用 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);
}