2012-06-11 32 views
2

我是iPhone编程中的新手。在我的应用程序中,我显示存储在我的资源文件夹中的PDF的第一页的缩略图。我使用下面的代码来创建缩略图,并且它适用于横向PDF。但是,当创建肖像PDF缩略图时,我得到了一些额外部分的图像,我无法看到在webview中打开PDF时的情况。在iPhone中创建肖像pdf的缩略图

这是我使用来创建缩略图的代码:

NSURL * pdfFileUrl = [NSURLfileURLWithPath:文件路径]。
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(((CFURLRef)pdfFileUrl);

  CGRect aRect = CGRectMake(0, 0, 1024, 768); 
      UIGraphicsBeginImageContext(aRect.size); 
      CGContextRef context = UIGraphicsGetCurrentContext();      

      CGContextSaveGState(context);     
      CGContextTranslateCTM(context, 0.0, aRect.size.height); 
      CGContextScaleCTM(context, 1.0, -1.0); 
      CGContextTranslateCTM(context, -(aRect.origin.x), -(aRect.origin.y)); 

      CGContextSetGrayFillColor(context, 1.0, 1.0); 
      CGContextFillRect(context, aRect);    

      //Grab the first PDF page 
      CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1); 
      CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, aRect, 0, false); 
      // And apply the transform. 
      CGContextConcatCTM(context, pdfTransform);    
      CGContextDrawPDFPage(context, page); 

      // Create the new UIImage from the context 
      UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext(); 

      CGContextRestoreGState(context);   
      UIGraphicsEndImageContext();  
      CGPDFDocumentRelease(pdf); 

在创建使用此代码肖像PDF的缩略图,我得到的图像是不准确的。它有一些额外的部分。我认为这是该PDF的一些隐藏部分。另外,当我在UIWebView中加载相同的PDF时,我可以在没有额外部分的情况下查看正确的PDF。任何人都可以为我提供解决方案吗?

谢谢。

回答

0

我发现问题在于服用CGRect。我使用iPad对齐方式对rect进行了硬编码。实际上,我们必须采用我们正在使用的PDF页面的矩形。所以我在我的代码中使用了以下更改来制作PDF的正确缩略图。

CGPDFPageRef页= CGPDFDocumentGetPage(PDF,1); //抓斗的第一PDF页面

的CGRect aRect = CGPDFPageGetBoxRect(页面,kCGPDFCropBox); //获取与所述类型相关联的PDF页面的矩形(kCGPDFCropBox)