How to get actual pdf page size in iPad?

前端 未结 5 2021
时光取名叫无心
时光取名叫无心 2020-12-10 08:16

How can I get PDF page width and height in iPad? Any document or suggestions on how I can find this information?

5条回答
  •  感动是毒
    2020-12-10 08:34

    Here's the code to do it; also to convert a point on the page from PDF coordinates to iOS coordinates. See also Get PDF hyperlinks on iOS with Quartz

    #import 
    
    
    . . . . . . . . . . . 
    
    NSString *pathToPdfDoc = [[NSBundle mainBundle] pathForResource:@"Test2" offType:@"pdf"];
    NSURL *pdfUrl = [NSURL fileURLWithPath:pathToPdfDoc];
    
    CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((CFURLRef)pdfUrl);
    
    CGPDFPageRef page = CGPDFDocumentGetPage(document, 1); // assuming all the pages are the same size!
    
    // code from https://stackoverflow.com/questions/4080373/get-pdf-hyperlinks-on-ios-with-quartz, 
    // suitably amended
    
    CGPDFDictionaryRef pageDictionary = CGPDFPageGetDictionary(page);
    
    
    //******* getting the page size
    
    CGPDFArrayRef pageBoxArray;
    if(!CGPDFDictionaryGetArray(pageDictionary, "MediaBox", &pageBoxArray)) {
        return; // we've got something wrong here!!!
    }
    
    int pageBoxArrayCount = CGPDFArrayGetCount( pageBoxArray );
    CGPDFReal pageCoords[4];
    for( int k = 0; k < pageBoxArrayCount; ++k )
    {
        CGPDFObjectRef pageRectObj;
        if(!CGPDFArrayGetObject(pageBoxArray, k, &pageRectObj))
        {
            return;
        }
    
        CGPDFReal pageCoord;
        if(!CGPDFObjectGetValue(pageRectObj, kCGPDFObjectTypeReal, &pageCoord)) {
            return;
        }
    
        pageCoords[k] = pageCoord;
    }
    
    NSLog(@"PDF coordinates -- bottom left x %f  ",pageCoords[0]); // should be 0
    NSLog(@"PDF coordinates -- bottom left y %f  ",pageCoords[1]); // should be 0
    NSLog(@"PDF coordinates -- top right   x %f  ",pageCoords[2]);
    NSLog(@"PDF coordinates -- top right   y %f  ",pageCoords[3]);
    NSLog(@"-- i.e. PDF page is %f wide and %f high",pageCoords[2],pageCoords[3]);
    
    // **** now to convert a point on the page from PDF coordinates to iOS coordinates. 
    
    double PDFHeight, PDFWidth;
    PDFWidth =  pageCoords[2];
    PDFHeight = pageCoords[3];
    
    // the size of your iOS view or image into which you have rendered your PDF page 
    // in this example full screen iPad in portrait orientation  
    double iOSWidth = 768.0; 
    double iOSHeight = 1024.0;
    
    // the PDF co-ordinate values you want to convert 
    double PDFxval = 89;  // or whatever
    double PDFyval = 520; // or whatever
    
    // the iOS coordinate values
    int iOSxval, iOSyval;
    
    iOSxval = (int) PDFxval * (iOSWidth/PDFWidth);
    iOSyval = (int) (PDFHeight - PDFyval) * (iOSHeight/PDFHeight);
    
    NSLog(@"PDF: %f %f",PDFxval,PDFyval);
    NSLog(@"iOS: %i %i",iOSxval,iOSyval);
    

提交回复
热议问题