我想我必须从错误的角度来看待这个问题。这是我第一次尝试使用Quartz进行PDF格式化。我希望能够打印输入到我的应用程序中的文本,但我可能需要在此版本中删除它。
我已经阅读了我可以从Apple和Web上获得的所有内容,但我似乎无法让我的东西工作。我可以将文档送到打印机,但它总是打印出来。我正在使用的流程是:
我的文本项目中有两个方法。这只是一个测试,所以没有花里胡哨,可能有内存泄漏,我只是想让它工作。
提前感谢您的帮助。
第一个将PDF文档创建为NSData。
- (NSData *)createPdfAsDataWithAttributedString:(NSAttributedString *)text {
// Save the text just in case…
_pdfText = [text copy];
// Allocate the pdf Context.
CGContextRef pdfContext;
// Create the PDF Attribute Dictionary.
CFMutableDictionaryRef pdfAttributeDictionary = NULL;
pdfAttributeDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(pdfAttributeDictionary, kCGPDFContextTitle, CFSTR("My Note"));
CFDictionarySetValue(pdfAttributeDictionary, kCGPDFContextCreator, CFSTR("Me"));
// Create the data referece as a mutable data type.
NSData *pdfData = [[NSMutableData alloc] init];
// User the data consumer using the data reference.
CGDataConsumerRef pdfDataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);
// Finally the pdfContext can be created.
pdfContext = CGPDFContextCreate(pdfDataConsumer, NULL, pdfAttributeDictionary);
// Start the first page.
CGContextBeginPage(pdfContext, NULL);
// Set the font
CGContextSelectFont(pdfContext, "Helvetica", 16.0f, kCGEncodingMacRoman);
CGContextSetTextDrawingMode(pdfContext, kCGTextFill);
CGContextSetRGBFillColor(pdfContext, 0, 0, 0, 1);
// Print the text
NSString *regText = [text string];
const char *pdfText = [regText cStringUsingEncoding:NSUTF8StringEncoding];
CGContextShowText(pdfContext, pdfText, strlen(pdfText));
// End the page.
CGContextEndPage(pdfContext);
// Save the current state
CGContextSaveGState(pdfContext);
// Release the PDF context
CGContextRelease(pdfContext);
return [pdfData autorelease];
}
第二个是印刷品。
- (IBAction)printPdfTouchUpInside:(id)sender {
PDFCreator *pdfCreator = [[PDFCreator alloc] init];
NSData *pdfData = [pdfCreator createPdfAsDataWithAttributedString:_printableText];
UIPrintInteractionController *printController = [UIPrintInteractionController sharedPrintController];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
[printInfo setPrinterID:@"Canon MP620 series"];
[printInfo setOrientation:UIPrintInfoOrientationPortrait];
[printInfo setOutputType:UIPrintInfoOutputGeneral];
[printInfo setJobName:@"Test Print"];
[printController setPrintInfo:printInfo];
[printController setPrintingItem:pdfData];
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
if (!completed && error) {
NSLog(@"FAILED! due to error in domain %@ with error code %u", error.domain, error.code);
}
};
[printController presentFromRect:[sender bounds] inView:sender animated:YES completionHandler:completionHandler];
}