본문 바로가기

iOS Programming

cocoa touch 에서의 간단한 pdf 핸드링


@interface MMPDFView : UIView {
CGPDFDocumentRef pdfDoc;
}

- (void)loadPDF:(NSURL *)url;
- (void)drawPdfPage:(int)page context:(CGContextRef)ctxt area:(CGRect)vrect isZoom:(BOOL)isZoom;

@end



@implementation MMPDFView

- (void)loadPDF:(NSURL *)url
{
if(pdfDoc != nil)
CGPDFDocumentRelease(pdfDoc);
pdfDoc = CGPDFDocumentCreateWithURL((CFURLRef)url);
[self setNeedsDisplay];
}


- (void)drawPdfPage:(int)page context:(CGContextRef)ctxt area:(CGRect)vrect
{
CGContextSetFillColorWithColor(ctxt, [UIColor whiteColor].CGColor);
CGContextFillRect(ctxt, self.frame);

int maxPage = CGPDFDocumentGetNumberOfPages(pdfDoc);

if(page > 0 && currentPage <= maxPage)
{
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, page);
CGRect pageRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFCropBox);
double hRate = vrect.size.width / pageRect.size.width;
double xstd = 0, ystd = pageRect.size.height * hRate;
if(pageRect.size.height * hRate <= vrect.size.height)
ystd = pageRect.size.height * hRate + (vrect.size.height - pageRect.size.height * hRate) / 2;
if(pageRect.size.width * hRate < vrect.size.width)
xstd = (vrect.size.width - pageRect.size.width * hRate) / 2;
CGContextTranslateCTM(ctxt, xstd, ystd);
CGContextScaleCTM(ctxt, hRate, -hRate);
CGContextSaveGState(ctxt);
CGContextDrawPDFPage(ctxt, pdfPage);
CGContextRestoreGState(ctxt);
}
}

- (void)drawRect:(CGRect)rect
{
if(pdfDoc == nil)
return;
CGContextRef ctxt = UIGraphicsGetCurrentContext();
[self drawPdfPage:0 context:ctxt area:self.frame];
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self loadPDF:파일경로];
    }
    return self;
}

- (void)dealloc {
if(pdfDoc != nil)
CGPDFDocumentRelease(pdfDoc);

    [super dealloc];
}


@end