【问题标题】:PDF First Page doesn't show in iOSPDF 第一页在 iOS 中不显示
【发布时间】:2014-07-14 08:56:22
【问题描述】:

我必须在 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 名称。

我错在哪里?

【问题讨论】:

  • 看起来您的问题出在您的“MyGetPDFDocumentRef”函数中。显示代码。
  • 我添加了我的代码。请检查一下。
  • 在您从 MyGetPDFDocumentRef 返回之前,打印出该函数看到的页数。即:“NSLog(@"number of pages in document is %d", CGPDFDocumentGetNumberOfPages(document));”。告诉我这个号码对你来说是否有效。
  • 如果我用 mainBundle PDF 文件测试就可以了。但不是与文档目录pdf文件。
  • 那不对,是吗?也许该 PDF 文件并没有像您想象的那样最终出现在您编译的应用程序中。

标签: ios uitableview pdf uiimage nsurl


【解决方案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文件最初来自哪里?您是下载它们还是将它们内置在某个应用程序中?

【讨论】:

  • 我已经按照你说的进行了测试。它也不起作用。位于该目录的我的 PDF 文件具有正确的 MB。
  • 萨博,我没办法了。
  • 是的。非常感谢你帮了我那么多。 :) 我还在努力解决它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2012-08-03
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2013-10-09
相关资源
最近更新 更多