Edit RTF/DOC file programmatically in xcode/ios

Solutions Collect From Internet About “Edit RTF/DOC file programmatically in xcode/ios”

In your .h file add some objects and defines

#define kBorderInset            20.0
#define kBorderWidth            1.0
#define kMarginInset            10.0

@interface ViewController : UIViewController
{
    CGSize pageSize;
    NSString *pdfFileName;
    NSString *contents_for_pdf;
}

- (void)generatePdfWithFilePath:(NSString *)thefilePath;

in .m file add this lines some where on button click to get contents of rtf file in string

NSString *rtf_path = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"rtf"];
contents_for_pdf = [[NSString alloc] initWithContentsOfFile:rtf_path encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",contents_for_pdf);
contents_for_pdf = [contents_for_pdf stringByReplacingOccurrencesOfString:@"I am new to StackOverflow" withString:@"I regularly visit StackOverflow"];

pageSize = CGSizeMake(612, 792);
NSString *fileName = @"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

[self generatePdfWithFilePath:pdfFileName];

I didnt modify the text of rtf file,I just used same text in rtf file.you should do as you want(I noticed some encoding characters in text) and function that will generate pdf is here.

- (void) generatePdfWithFilePath: (NSString *)thefilePath
{
    UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
    //Start a new page.
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);

    //Draw text fo our header.

    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);

    UIFont *font = [UIFont systemFontOfSize:14.0];

    CGSize stringSize = [contents_for_pdf sizeWithFont:font
                                     constrainedToSize:CGSizeMake(pageSize.width - 2*kBorderInset-2*kMarginInset, pageSize.height - 2*kBorderInset - 2*kMarginInset) 
                                         lineBreakMode:UILineBreakModeWordWrap];

    CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 50.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);

    [contents_for_pdf drawInRect:renderingRect 
                        withFont:font
                   lineBreakMode:UILineBreakModeWordWrap
                       alignment:UITextAlignmentLeft];

    UIGraphicsEndPDFContext();

    UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:@"PDF Created" message:@"Sucessfull" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
    [Alert show];
}