2010-07-20 9 views
6

Estoy atascado con el análisis de un archivo PDF. Por favor, guíame cómo hacer esto.Cómo analizar PDF en Objective C para iPad

Archivo de encabezado.

//PDFViewer.h 
@interface PDFViewer : UIView 
{ 
CGPDFDocumentRef pdf; 
} 

-(void)drawInContext:(CGContextRef)context; 

@end 

archivo de implementación

//PDFViewer.m 
@implementation PDFViewer 


- (id)initWithFrame:(CGRect)frame 
{ 

if ((self = [super initWithFrame:frame])) 
{ 
     // Initialization code 
    if(self != nil) 
    { 
    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); 
} 

/* 
// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect { 
    // Drawing code 
} 
*/ 

- (void)dealloc 
{ 
    CGPDFDocumentRelease(pdf); 
[super dealloc]; 
} 


@end 

Ahora estoy añadiendo esta clase (PDFViewer.h) a mi MainViewController.

//MainViewController.m 

CGRect frame = CGRectMake(0, 200, 300, 500); 

PDFViewer *pdfViewer = [[PDFViewer alloc] initWithFrame:frame]; 
CGContextRef context = UIGraphicsGetCurrentContext(); 
[pdfViewer drawInContext:context]; 
[self.view addSubview:pdfViewer]; 

No muestra nada. Recibo los siguientes errores/advertencias:

local MultiView[2850] <Error>: CGContextTranslateCTM: invalid context 
local MultiView[2850] <Error>: CGContextScaleCTM: invalid context 
local MultiView[2850] <Error>: CGContextSaveGState: invalid context 
local MultiView[2850] <Error>: CGContextConcatCTM: invalid context 
local MultiView[2850] <Error>: CGContextRestoreGState: invalid context 

¿Qué me falta?

Atentamente.

Respuesta

4

UIGraphicsGetCurrentContext no devuelve un contexto si no hay uno, obviamente.

Intenta obtener el contexto en la inicialización de la vista, en ese momento no hay contexto disponible. Se inserta un contexto válido en la pila justo antes de llamar al -[UIView drawRect:]. Esto debería funcionar:

//PDFViewer.m 
@implementation PDFViewer 

- (void)drawRect:(CGRect)rect { 
    [self drawInContext:UIGraphicsGetCurrentContext()]; 
} 

@end 

EDITAR Apesar de que no me gusta dar a nadie copiar y pegar listas de códigos, no creo que hay otra opción que queda si no entiende mi último comentario No sé lo que ha intentado, pero si se intenta entender lo que estoy diciendo en realidad, este es el único que se puede llegar a:

//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]; 
+0

me hizo el siguiente : - (void) drawRect: (CGRect) rect { \t CGRect frame = CG RectMake (0, 200, 400, 400); \t \t pdfViewer = [[PDFViewer alloc] initWithFrame: frame]; \t \t [pdfViewer drawInContext: UIGraphicsGetCurrentContext()]; \t [self.view addSubview: pdfViewer]; } No muestra nada. – TechBee

+0

No, por supuesto, eso no hace nada. Simplemente mantenga la parte de inicialización en 'MainViewController', excepto desde' CGContextRef context = ...; [pdfViewer drawInContext: context]; 'líneas.Es el código de dibujo que se llama en la inicialización, que se debe invocar cuando se debe dibujar la vista, que está en el método '-drawRect:' de 'PDFViewer'. – Joost

+0

k ¿Puede darme un código de muestra? Estoy malditamente confundido :( Saludos – TechBee

3

Obtuve otra manera simple de analizar PDF para iPhone/iPad:
1.Tome uno UIwebView (nombre: pdfView).

2.Give IBoutlet conexión con él & delegarla en FilesOwner

3.In Viewdidload

[self.pdfView loadRequest:[NSURLRequest requestWithURL:[NSURL 
             fileURLWithPath:[[NSBundle mainBundle] 
             pathForResource:@"ObjC" ofType:@"pdf"]]]]; 

4.ObjC.pdf debe estar en la carpeta de recursos ..