2012-06-11 33 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)