2011-03-11 5 views
3

약 320 * 2000에 가까운 컨텐츠 크기를 가진 UIScrollView의 pdf를 생성하고 싶습니다. 현재 그래픽 이미지 컨텍스트를 사용하여 스크롤 뷰 레이어를 캡처하면 스크롤 뷰의 전체 레이어가 아닌 스크롤 뷰의 가시적 인 부분 만 캡쳐합니다. 샘플 코드는, 내가 같은 정확하게 일을하려고하시기 바랍니다 볼PDF 생성 UIScrollView + iphone

-(void)CreatePdf:(id)sender 
{ 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *saveDirectory = [paths objectAtIndex:0]; 
    NSString *saveFileName = @"myPDF.pdf"; 
    [self writePDFAma]; 
    CGRect arect=CGRectMake(0, 0, 768, 1024); 

    CreatePDFFileAma(arect, nil); 
} 



-(void) writePDFAma 
{ 
    UIImage *image; 
    NSData *data; 
    UIAlertView *successAlert; 
    UIAlertView *failureAlert; 
    // 
    NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    // // This should be our documents directory 
    NSString *saveDiirectory = [documentPath objectAtIndex:0]; 
    // // Our PDF is named 'Example.pdf' 
    NSString *saveFileName = @"FormImage2.JPG"; 
    // // Create the full path using our saveDirectory and saveFileName 
    NSString *finalPath = [saveDiirectory stringByAppendingPathComponent:saveFileName]; 
    //NSLog(@"%@",finalPath); 
    CGSize asize=CGSizeMake(_scrollview.frame.size.width, _scrollview.frame.size.height); 
    //NSLog(@"%d..%d",mainViewAma.frame.size.width, mainViewAma.frame.size.height); 
    UIGraphicsBeginImageContext(asize); 
     [[_scrollview layer] renderInContext:UIGraphicsGetCurrentContext()]; 
image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    data = UIImageJPEGRepresentation(image, 1.0); 

    BOOL catch; 
    if(!catch){ 
     if ([[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil]) 
     { 
      successAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Doodle was successfully saved to the Photo Library." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil]; 
      //[successAlert show]; 
      [successAlert release]; 
     } else { 
      failureAlert = [[UIAlertView alloc] initWithTitle:@"Failure" message:@"Failed to save doodle to the Photo Library." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil]; 
      //[failureAlert show]; 
      [failureAlert release]; 
     } 

    } 

} 


void CreatePDFFileAma (CGRect pageRect, const char *filename) 
{ 
    // This code block sets up our PDF Context so that we can draw to it 
    //some code here 
    CGContextRef pdfContext; 
    CFURLRef url; 
    CFMutableDictionaryRef myDictionary = NULL; 
    NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    // // This should be our documents directory 
    NSString *saveDirectory = [documentPath objectAtIndex:0]; 
    // // Our PDF is named 'Example.pdf' 



    //NSString *saveFileName = @"PDFForm2.pdf"; 



    // // Create the full path using our saveDirectory and saveFileName 
    NSString *finalPath = [saveDirectory stringByAppendingPathComponent:saveFileName]; 
    NSURL * aurl=[[NSURL alloc]initFileURLWithPath:finalPath]; 
    url=(CFURLRef)aurl; 
    // This dictionary contains extra options mostly for 'signing' the PDF 
    myDictionary = CFDictionaryCreateMutable(NULL, 0, 
              &kCFTypeDictionaryKeyCallBacks, 
              &kCFTypeDictionaryValueCallBacks); 
    CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("AMA FORM PDF")); 
    CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name2")); 
    // Create our PDF Context with the CFURL, the CGRect we provide, and the above defined dictionary 
    pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary); 
    // Cleanup our mess 
    CFRelease(myDictionary); 
    CFRelease(url); 
    // Starts our first page 
    CGContextBeginPage (pdfContext, &pageRect); 

    // Draws a black rectangle around the page inset by 50 on all sides 
    CGContextStrokeRect(pdfContext, CGRectMake(50, 50, 768, 1024)); 

    // This code block will create an image that we then draw to the page 
    CGImageRef image; 
    CGDataProviderRef provider; 
    CFURLRef pictureURL; 
    documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    // // This should be our documents directory 
    saveDirectory = [documentPath objectAtIndex:0]; 
    NSString *saveFileName2 = @"FormImage2.JPG"; 
    // // Create the full path using our saveDirectory and saveFileName 
    NSString *finalPath2 = [saveDirectory stringByAppendingPathComponent:saveFileName2]; 
    NSURL * aurl2=[[NSURL alloc]initFileURLWithPath:finalPath2]; 
    pictureURL=(CFURLRef)aurl2; 
    provider = CGDataProviderCreateWithURL (pictureURL); 
    CFRelease (pictureURL); 
    image = CGImageCreateWithJPEGDataProvider(provider, NULL, TRUE, kCGRenderingIntentDefault); //DataProvider (, NULL, true, kCGRenderingIntentDefault); 
    CGDataProviderRelease (provider); 
    CGContextDrawImage (pdfContext, CGRectMake(0, 0,768, 1024),image); 
    CGImageRelease (image); 
    CGContextEndPage (pdfContext); 
    // We are done with our context now, so we release it 
    CGContextRelease (pdfContext); 
} 

답변

0

이 가능하다 :

나는 아래의 코드를 사용하고 있습니다.

당신은 볼을 캡처 :

당신은 여기에 당신이 당신의 문제에 대한 어쨌든

어쩌면이 도움이 될 수 있습니다 [email protected] 매우 관대 한 것이라고에 대한 감사의 소스 코드를 보낼 수 스크롤 뷰의 크기가 표시 내용과 일치해야만 해당 내용이 표시됩니다.

코드 : self.scrollView.frame = CGRectMake (0, 0, "your content width here") 다음과 같은 방법을 사용하여 드로잉 코드를 시작하기 전에 캡처해야하는 콘텐츠와 일치하도록 스크롤 뷰의 크기를 조정해야합니다. , "귀하의 콘텐츠 높이"); 당신은 컨테이너보기로이 경우, 백업하기 위해 스크롤 뷰의 크기를 조정해야합니다 그리기 완료 후 :

코드 : self.scrollView.frame = CGRectMake (0, 0, self.view.frame.size .width, self.view.frame.size.height);

+0

안녕 마르코 난 당신의 논리를 implimenting에 의해 시도했지만 나를 위해 작동 나던 : 더 많은 페이지에 대한
나는 기본적으로이 사용합니다. – ravoorinandan

7

ㅎ들, 난 우리는 두 가지

1) 페이지 수 2) contentsize 있는 ScrollView의에 대해 명확해야한다있는 UIScrollView 에서 PDF를 만들 그물에 사용할 수있는 예제를 사용하여 일부 코드베이스를 준비

콘텐츠 크기 (10 * 910)의 스크롤보기를 만들었습니다. 그래서 그것은 10 페이지가 있습니다.. 이것은 iPad 용입니다. 여기

내가 다른 해결책을 함께 제공되는 코드베이스

- (void) createPDF 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *directroyPath = nil; 
    directroyPath = [documentsDirectory stringByAppendingPathComponent:@"PDF"]; 
    NSString *filePath = [directroyPath stringByAppendingPathComponent:@"test.pdf"]; 
    // check for the "PDF" directory 
    NSError *error; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 

    } else { 
     [[NSFileManager defaultManager] createDirectoryAtPath:directroyPath 
            withIntermediateDirectories:NO 
                attributes:nil 
                 error:&error]; 
    } 

    CGContextRef pdfContext = [self createPDFContext:myScrollView.bounds path:(CFStringRef)filePath]; 
    NSLog(@"PDF Context created"); 

    for (int i = 0 ; i< 10 ; i++) 
    { 

     // page 1 
     CGContextBeginPage (pdfContext,nil); 

     //turn PDF upsidedown 
     CGAffineTransform transform = CGAffineTransformIdentity;  
     transform = CGAffineTransformMakeTranslation(0, (i+1) * 910); 
     transform = CGAffineTransformScale(transform, 1.0, -1.0); 
     CGContextConcatCTM(pdfContext, transform); 

     //Draw view into PDF 
     [myScrollView.layer renderInContext:pdfContext];  
     CGContextEndPage (pdfContext);   
     [myScrollView setContentOffset:CGPointMake(0, (i+1) * 910) animated:NO]; 

    } 
    CGContextRelease (pdfContext); 
} 

- (CGContextRef) createPDFContext:(CGRect)inMediaBox path:(CFStringRef) path  
{ 
    CGContextRef myOutContext = NULL; 
    CFURLRef url; 
    url = CFURLCreateWithFileSystemPath (NULL, path,           
             kCFURLPOSIXPathStyle,          
             false); 

    if (url != NULL) {  
     myOutContext = CGPDFContextCreateWithURL (url, 
                &inMediaBox,             
                NULL);   
     CFRelease(url);  
    } 
    return myOutContext; 
} 
+0

안녕 Nikesh, 내가 당신의 코드를 시도했지만 미리보기도 아크로뱃도 열 수 없기 때문에 내가 만든 PDF가 분명히 망가졌습니다 ... 당신은 아이디어가 있습니까? – Faser

+1

@UrbanSeifert .pdf 파일 확장명으로 PDF 파일 이름의 이름을 지정 했습니까? – Bek

+0

@ Nikesh .. 코드에 감사드립니다. 그것은 완벽하게 작동하지만 표시되는 컨트롤러도 변경되지 않고 내 페이지가 변경되지 않는 한 가지 문제가 있습니다. 예를 들면. 나는 페이지 2에 있는데, 페이지 1에는 절반을, 페이지 2에는 절반을 표시하는 하나의 버튼이 있습니다. 이에 대한 해결책이 있습니까? – Abha

5

입니다 : graphicsContext에서 캡처,

-(NSData*)pdfDataFromTableViewContent{ 
    NSMutableData *pdfData = [NSMutableData data]; 
    //The real size, not only the visible part 
    CGSize contentSize = self.tableView.contentSize; 
    CGRect tableViewRealFrame = self.tableView.frame; 
    //Size tableView to show the whole content 
    self.tableView.frame = CGRectMake(0, 0, contentSize.width, contentSize.height); 
    //Generate PDF (one page) 
    UIGraphicsBeginPDFContextToData(pdfData,self.tableView.frame, nil); 
    UIGraphicsBeginPDFPage(); 
    [self.tableView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIGraphicsEndPDFContext(); 
    //Resize frame 
    self.tableView.frame = tableViewRealFrame; 
    return pdfData;} 

크기있는 ScrollView의 전체 내용에 맞도록 프레임 크기 프레임 뒤로.

위 코드는 한 페이지를 생성합니다.

//MultiPage 
CGRect mediaBox = self.tableView.frame; 
CGSize pageSize = CGSizeMake(self.view.frame.size.width, 800); 
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil); 
CGContextRef pdfContext = UIGraphicsGetCurrentContext(); 
NSInteger currentPage = 0; 
BOOL done = NO; 
do { 
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0.0, pageSize.width, pageSize.height), nil); 
    CGContextTranslateCTM(pdfContext, 0, -(pageSize.height*currentPage)); 
    [self.view.layer renderInContext:pdfContext]; 
    if ((pageSize.height*(currentPage+1)) > mediaBox.size.height) done = YES; 
    else currentPage++; 
} while (!done); 
UIGraphicsEndPDFContext();