user635064
user635064

Reputation: 6247

Cocoa PDFKit add text to PDF

I am trying to add text to t a PDFPage. Specifically, I want to add it to the header/footer of the pdf document. I have looked everywhere for an example of doing this but I can't find it. If someone can point to a tutorial or give a quick example of how I can add text to PDFPage it would be really helpful. Thanks.

Upvotes: 2

Views: 3005

Answers (3)

Siddhant Gupta
Siddhant Gupta

Reputation: 156

The answers here are incomplete, after putting various pieces together, here is complete sample code (Objective-C):

//  Need to create pdf Graphics context for Drawing text
    CGContextRef pdfContextRef = NULL;
    CFURLRef writeFileUrl = (CFURLRef)[NSURL fileURLWithPath:writeFilePath];
    
    if(writeFileUrl != NULL){
        pdfContextRef = CGPDFContextCreateWithURL(writeFileUrl, NULL, NULL);
    }
    
//  Start page in PDF context
    CGPDFContextBeginPage(pdfContextRef, NULL);
    
    NSGraphicsContext* pdfGraphicsContext = [NSGraphicsContext graphicsContextWithCGContext:pdfContextRef flipped:false];
    [NSGraphicsContext saveGraphicsState];
    
//  Need to set the current graphics context
    [NSGraphicsContext setCurrentContext:pdfGraphicsContext];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:26], NSFontAttributeName,[NSColor blackColor], NSForegroundColorAttributeName, nil];
    NSAttributedString * currentText=[[NSAttributedString alloc] initWithString:@"Write Something" attributes: attributes];

//  [currentText drawInRect: CGRectMake(0, 300, 500, 100 )];
    [currentText drawAtPoint:NSMakePoint(100, 100)];
    
    [NSGraphicsContext restoreGraphicsState];

//  Close all the created pdf Contexts
    CGPDFContextEndPage(pdfContextRef);
    CGPDFContextClose(pdfContextRef);

Upvotes: 0

Michael J. Barber
Michael J. Barber

Reputation: 25052

The short answer is to subclass PDFPage and override the drawing methods. There's a description here.

Upvotes: 0

VenoMKO
VenoMKO

Reputation: 3294

You can do it using Quartz 2D - PDF Document Creation, Viewing, and Transforming. This code will help you to write into file:

[someString drawAtPoint:CGPointMake(100, 200) withFont:[NSFont systemFontOfSize:20.0f]];

Upvotes: 1

Related Questions