I am stuck with parsing a PDF file. Please guide me how to do this.
Header file.
//PDFViewer.h
@interface PDFViewer : UIView
{
CGPDFDocumentRef pdf;
}
UIGraphicsGetCurrentContext
does not return a context if there isn't one, obviously.
You try to get the context at view initialization, at that time there is no context available. A valid context gets pushed onto the stack just before -[UIView drawRect:]
is being called. This should work:
//PDFViewer.m
@implementation PDFViewer
- (void)drawRect:(CGRect)rect {
[self drawInContext:UIGraphicsGetCurrentContext()];
}
@end
EDIT Eventhough I don't like to give anyone copy-and-paste-ready-code, I don't think there is another option left if you didn't understand my latest comment. I don't know what you've tried, but if you try to understand what I'm really saying, this is the only thing you can come up with:
//PDFViewer.m
@implementation PDFViewer
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("WR1MayJun1S08.pdf"), NULL, NULL);
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
CFRelease(pdfURL);
}
return self;
}
-(void)drawInContext:(CGContextRef)context
{
// PDF page drawing expects a Lower-Left coordinate system, so we flip the coordinate system
// before we start drawing.
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// Grab the first PDF page
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);
// We're about to modify the context CTM to draw the PDF page where we want it, so save the graphics state in case we want to do more drawing
CGContextSaveGState(context);
// CGPDFPageGetDrawingTransform provides an easy way to get the transform for a PDF page. It will scale down to fit, including any
// base rotations necessary to display the PDF page correctly.
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, self.bounds, 0, true);
// And apply the transform.
CGContextConcatCTM(context, pdfTransform);
// Finally, we draw the page and restore the graphics state for further manipulations!
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
}
- (void)drawRect:(CGRect)rect {
[self drawInContext:UIGraphicsGetCurrentContext()];
}
- (void)dealloc
{
CGPDFDocumentRelease(pdf);
[super dealloc];
}
@end
—
//MainViewController.m
CGRect frame = CGRectMake(0, 200, 300, 500);
PDFViewer *pdfViewer = [[PDFViewer alloc] initWithFrame:frame];
[self.view addSubview:pdfViewer];
I got another simple way to parse PDF for iPhone/iPad:
1.Take one UIwebView
(name:pdfView
).
2.Give IBoutlet
connection to it & Delegate it to FilesOwner
3.In Viewdidload
[self.pdfView loadRequest:[NSURLRequest requestWithURL:[NSURL
fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"ObjC" ofType:@"pdf"]]]];
4.ObjC.pdf should be in resource folder..