2014-04-09 3 views
0

다음 코드를 사용하여 WebView를 PDf로 변환 중입니다.페이지 나누기없이 PDF를 생성하는 방법

UIWebView *webView = self.webView; 
     NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"]; 

     int height = [heightStr intValue]; 
     // CGRect screenRect = [[UIScreen mainScreen] bounds]; 
     // CGFloat screenHeight = (self.contentWebView.hidden)?screenRect.size.width:screenRect.size.height; 
     CGFloat screenHeight = webView.bounds.size.height; 
      int pages = ceil(height/screenHeight); 

     NSMutableData *pdfData = [NSMutableData data]; 
     UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil); 
     CGRect frame = [webView frame]; 
     for (int i = 0; i < pages; i++) { 
      // Check to screenHeight if page draws more than the height of the UIWebView 
      if ((i+1) * screenHeight > height) { 
       CGRect f = [webView frame]; 
       f.size.height -= (((i+1) * screenHeight) - height); 
       f.size.width = self.webView.bounds.size.width*1.6; 
       [webView setFrame: f]; 
      } 

      UIGraphicsBeginPDFPage(); 
      CGContextRef currentContext = UIGraphicsGetCurrentContext(); 
      //  CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins 

      [[[webView subviews] lastObject] setContentOffset:CGPointMake(0, screenHeight * i) animated:NO]; 
      [webView.layer renderInContext:currentContext]; 
     } 

     UIGraphicsEndPDFContext(); 
     // Retrieves the document directories from the iOS device 
     NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); 

     NSString* documentDirectory = [documentDirectories objectAtIndex:0]; 
     NSString* documentDirectoryFilename =[documentDirectory stringByAppendingString:@"/pdfFile.PDF"] ; 

     // instructs the mutable data object to write its context to a file on disk 
     [pdfData writeToFile:documentDirectoryFilename atomically:YES]; 
     [webView setFrame:frame]; 

하지만 문제는 그림과 같이 페이지 나누기가있는 PDF를 생성하는 것입니다. enter image description here

내가 어떤 일 break.can이 페이지는 내가 무엇을해야하는지 제시하지 않습니다.

답변

1

당신은

UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil); 

현재 적절한 값 webView.bounds

변경을 설정 여기에서 페이지 크기를 설정합니다.

+0

그래, 내가 웹보기의있는 ScrollView에 높이 동등 물이 CGRect 변수와 webView.bounds 변화, 그리고 작업의 [[[웹뷰 파단] lastObject] setContentOffset : CGPointMake (0 screenHeight * I) 애니메이션 : NO] 없다 가변 높이로 screenHeight * i를 변경했습니다. int 페이지 = ceil (height/screenHeight)을 int 페이지 = 1로 바꿨습니다. –

0

이 작은 CSS는 나를 위해 일했습니다.

@media print { 
     .avoid_pagebreak { display: block; page-break-inside:avoid; page-break-before: auto; } 
    } 
    ... 
    <div class="avoid_pagebreak"> 
    ... 
    </div> 
관련 문제