PDF首页不会在iOS中显示

时间:2014-05-25 13:11:39

标签: ios uitableview pdf uiimage nsurl

我必须在UITableViewCell's ImageView中显示PDF首页。

我的PDF文档位于应用程序的文档目录中。

以下是CellForRowAtIndexPath

中的代码
NSURL* url =[self.arrayOfBooks objectAtIndex:indexPath.row];

UIImage *cellImage = [self buildThumbnailImage:MyGetPDFDocumentRef(url.absoluteString)];

cell.imageView.image = cellImage;

这是buildThumbnailImage方法。

- (UIImage *)buildThumbnailImage:(CGPDFDocumentRef)pdfDocument
{
    BOOL hasRetinaDisplay = FALSE;  // by default
    CGFloat pixelsPerPoint = 1.0;  // by default (pixelsPerPoint is just the "scale" property of the screen)

    if ([UIScreen instancesRespondToSelector:@selector(scale)])  // the "scale" property is only present in iOS 4.0 and later
    {
        // we are running iOS 4.0 or later, so we may be on a Retina display;  we need to check further...
        if ((pixelsPerPoint = [[UIScreen mainScreen] scale]) == 1.0)
            hasRetinaDisplay = FALSE;
        else
            hasRetinaDisplay = TRUE;
    }
    else
    {
        // we are NOT running iOS 4.0 or later, so we can be sure that we are NOT on a Retina display
        pixelsPerPoint = 1.0;
        hasRetinaDisplay = FALSE;
    }

    size_t imageWidth = 320;  // width of thumbnail in points
    size_t imageHeight = 460;  // height of thumbnail in points

    if (hasRetinaDisplay)
    {
        imageWidth *= pixelsPerPoint;
        imageHeight *= pixelsPerPoint;
    }

    size_t bytesPerPixel = 4;  // RGBA
    size_t bitsPerComponent = 8;
    size_t bytesPerRow = bytesPerPixel * imageWidth;

    void *bitmapData = malloc(imageWidth * imageHeight * bytesPerPixel);

    // in the event that we were unable to mallocate the heap memory for the bitmap,
    // we just abort and preemptively return nil:
    if (bitmapData == NULL)
        return nil;

    // remember to zero the buffer before handing it off to the bitmap context:
    bzero(bitmapData, imageWidth * imageHeight * bytesPerPixel);

    CGContextRef theContext = CGBitmapContextCreate(bitmapData, imageWidth, imageHeight, bitsPerComponent, bytesPerRow,
                                                    CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast);

    //CGPDFDocumentRef pdfDocument = MyGetPDFDocumentRef();  // NOTE: you will need to modify this line to supply the CGPDFDocumentRef for your file here...
    CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDocument, 1);  // get the first page for your thumbnail

    CGAffineTransform shrinkingTransform =
    CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, CGRectMake(0, 0, imageWidth, imageHeight), 0, YES);

    CGContextConcatCTM(theContext, shrinkingTransform);

    CGContextDrawPDFPage(theContext, pdfPage);  // draw the pdfPage into the bitmap context
    CGPDFDocumentRelease(pdfDocument);

    //
    // create the CGImageRef (and thence the UIImage) from the context (with its bitmap of the pdf page):
    //
    CGImageRef theCGImageRef = CGBitmapContextCreateImage(theContext);
    free(CGBitmapContextGetData(theContext));  // this frees the bitmapData we malloc'ed earlier
    CGContextRelease(theContext);

    UIImage *theUIImage;

    // CAUTION: the method imageWithCGImage:scale:orientation: only exists on iOS 4.0 or later!!!
    if ([UIImage respondsToSelector:@selector(imageWithCGImage:scale:orientation:)])
    {
        theUIImage = [UIImage imageWithCGImage:theCGImageRef scale:pixelsPerPoint orientation:UIImageOrientationUp];
    }
    else
    {
        theUIImage = [UIImage imageWithCGImage:theCGImageRef];
    }

    CFRelease(theCGImageRef);
    return theUIImage;
}


CGPDFDocumentRef MyGetPDFDocumentRef(NSString *inputPDFFile)
{
    //NSString *inputPDFFile = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"test.pdf"];

    const char *inputPDFFileAsCString = [inputPDFFile cStringUsingEncoding:NSASCIIStringEncoding];
    //NSLog(@"expecting pdf file to exist at this pathname: \"%s\"", inputPDFFileAsCString);

    CFStringRef path = CFStringCreateWithCString(NULL, inputPDFFileAsCString, kCFStringEncodingUTF8);

    CFURLRef url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0);
    CFRelease (path);

    CGPDFDocumentRef document = CGPDFDocumentCreateWithURL(url);
    CFRelease(url);

    if (CGPDFDocumentGetNumberOfPages(document) == 0)
    {
        printf("Warning: No pages in pdf file \"%s\" or pdf file does not exist at this path\n", inputPDFFileAsCString);
        return NULL;
    }

    return document;
}

以下是我如何从文档目录加载pdf文件列表。

- (NSMutableArray *)loadBookFromDocumentDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [NSString stringWithFormat:@"%@",[paths objectAtIndex:0]];

    NSFileManager *manager = [NSFileManager defaultManager];

    NSError *error;

    NSArray *files = [manager contentsOfDirectoryAtURL:[NSURL fileURLWithPath:documentsDirectory]
                            includingPropertiesForKeys:[NSArray arrayWithObject:NSURLContentModificationDateKey]
                                               options:NSDirectoryEnumerationSkipsHiddenFiles

                                                 error:&error];

    NSArray* sortArray = [files sortedArrayUsingComparator:
                          ^(NSURL *file1, NSURL *file2)
                          {
                              NSDate *file1Date;
                              [file1 getResourceValue:&file1Date forKey:NSURLContentModificationDateKey error:nil];

                              NSDate *file2Date;
                              [file2 getResourceValue:&file2Date forKey:NSURLContentModificationDateKey error:nil];

                              // Ascending:
                              //return [file1Date compare: file2Date];
                              // Descending:
                              return [file2Date compare: file1Date];
                          }];

    NSMutableArray *sortedContents = [[NSMutableArray alloc] initWithArray:sortArray];
    return sortedContents;
}

当我运行我的应用程序时,它不会在Cell ImageView上显示任何内容并显示此消息。

file:///Users/MacUser/Library/Application%20Support/iPhone%20Simulator/7.1-64/Applications/08BE9071-6251-44ED-A8E0-55CD478380FC/Documents/CGPDFDocument.pdf" or pdf file does not exist at this path

我确信我有这个pdf,甚至在TableView中显示PDF名称。

我在哪里?

1 个答案:

答案 0 :(得分:1)

好。我想我明白这里发生了什么。

您已经通过iTunes"添加了您的PDF文件。我不知道应该如何实际工作。

但我很清楚,模拟器文件夹中的PDF文件大小为零字节。

您现在拥有的代码应该可以使用,您只需要将有效的PDF文件放入其中即可。

在终端中,您可以使用命令

打开该文件夹
open ~/Library/Application\ Support/iPhone\ Simulator/7.1-64/Applications/08BE9071-6251-44ED-A8E0-55CD478380FC/Documents

当它在Macintosh Finder中打开时,您会看到其中的所有PDF文件大小为零字节。手动复制正确的PDF文件,您的应用程序应该开始在模拟器中神奇地工作。

现在,对于生产代码,您需要编写代码才能将PDF文件复制到文档文件夹中。 PDF文件最初来自哪里?你下载它们还是内置到应用程序的某个地方?