//
//  GeneratePdf.m
//  ZeroRec
//
//  Created by AIG-Soft on 11/04/05.
//  Copyright 2011 AIG-Soft. All rights reserved.
//
// from DrawingPrintingiOS.pdf;ただし、バグがあるので修正

#import "GeneratePdf.h"
#import "FileControl2.h"
#import "NSString+drawiOS7.h"
#import "NSString+sizeWithFont.h"

@implementation GeneratePdf

- (CFRange)renderPage:(NSInteger)pageNum withTextRange:(CFRange)currentRange andFramesetter:(CTFramesetterRef)framesetter
// Use Core Text to draw the text in a frame on the page.
{
	// Get the graphics context.
	CGContextRef currentContext = UIGraphicsGetCurrentContext();
	// Put the text matrix into a known state. This ensures
	// that no old scaling factors are left in place.
	CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
	// Create a path object to enclose the text. Use 72 point
	// margins all around the text. 
	CGRect	frameRect = CGRectMake(72, 72, 468, 648);
	CGMutablePathRef framePath = CGPathCreateMutable();
	CGPathAddRect(framePath, NULL, frameRect);
	// Get the frame that will do the rendering.
	// The currentRange variable specifies only the starting point.
	// The framesetter lays out as much text as will fit into the frame.
	CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
	CGPathRelease(framePath);
	// Core Text draws from the bottom-left corner up, so flip 
	// the current transform prior to drawing. 
	CGContextTranslateCTM(currentContext, 0, 792);
	CGContextScaleCTM(currentContext, 1.0, -1.0);
	// Draw the frame. 
	CTFrameDraw(frameRef, currentContext);
	// Update the current range based on what was drawn. 
	currentRange = CTFrameGetVisibleStringRange(frameRef);
	currentRange.location += currentRange.length;
	currentRange.length = 0;
	CFRelease(frameRef);
	return currentRange;
}

- (void)drawPageNumber:(NSInteger)pageNum
{
	NSString* pageString = [NSString stringWithFormat:NSLocalStr(@"PAGE"), pageNum];
	UIFont* theFont = [UIFont systemFontOfSize:12];
	CGSize maxSize = CGSizeMake(612, 72);
	CGSize pageStringSize = [pageString sizeWithFont7:theFont constrainedToSize:maxSize lineBreakMode:NSLineBreakByClipping];
	CGRect stringRect = CGRectMake(((612.0 - pageStringSize.width) / 2.0),
								   720.0 + ((72.0 - pageStringSize.height) / 2.0),
								   pageStringSize.width,
								   pageStringSize.height);
	[pageString drawInRect7:stringRect withFont:theFont withColor:[UIColor blackColor]];
}


- (void)savePDFFile:(NSString *)text fname:(NSString *)pdfname
{
	// Core Text Framesetterで使うテキストを準備する
	CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, (CFStringRef)text, NULL);
	if (currentText) {
		CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
		if (framesetter) {
			// Create the PDF context using the default page size of 612 x 792.
			UIGraphicsBeginPDFContextToFile(pdfname, CGRectZero, nil);
			CFRange currentRange = CFRangeMake(0, 0);
			NSInteger currentPage = 0;
			do { // 新しいページの始まりに印をつける
				UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
				// 各ページの先頭にページ番号を描画する
				currentPage++;
				[self drawPageNumber:currentPage];
				// Render the current page and update the current range to point to the beginning of the next page.
				currentRange = [self renderPage:currentPage withTextRange:currentRange andFramesetter:framesetter];
				// テキストの終わりまで来たらループを抜ける
			} while (currentRange.location != CFAttributedStringGetLength((CFAttributedStringRef)currentText));
			// PDF contextを閉じ、内容を書き出す.
			// text中に\nが含まれていると↓ここで"<Error> unsupported 'Zapf' version 00020000"が出る。が、実害はないので無視する。
			UIGraphicsEndPDFContext();
			// framesetterのrelease
			CFRelease(framesetter);
		} else {
			nslog(@"属性付き文字列のレイアウトに必要なframesetterを生成できません"); }
		// 属性付き文字列のRelease
		CFRelease(currentText);
	} else {
		nslog(@"framesetterのための属性付き文字列が生成できません");
	}
}

@end
