2013-05-17 3 views
4

Я создаю pdf от UIView до pdf, он отлично работает, но у меня есть scrollView с контентом, который я хочу преобразовать в pdf, но он отображает только видимую часть в pdf, а не весь контент scrollView. Вот мой кодСоздание PDF из UIScrollView в приложении iphone

-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename 
{  
    NSMutableData *pdfData = [NSMutableData data]; 

    // Get Scrollview size 
    CGRect scrollSize = CGRectMake(1018,76,scrollView.contentSize.width,scrollView.contentSize.height); 

    // Points the pdf converter to the mutable data object and to the UIView to be converted 
    UIGraphicsBeginPDFContextToData(pdfData, scrollSize, nil); 
    UIGraphicsBeginPDFPage(); 
    CGContextRef pdfContext = UIGraphicsGetCurrentContext(); 


    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData 

    [aView.layer renderInContext:pdfContext]; 





    // remove PDF rendering context 
    UIGraphicsEndPDFContext(); 

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

    NSString* documentDirectory = [documentDirectories objectAtIndex:0]; 
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename]; 

    // instructs the mutable data object to write its context to a file on disk 
    [pdfData writeToFile:documentDirectoryFilename atomically:YES]; 
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename); 
} 
+0

Посетите этот ответ, это поможет вам. http://stackoverflow.com/a/6566696/1223897 – Yuvrajsinh

+0

@Yuvrajsinh это тот же самый код, который я использую, но это для равнины не UIScrollView –

+0

Я думаю, что проблема, вы создаете новый UIView с статический размер. Используйте свойScrollView.contentSize для получения точного размера содержимого (ширина, высота) в вашем scrollview и без необходимости создания нового представления. – Yuvrajsinh

ответ

1

THis дает видимую часть UIScrollView

CGRect visibleRect; 
visibleRect.origin = scrollView.contentOffset; 
visibleRect.size = scrollView.bounds.size; 

float theScale = 1.0/scale; 
visibleRect.origin.x *= theScale; 
visibleRect.origin.y *= theScale; 
visibleRect.size.width *= theScale; 
visibleRect.size.height *= theScale; 

так что вы можете использовать это в UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
некоторыми незначительными изменениями параметров.

+0

где написать этот код Вы можете изменить в моем коде, пожалуйста, –

+0

и какой масштаб он не объявлен, он дает ошибку –

+0

Каков масштаб, можете ли вы мне помочь –

1
(void)createPDFfromUIView:(UIScrollView*)aView saveToDocumentsWithFileName:(NSString*)aFilename 
{ 
    // Creates a mutable data object for updating with binary data, like a byte array 
    NSMutableData *pdfData = [NSMutableData data]; 

    // Get Scrollview size 
    CGRect scrollSize = CGRectMake(aView.origin.x,aView.origin.y,aView.contentSize.width,aView.contentSize.height); 

    // Points the pdf converter to the mutable data object and to the UIView to be converted 
    UIGraphicsBeginPDFContextToData(pdfData, scrollSize, nil); 
    UIGraphicsBeginPDFPage(); 
    CGContextRef pdfContext = UIGraphicsGetCurrentContext(); 


    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData 

    [aView.layer renderInContext:pdfContext]; 

    // remove PDF rendering context 
    UIGraphicsEndPDFContext(); 

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

    NSString* documentDirectory = [documentDirectories objectAtIndex:0]; 
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename]; 

    // instructs the mutable data object to write its context to a file on disk 
    [pdfData writeToFile:documentDirectoryFilename atomically:YES]; 
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename); 
} 
+0

aView.originalx мы должны дать оригинальное ПОлОжЕНИЕ Scrollview –

+0

те же проблемы, показывающее видимое содержание в PDF –

+0

Этих ответы имеют сложные решения передать его: http://stackoverflow.com/a/5405944/1223897 Http: //stackoverflow.com/a/14292471/1223897 – Yuvrajsinh

1

Этот код я использовал, чтобы сделать PDF из UIScrollView и это действительно помогает, но это не будет столь же хорошо, как если бы мы опираемся на PDF - пожалуйста, смотрите - Pdf от UIScrollView

- (void) createPDF 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *directroyPath = nil; 
    directroyPath = [documentsDirectory stringByAppendingPathComponent:@"temp"]; 
    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:_scrollView2.bounds path:(CFStringRef)filePath]; 
    NSLog(@"PDF Context created"); 

    /* 
    Here limit of i is no of pages in your uiscrollview or 
    you can use hit and trial here because there is a 
    length of page is going to be equal to 
    the visible size of uiscrollView in your application 
    */ 

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

     // page 1 
     CGContextBeginPage (pdfContext,nil); 

     //turn PDF upsidedown 
     CGAffineTransform transform = CGAffineTransformIdentity; 

     //here 365 is equal to the height of myScrollView.frame.size.height 

     transform = CGAffineTransformMakeTranslation(0, (i+1) * 365); 
     transform = CGAffineTransformScale(transform, 1.0, -1.0); 
     CGContextConcatCTM(pdfContext, transform); 

     //Draw view into PDF 
     [_scrollView2.layer renderInContext:pdfContext]; 
     CGContextEndPage (pdfContext); 
     [_scrollView2 setContentOffset:CGPointMake(0, (i+1) * 365) 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; 
} 
Смежные вопросы