Create PDF in Cocoa

Here below is the code PDFgets created, but I can writein PDF. But I can not render NSViewinPDF

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");

Method:

-(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;
}

EDIT : I can writein PDFusing this code

  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
source share
1 answer

CHANGE : Renderan NSView and add as an image in PDFthe following manner:

//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);
+1
source

Source: https://habr.com/ru/post/1629340/


All Articles