PDF Generation From UIScrollView + iphone

后端 未结 3 1735
半阙折子戏
半阙折子戏 2021-01-03 11:08

I want to generate a pdf of UIScrollView whose content size is near about 320*2000. If I use current graphic image context to capture the scroll view layer, then it only cap

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 11:57

    I came up with a different solution:

    -(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;}
    

    Size the frame to fit the entire content of the scrollView, capture it in graphicsContext, size the frame back.

    The upper code generates one page.
    For more pages I use basically this:

    //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();
    

提交回复
热议问题