PDF在Cocoa中创建

时间:2013-01-02 08:28:51

标签: macos cocoa

以下代码PDF得到created,但我可以在writePDF。但我无法render NSView PDF }}

CGContextRef aCgPDFContextRef = [self createPDFContext:CGRectMake(0, 0, 612, 892) path:(CFStringRef)filepath];

CGContextBeginPage(aCgPDFContextRef,nil);

//Draw view into PDF
NSView *aPageNote=[[NSView alloc]initWithFrame:CGRectMake(0,0, 612, 892)];

CGAffineTransform aCgAffTrans = CGAffineTransformIdentity;
aCgAffTrans = CGAffineTransformMakeTranslation(0,892);
aCgAffTrans = CGAffineTransformScale(aCgAffTrans, 1.0, -1.0);
CGContextConcatCTM(aCgPDFContextRef, aCgAffTrans);

NSString *strText = @"Test 123333333333333333";
[strText drawAtPoint:NSMakePoint(100, 200) withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSFont systemFontOfSize:40.0],NSFontAttributeName,nil]];//drawAtPoint:CGPointMake(200, 300) withFont:[NSFont systemFontOfSize:20]];

[aPageNote setWantsLayer:YES];
[aPageNote.layer renderInContext:aCgPDFContextRef];
CGContextEndPage(aCgPDFContextRef);

CGContextRelease (aCgPDFContextRef);
NSLog(@"Pdf Successfully Created");

方法:

-(CGContextRef) createPDFContext:(CGRect)aCgRectinMediaBox path:(CFStringRef) aCfStrPath
{
 CGContextRef aCgContextRefNewPDF = NULL;
 CFURLRef aCfurlRefPDF;
 aCfurlRefPDF = CFURLCreateWithFileSystemPath (NULL,aCfStrPath,kCFURLPOSIXPathStyle,false);
 if (aCfurlRefPDF != NULL) {
    aCgContextRefNewPDF = CGPDFContextCreateWithURL (aCfurlRefPDF,&aCgRectinMediaBox,NULL);
    CFRelease(aCfurlRefPDF);
 }
 return aCgContextRefNewPDF;
}

编辑:我可以使用此代码write PDF

  CGContextBeginPage(aCgPDFContextRef,nil);
NSString *strText1 = @"I am iOS Developer";
CGContextSelectFont (aCgPDFContextRef, "Helvetica", 24, kCGEncodingMacRoman);
CGContextSetTextDrawingMode (aCgPDFContextRef, kCGTextFill);
CGContextSetRGBFillColor (aCgPDFContextRef, 0, 0, 0, 1);
const char *text1 = [strText1 UTF8String];
CGContextShowTextAtPoint (aCgPDFContextRef, 50, 375, text1, strlen(text1));
CGContextEndPage(aCgPDFContextRef);

1 个答案:

答案 0 :(得分:1)

编辑Render NSView并将{x}添加为PDF,如下所示:

//Firstly render NS element into NSImage
NSImage *i = [[NSImage alloc] initWithData:[yourView dataWithPDFInsideRect:[yourView bounds]]];
//Now u can add in PDF
CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)[i TIFFRepresentation], NULL);
CGImageRef imageRef =  CGImageSourceCreateImageAtIndex(source, 0, NULL);
CGContextDrawImage(aCgPDFContextRef,[yourView bounds], imageRef);