2013-05-07 2 views
6

다중 페이지 PDF를 작성하려고합니다. 나는 이것을 따라 갔다 tutorial. 정적 텍스트 용 XIB 파일로 작업 한 다음 코드에서 테이블을 추가합니다. 하지만 ATM을 사용하는 데 문제가되는 것은 테이블이 커지면 한 페이지 큽니다. 테이블에 9 행 이상있을 때. 다음 페이지에서 계속 진행해야합니다.다중 페이지 PDF를 objective-c로 작성하십시오.

이것은 내가 코드에서 수행하고있는 작업입니다.

+(void)drawPDF:(NSString*)fileName 
{ 
    NSMutableDictionary *mutDictValues = [[[NSUserDefaults standardUserDefaults] objectForKey:@"dicValues"] mutableCopy]; 
    NSMutableArray *arrSelectedCities = [[mutDictValues objectForKey:@"cities"]mutableCopy ]; 

    if(arrSelectedCities.count <= 8){ 
     // If there are only 8 rows --> we can fit everyting on one page ! 

     // Create the PDF context using the default page size of 612 x 792. 
     UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil); 
     // Mark the beginning of a new page. 
     UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil); 

     [self drawLabels]; 
     [self drawLogo]; 

     int xOrigin = 50; 
     int yOrigin = 350; 

     int rowHeight = 50; 
     int columnWidth = 240; 

     int numberOfRows = 9; 
     int numberOfColumns = 2; 

     [self drawTableAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns]; 

     [self drawTableDataAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns withArray:arrSelectedCities]; 

     // Close the PDF context and write the contents out. 
     UIGraphicsEndPDFContext(); 

    }else{ 
     // When we have more then 8 rows we should have 2 pages. 
     NSLog(@"Create 2 pages"); 
     // Create the PDF context using the default page size of 612 x 792. 
     UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil); 
     // Mark the beginning of a new page. 
     UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil); 

     [self drawLabels]; 
     [self drawLogo]; 

     int xOrigin = 50; 
     int yOrigin = 350; 

     int rowHeight = 50; 
     int columnWidth = 240; 

     int numberOfRows = 9; 
     int numberOfColumns = 2; 

     [self drawTableAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns]; 

     [self drawTableDataAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns withArray:arrSelectedCities]; 


     // Create the PDF context using the default page size of 612 x 792. 
     UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil); 
     // Mark the beginning of a new page. 
     UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil); 


     int xOrigin2 = 50; 
     int yOrigin2 = 60; 
     int numberOfRows2 = ((arrSelectedCities.count+1)-9); 

     [self drawTableAt:CGPointMake(xOrigin2, yOrigin2) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows2 andColumnCount:numberOfColumns]; 

     [self drawTableDataAt:CGPointMake(xOrigin2, yOrigin2) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows2 andColumnCount:numberOfColumns withArray:arrSelectedCities]; 


    } 
    // Close the PDF context and write the contents out. 
    UIGraphicsEndPDFContext(); 
} 

내가 여기서하고있는 일을 설명하겠습니다. 내 tableview 채우기합니다 배열이 있습니다. 배열이 8보다 크면 2 페이지를 사용해야합니다. 다른 모든 것은 한 페이지로 작동합니다. 이, 그것은 단지 두 번째 페이지를 만드는 것입니다 무엇을

....

아무도 나를 도와 드릴까요? 단지 UIGraphicsBeginPDFPageWithInfo() 두 번째 페이지를 만들 때 다시 UIGraphicsBeginPDFContextToFile()를 호출해서는 안

답변

15

, 가 :

UIGraphicsBeginPDFContextToFile(...); 
UIGraphicsBeginPDFPageWithInfo(...); // start first page 
// ... 
UIGraphicsBeginPDFPageWithInfo(...); // start second page 
// ... 
UIGraphicsEndPDFContext(); 
+0

를 사용! 고마워 친구 ! – Steaphann

+0

일부 변경 사항은이 하나의 완벽한 다중 페이지 PDF를 생성하기 위해 일했습니다. 고마워. :) –

0

당신은 두 번째 페이지 (UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil))에 대한 상황을 만들 필요가 없습니다, 당신은이 페이지를 만들어야합니다. CGPDFContextEndPage()을 사용하여 열린 페이지를 닫는 것에 대해서도 기억해야합니다.

+0

어떻게하면 두 번째 페이지를 만들 수 있습니까? – Steaphann

+0

@Tomasz : UIGraphicsBeginPDFPageWithInfo() 및 UIGraphicsEndPDFContext()는 현재 페이지를 닫습니다. CGPDFContextEndPage()는 이해할 수 있듯이 여기서 사용되지 않는 CGPDFContextBeginPage()에 해당합니다. –

+0

@ MartinR - 당신 말이 맞아, 나는 틀린 매크로 였어. –

1
NSArray *imageArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"3.png"], [UIImage imageNamed:@"4.png"], [UIImage imageNamed:@"5.png"], [UIImage imageNamed:@"3.png"], nil]; 



NSMutableData *pdfFile = [[NSMutableData alloc] init]; 
double pageWidth = 0.0; 
double pageHeight = 0.0; 
UIImage *image; 
for (int i = 0; i < [imageArray count]; i++) 
{ 
    image =[UIImage imageWithCGImage:[imageArray[i] CGImage]]; 
    pageWidth = pageWidth + image.size.width ; 
    pageHeight = pageHeight + image.size.height; 
} 
image =[UIImage imageWithCGImage:[imageArray[0] CGImage]]; 
CGRect rect; 
rect = CGRectMake(0, 0,image.size.width ,image.size.height); 
UIGraphicsBeginPDFContextToData(pdfFile, CGRectZero, nil); 
for (int i = 0; i < [imageArray count] ; i++) 
{ 
    UIGraphicsBeginPDFPageWithInfo(rect, nil); 
    UIImage *contextImage = imageArray[i]; 
    [contextImage drawInRect:rect]; 
} 
UIGraphicsEndPDFContext(); 

// save PDF file 
NSString *saveFileName = [NSString stringWithFormat:@"%@%fx%f.pdf", @"test", pageWidth, pageHeight]; 

NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); 

NSString* documentDirectory = [documentDirectories objectAtIndex:0]; 
NSString* savePath = [documentDirectory stringByAppendingPathComponent:saveFileName]; 

if([[NSFileManager defaultManager] fileExistsAtPath:savePath]) 
{ 
    [[NSFileManager defaultManager] removeItemAtPath:savePath error:nil]; 
} 
[pdfFile writeToFile: savePath atomically: YES]; 
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"PDF File created and saved successfully." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
[alert show]; 
+0

이 질문에 대한 좋은 대답 일지 모르지만, 왜 *이 문제에 대한 설명을 게시 해주십시오. – Glorfindel

0
- (void)viewDidLoad { 
[super viewDidLoad]; 
[self createPDF]; 
} 

- (void)createPDF { 
[self setupPDFDocumentNamed:@"myPdf" Width:850 Height:1100]; 
[self beginPDFPage]; 
    } 

    - (void)beginPDFPage { 
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil); 

// kPadding will make 20 points margin on both sides of pdf 
CGRect textRect = [self addText:@"Line Text Testing" withFrame:CGRectMake(PdfPadding, PdfPadding, 400, 200) fontSize:48.0f]; 

textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height +PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor blueColor]]; 

UIImage *anImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://www.phantompeer.com/sitefiles/osx.png"]]]; 
textRect = [self addImage:anImage atPoint:CGPointMake((pageSize.width/2)-(anImage.size.width/2),textRect.origin.y + textRect.size.height + PdfPadding)]; 
textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height + PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor redColor]]; 

textRect = [self addText:@"Line Text Testing" withFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height + PdfPadding, 400, 200) fontSize:48.0f]; 

textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height +PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor blueColor]]; 

anImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://www.w3schools.com/css/img_fjords.jpg"]]]; 
    textRect = [self addImage:anImage atPoint:CGPointMake((pageSize.width/2)-(anImage.size.width/2),textRect.origin.y + textRect.size.height + PdfPadding)]; 

textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height + PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor redColor]]; 


UIGraphicsEndPDFContext(); 
[self loadRemotePdf]; 
    } 
-(CGRect)addText:(NSString*)text withFrame:(CGRect)frame fontSize:(float)fontSize { 



UIFont *font = [UIFont systemFontOfSize:fontSize]; 
CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(pageSize.width - 2*20-2*20, pageSize.height - 2*20 - 2*20) lineBreakMode:UILineBreakModeWordWrap]; 



if((frame.origin.y + stringSize.height + PdfPadding) > pageSize.height) { 
    frame = CGRectMake(frame.origin.x, PdfPadding, frame.size.width, frame.size.height); 
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil); 
} 

float textWidth = frame.size.width; 

if (textWidth < stringSize.width) 
    textWidth = stringSize.width; 
if (textWidth > pageSize.width) 
    textWidth = pageSize.width - frame.origin.x; 


CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height); 

[text drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft]; 

frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height); 

return frame; 
} 

-(CGRect)addLineWithFrame:(CGRect)frame withColor:(UIColor*)color { 


if((frame.origin.y + frame.size.height+PdfPadding) > pageSize.height) { 
    frame = CGRectMake(frame.origin.x, PdfPadding, frame.size.width, frame.size.height); 
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil); 
} 

CGContextRef currentContext = UIGraphicsGetCurrentContext(); 
CGContextSetStrokeColorWithColor(currentContext, color.CGColor); 

// this is the thickness of the line 
CGContextSetLineWidth(currentContext, frame.size.height); 
CGPoint startPoint = frame.origin; 
CGPoint endPoint = CGPointMake(frame.origin.x + frame.size.width, frame.origin.y); 

CGContextBeginPath(currentContext); 
CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y); 
CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y); 

CGContextClosePath(currentContext); 
CGContextDrawPath(currentContext, kCGPathFillStroke); 



return frame; 
     } 


-(CGRect)addImage:(UIImage*)image atPoint:(CGPoint)point { 
CGRect imageFrame = CGRectMake(point.x, point.y, image.size.width, image.size.height); 

if((imageFrame.origin.y + imageFrame.size.height + PdfPadding) > pageSize.height) { 
    imageFrame = CGRectMake(imageFrame.origin.x, PdfPadding, imageFrame.size.width, imageFrame.size.height); 
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil); 
} 
[image drawInRect:imageFrame]; 
return imageFrame; 
} 

- (void) loadRemotePdf 
{ 
CGRect rect = [[UIScreen mainScreen] bounds]; 
CGSize screenSize = rect.size; 


NSString *newPDFName = [NSString stringWithFormat:@"myPdf.pdf"]; 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName]; 

UIWebView *myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)]; 
myWebView.autoresizesSubviews = YES; 
myWebView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth); 

NSURL *myUrl = [NSURL fileURLWithPath:pdfPath]; 
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl]; 

[myWebView loadRequest:myRequest]; 

[self.view addSubview: myWebView]; 
} 

PDF에 새 페이지를 만들 경우, 이것은 나를 위해 일한

UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil); 
관련 문제