// // PDFUtils.m // AntsContract // // Created by Ray on 12/20/16. // Copyright © 2016 United Software Applications, Inc. All rights reserved. // #import "PDFUtils.h" #import "RAPDFPage.h" #import "ImageDrawable.h" #import "TextDrawable.h" #import "RectDrawable.h" #import "RAUtils.h" @implementation PDFUtils +(NSString*) addSignature :(UIImage*) img to:(NSMutableDictionary*)signatureData subType:(NSString*)subtype { if(true) { NSString* newfile=[self saveTempSignature:UIImagePNGRepresentation(img)]; int newidx = [signatureData[subtype][@"count"] intValue]; // [@"file"]= newfile; NSMutableDictionary* item = [[NSMutableDictionary alloc] init]; item[@"file"]=newfile; NSMutableDictionary* subjson =signatureData[subtype]; if(subjson==nil) subjson = [[NSMutableDictionary alloc] init]; subjson[[NSString stringWithFormat:@"item_%d",newidx]] = item; subjson[@"count"]=[NSNumber numberWithInt:newidx+1]; signatureData[subtype]=subjson; return newfile; } } +(NSString *) saveTempSignature:(NSData *) image { NSString* tempDir = NSTemporaryDirectory(); NSString *saveFileName=[NSString stringWithFormat:@"%@.png",[[NSUUID UUID ] UUIDString] ] ; NSString *newFilePath=[tempDir stringByAppendingPathComponent:saveFileName]; bool bsuccess=[image writeToFile:newFilePath atomically:YES]; if(bsuccess) { return newFilePath; } else { return nil; } } +(NSMutableDictionary*) loadControl:(NSString*)path { // NSString *path = [[NSBundle mainBundle] pathForResource:templateName ofType:nil]; NSData *data = [NSData dataWithContentsOfFile:path]; NSMutableDictionary *ret = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] mutableCopy]; return ret; } +(CGSize) QueryPDFSizeFromData:(NSData *)pdfData { CGPDFDocumentRef document = [self OpenPDFFromData:pdfData]; CGRect rect= [self QuerySize:document]; CFRelease(document); return rect.size; } +(CGRect) QuerySize:(CGPDFDocumentRef)document { CGPDFPageRef page= CGPDFDocumentGetPage (document , 1); // CGPDFPageRef page1= CGPDFDocumentGetPage (document , i); CGRect papersize=CGPDFPageGetBoxRect(page, kCGPDFMediaBox); return papersize; } + (CGPDFDocumentRef)OpenPDFFromData:(NSData *)pdfData { CFDataRef dataRef = (__bridge_retained CFDataRef)(pdfData); CGDataProviderRef proRef = CGDataProviderCreateWithCFData(dataRef); CGPDFDocumentRef pdfRef = CGPDFDocumentCreateWithProvider(proRef); CGDataProviderRelease(proRef); CFRelease(dataRef); return pdfRef; } +(CGPDFDocumentRef)OpenPDF:(NSString*) file { //获取路径 /* NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//坐标 NSString *saveDirectory=[paths objectAtIndex:0]; NSString *saveFileName=@"myPDF.pdf"; NSString *newFilePath=[saveDirectory stringByAppendingPathComponent:saveFileName]; */ NSString *default_path = file;//[[NSBundle mainBundle] pathForResource:file ofType:nil]; // const char *filename=[default_path UTF8String]; DebugLog(@"%@",default_path); //关联上下文的对象 // CGContextRef pdfContext; // CFStringRef path; // // CFURLRef url; // // path=CFStringCreateWithCString(NULL, filename, kCFStringEncodingUTF8); // // url=CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0); // CFRelease(path); CGPDFDocumentRef document; CFURLRef pdfURL = (__bridge CFURLRef)[NSURL fileURLWithPath:default_path]; // CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(pdfURL); document = CGPDFDocumentCreateWithURL (pdfURL); // CFRelease(url); // size_t totalpage = CGPDFDocumentGetNumberOfPages (document); // // if (totalpage == 0) { // printf("[%s] needs at least one page!\n", [@"myPDF.pdf" UTF8String] ); // return NULL; // } else { // printf("[%ld] pages loaded in this PDF!\n", totalpage); // // // /*8 // for (NSInteger pageNumber = 1; pageNumber <= count; pageNumber++) // { // CGPDFPageRef pageRef = CGPDFDocumentGetPage(document, pageNumber); // // CGPDFDictionaryRef pageDictionaryFromPage = CGPDFPageGetDictionary(pageRef); // // if (pageDictionaryFromPage == pageDictionaryFromDestArray) // Found it // { // targetPageNumber = pageNumber; break; // } // // // }*/ // } // CGPDFPageRef page= CGPDFDocumentGetPage(document, 0); // CGContextDrawPDFPage(<#CGContextRef _Nullable c#>, <#CGPDFPageRef _Nullable page#>) return document; } +(CGRect)WindowRect2PDFRect:(CGRect)rect pdf_rect:(CGRect)pdf_rect window_size:(CGSize)window_size { CGRect pdf_expand; float offset_x = 0; float offset_y = 0; float scale =1; if(pdf_rect.size.height>=pdf_rect.size.width) { pdf_expand = CGRectMake(0, 0, pdf_rect.size.height*window_size.width/window_size.height, pdf_rect.size.height); offset_x = (pdf_expand.size.width-pdf_rect.size.width)/2; scale = pdf_rect.size.height/window_size.height; } else { pdf_expand = CGRectMake(0, 0, pdf_rect.size.width, pdf_rect.size.width*window_size.height/window_size.width); offset_y = (pdf_expand.size.height-pdf_rect.size.height)/2; scale = pdf_rect.size.width/window_size.width; } float x=rect.origin.x*scale-offset_x; float y=rect.origin.y*scale-offset_y; float width = rect.size.width*scale; float height = rect.size.height*scale; return CGRectMake(x, y, width, height); } +(CGRect)PDFRect2WindowRect:(CGRect)rect pdf_rect:(CGRect)pdf_rect window_size:(CGSize)window_size { CGRect win_expand; float offset_x = 0; float offset_y = 0; float scale =1; if(pdf_rect.size.height>=pdf_rect.size.width) { win_expand = CGRectMake(window_size.width/2-(window_size.height*pdf_rect.size.width/pdf_rect.size.height)/2, 0, (window_size.height*pdf_rect.size.width/pdf_rect.size.height), window_size.height); offset_x = (win_expand.size.width-window_size.width)/2; scale = window_size.height/pdf_rect.size.height; } else { win_expand = CGRectMake(0, window_size.height/2-(window_size.width*pdf_rect.size.height/pdf_rect.size.width)/2, window_size.width, (window_size.width*pdf_rect.size.height/pdf_rect.size.width)); offset_y = (win_expand.size.height-window_size.height)/2; scale = window_size.width/pdf_rect.size.width; } float x=rect.origin.x*scale-offset_x; float y=rect.origin.y*scale-offset_y; float width = rect.size.width*scale; float height = rect.size.height*scale; return CGRectMake(x, y, width, height); } +(NSString*)SavePDF:(NSMutableDictionary*) controlTemplate source:(CGPDFDocumentRef )document window_rect:(CGRect)window_rect name:(NSString*)name isnew:(bool)isNewDocument { //获取路径 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//坐标 NSString *saveDirectory=[paths objectAtIndex:0]; if(name==nil) name=[[NSUUID UUID ] UUIDString]; NSString *saveFileName=[NSString stringWithFormat:@"%@.pdf",name ] ; NSString *newFilePath=[saveDirectory stringByAppendingPathComponent:saveFileName]; const char *filename=[newFilePath UTF8String]; DebugLog(@"%@",newFilePath); //设置页面大小 Letter纸 //CGPDFDocumentGetMediaBox(document,1); // CGPDFDictionaryRef pdf_dict= CGPDFDocumentGetInfo(document); //关联上下文的对象 CFStringRef path; CFURLRef url; path=CFStringCreateWithCString(NULL, filename, kCFStringEncodingUTF8); url=CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0); CFRelease(path); // CGPDFCONTEXTCREATE CGContextRef pdfContext; CGRect docsize = CGRectMake(0, 0, 612, 1008); // NSDictionary *PDFAttributes = // [NSDictionary dictionaryWithObjectsAndKeys: // @"usai2010", (NSString *)kCGPDFContextOwnerPassword, // kCFBooleanTrue, (NSString *)kCGPDFContextAllowsPrinting, // kCFBooleanFalse, (NSString *)kCGPDFContextAllowsCopying, // nil]; // // Create a descriptor. // CFDictionaryRef cfpdfAttributes =(__bridge_retained CFDictionaryRef)PDFAttributes; // CFBridgingRelease(cfpdfAttributes); CFMutableDictionaryRef myDictionary = NULL; myDictionary= CFDictionaryCreateMutable(NULL, 0, NULL, NULL); // CFDictionarySetValue(myDictionary, // kCGPDFContextTitle, // CFSTR("Photo from iPrivate Album")); // CFDictionarySetValue(myDictionary, // kCGPDFContextCreator, // CFSTR("iPrivate Album")); // //设置文档名称 // CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File")); // //设置创建者 // CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name")); //设置文档尺寸 // CFDictionarySetValue(myDictionary, kCGPDFContextOwnerPassword, CFNUMBERCREATE (40)); CFDictionarySetValue(myDictionary, kCGPDFContextOwnerPassword, CFSTR("usai2010")); // CFDictionarySetValue(myDictionary, kCGPDFContextUserPassword, CFSTR("usai2010")); CFDictionarySetValue(myDictionary, kCGPDFContextAllowsPrinting, kCFBooleanTrue); CFDictionarySetValue(myDictionary, kCGPDFContextAllowsCopying, kCFBooleanFalse); // pdfContext=CGPDFContextCreateWithURL(url, &docsize,myDictionary); CFRelease(myDictionary); CFRelease(url); size_t page_count=CGPDFDocumentGetNumberOfPages(document); for(int i=1;i<=page_count;i++) { int p = (i+4)%5+1; NSMutableDictionary* page_control=controlTemplate[[NSString stringWithFormat:@"page_%d",p-1]]; CGPDFPageRef page= CGPDFDocumentGetPage (document , p); // CGPDFPageRef page1= CGPDFDocumentGetPage (document , i); CGRect papersize=CGPDFPageGetBoxRect(page, kCGPDFMediaBox); CGContextBeginPage(pdfContext, &papersize); RAPDFPage* pdfPage = [[RAPDFPage alloc] init:nil size:papersize]; [pdfPage DirectDraw:pdfContext page:page]; for(int j=0;j<[page_control[@"count"] intValue];j++) { NSMutableDictionary* control=page_control[[NSString stringWithFormat:@"control_%d",j]]; PDFDrawable * control_drawable = nil; CGRect control_rect = CGRectMake([control[@"pos_x"] floatValue], [control[@"pos_y"] floatValue], [control[@"width"] floatValue], [control[@"height"] floatValue]); NSString* control_type = control[@"type"]; if([control_type isEqualToString:@"Signature"]||[control_type isEqualToString:@"Image"]) { NSString* value = control[@"value"]; if(value.length==0) continue; control_drawable=[[ImageDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"local" source:value hAlign:@"center" vAlign:@"middle"]; } else if([control_type isEqualToString:@"TextView"]||[control_type isEqualToString:@"Label"]||[control_type isEqualToString:@"TouchLabel"]||[control_type isEqualToString:@"DatePicker"]) { NSString* value = control[@"value"]; if(value.length==0) continue; NSString* size = control[@"size"]; if(size.length==0) size=@"10"; NSString* textAlignment=control[@"textAlignment"]; if(textAlignment.length==0) textAlignment = @"Left"; double margin_left = [control[@"margin_left"] doubleValue]; double margin_top = [control[@"margin_top"] doubleValue]; CGRect text_rect = [self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size]; control_drawable=[[TextDrawable alloc] init:text_rect source_type:@"const" source:value textAlignment:textAlignment vAlign:@"middle" size:size]; [control_drawable setMargin_left:margin_left]; [control_drawable setMargin_top:margin_top]; if(!isNewDocument&& [control[@"dirty"] boolValue]) { CGRect bg_rect= text_rect; PDFDrawable * rect_drawable = [[RectDrawable alloc] init:bg_rect color:@"0xffff00"]; if(rect_drawable) [pdfPage DirectDraw:pdfContext drawable:rect_drawable]; } } else if([control_type isEqualToString:@"Check"]) { NSArray* value = control[@"value"]; if(value.count==0) continue; NSArray* cadedate = control[@"cadedate"]; float marker_size = [control[@"marker_size"] floatValue]; for(int c=0;c=3*/) { NSString* value = marker[0][0]; if(value.length==0) continue; NSString* size = control[@"size"]; if(size.length==0) size=@"10"; control_drawable=[[TextDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"const" source:value textAlignment:@"Center" vAlign:@"middle" size:size]; } else { CGRect marker_rect= CGRectMake([marker[1][0] floatValue] ,[marker[1][1] floatValue], marker_size, marker_size); PDFDrawable * marker_drawable = [[RectDrawable alloc] init:[self WindowRect2PDFRect:marker_rect pdf_rect:papersize window_size:window_rect.size] color:@"0x000000"]; if(marker_drawable) [pdfPage DirectDraw:pdfContext drawable:marker_drawable]; } } if(!isNewDocument&& [control[@"dirty"] boolValue]) { CGRect text_rect = [self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size]; CGRect bg_rect= text_rect; PDFDrawable * rect_drawable = nil; if([control_type isEqualToString:@"Check"]) { rect_drawable = [[RectDrawable alloc] init:bg_rect color:@"0xffff00" alpha:0.2]; } else { rect_drawable = [[RectDrawable alloc] init:bg_rect color:@"0xffff00"]; } if(rect_drawable) [pdfPage DirectDraw:pdfContext drawable:rect_drawable]; } // NSString* size = control[@"size"]; // if(size.length==0) // size=@"10"; // // control_drawable=[[TextDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"const" source:value textAlignment:@"center" vAlign:@"middle" size:size]; } if(control_drawable) [pdfPage DirectDraw:pdfContext drawable:control_drawable]; } // NSMutableDictionary* tline1= [LineDrawable createlineTemplate:1 from:CGPointMake(20, 20) to:CGPointMake(500,500)]; // LineDrawable* line1=nil; // line1= [[LineDrawable alloc] init:tline1]; // // [pdfPage DirectDraw:pdfContext drawable:line1]; // NSRange range = NSMakeRange(0,9999); // [line1 Draw:pdfContext dataSource:nil ParentRect:papersize startX:0 startY:0 flipHeight:0 range:range]; CGContextEndPage(pdfContext); // CGPDFPageRelease(page); // [pdfPage Draw:pdfContext dataSource:nil]; // [self drawPage:pdfContext template:page size:papersize dataSource:data]; // CFBridgingRelease(page); } CGPDFContextClose(pdfContext); CGContextRelease(pdfContext); // CFRelease(cfpdfAttributes); // //开始画pdf // // // NSString *temtext=[[NSString alloc]init]; // // // // const char *text=(char *)[temtext UTF8String]; // // // // int width; // // // // int height; // // // // // [self newpage:pdfContext size:papersize]; // // // // CGContextRelease(pdfContext); return newFilePath; } //{ // // //获取路径 // // NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//坐标 // // NSString *saveDirectory=[paths objectAtIndex:0]; // // NSString *saveFileName=[NSString stringWithFormat:@"%@.pdf",[[NSUUID UUID ] UUIDString] ] ;; // // NSString *newFilePath=[saveDirectory stringByAppendingPathComponent:saveFileName]; // // const char *filename=[newFilePath UTF8String]; // // DebugLog(@"%@",newFilePath); // //设置页面大小 Letter纸 // // //CGPDFDocumentGetMediaBox(document,1); // // CGPDFDictionaryRef pdf_dict= CGPDFDocumentGetInfo(document); // // // // // // //关联上下文的对象 // // // // CFStringRef path; // // CFURLRef url; // // path=CFStringCreateWithCString(NULL, filename, kCFStringEncodingUTF8); // // url=CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0); // // CFRelease(path); // // CGPDFCONTEXTCREATE // // // CGContextRef pdfContext; // CGRect docsize = CGRectMake(0, 0, 100, 100); // // //// if(name.length==0) //// { //// name=@"Helvetica"; //// // name=@"DejaVu Sans"; //// } //// if(size==0) //// { //// size=10; //// } //// NSString* style = @"Regular"; //// if(bold) //// style=@"Bold"; //// //// //name=@"Courier"; // //// NSDictionary *PDFAttributes = //// [NSDictionary dictionaryWithObjectsAndKeys: //// @"usai2010", (NSString *)kCGPDFContextOwnerPassword, //// kCFBooleanTrue, (NSString *)kCGPDFContextAllowsPrinting, //// kCFBooleanFalse, (NSString *)kCGPDFContextAllowsCopying, //// nil]; //// // Create a descriptor. //// CFDictionaryRef cfpdfAttributes =(__bridge CFDictionaryRef)(PDFAttributes); //// //// //// // CFBridgingRelease(cfpdfAttributes); //// pdfContext=CGPDFContextCreateWithURL(url, &docsize,cfpdfAttributes); // // // // CFMutableDictionaryRef myDictionary = NULL; // //文档信息字典 //// myDictionary = CFDictionaryCreateMutable(NULL, 0, //// &kCFTypeDictionaryKeyCallBacks, //// &kCFTypeDictionaryValueCallBacks); //// ////// CFStringRef password = (__bridge CFStringRef)@"usai2010"; ////// CFDictionarySetValue(myDictionary, kCGPDFContextOwnerPassword, password); //// //// CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name")); //// ////// //// CFDictionarySetValue(myDictionary, kCGPDFContextOwnerPassword, CFSTR("usai2010")); ////// //// //// CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File")); //// CFDictionarySetValue(myDictionary, kCGPDFContextAllowsPrinting, kCFBooleanTrue); //// CFDictionarySetValue(myDictionary, kCGPDFContextAllowsCopying, kCFBooleanFalse); // // //创建文档 // pdfContext = CGPDFContextCreateWithURL (url, &docsize, NULL); // // // // size_t page_count=CGPDFDocumentGetNumberOfPages(document); // for(int i=1;i<=page_count;i++) // { // NSMutableDictionary* page_control=controlTemplate[[NSString stringWithFormat:@"page_%d",i-1]]; // CGPDFPageRef page= CGPDFDocumentGetPage (document , i); // // CGRect papersize=CGPDFPageGetBoxRect(page, kCGPDFMediaBox); // // // // CGContextBeginPage(pdfContext, &papersize); // // RAPDFPage* pdfPage = [[RAPDFPage alloc] init:nil size:papersize]; // // [pdfPage DirectDraw:pdfContext page:page]; // // // for(int j=0;j<[page_control[@"count"] intValue];j++) // { // NSMutableDictionary* control=page_control[[NSString stringWithFormat:@"control_%d",j]]; // // PDFDrawable * control_drawable = nil; // CGRect control_rect = CGRectMake([control[@"pos_x"] floatValue], [control[@"pos_y"] floatValue], [control[@"width"] floatValue], [control[@"height"] floatValue]); // // // NSString* control_type = control[@"type"]; // if([control_type isEqualToString:@"Signature"]||[control_type isEqualToString:@"Image"]) // { // // NSString* value = control[@"value"]; // if(value.length==0) // continue; // // // control_drawable=[[ImageDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"local" source:value hAlign:@"center" vAlign:@"middle"]; // } // else if([control_type isEqualToString:@"TextView"]||[control_type isEqualToString:@"Label"]||[control_type isEqualToString:@"DatePicker"]) // { // // NSString* value = control[@"value"]; // if(value.length==0) // continue; // NSString* size = control[@"size"]; // if(size.length==0) // size=@"10"; // NSString* textAlignment=control[@"textAlignment"]; // if(textAlignment.length==0) // textAlignment = @"Center"; // double margin_left = [control[@"margin_left"] doubleValue]; // // // control_drawable=[[TextDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"const" source:value textAlignment:textAlignment vAlign:@"middle" size:size]; // // [control_drawable setMargin_left:margin_left]; // } // else if([control_type isEqualToString:@"Check"]) // { // NSArray* value = control[@"value"]; // if(value.count==0) // continue; // NSArray* cadedate = control[@"cadedate"]; // float marker_size = [control[@"marker_size"] floatValue]; // // for(int c=0;c=3) // { // NSString* value = marker[0][0]; // if(value.length==0) // continue; // NSString* size = control[@"size"]; // if(size.length==0) // size=@"10"; // // control_drawable=[[TextDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"const" source:value textAlignment:@"Center" vAlign:@"middle" size:size]; // } // else // { // CGRect marker_rect= CGRectMake([marker[1][0] floatValue] ,[marker[1][1] floatValue], marker_size, marker_size); // PDFDrawable * marker_drawable = [[RectDrawable alloc] init:[self WindowRect2PDFRect:marker_rect pdf_rect:papersize window_size:window_rect.size] color:@"0x000000"]; // if(marker_drawable) // [pdfPage DirectDraw:pdfContext drawable:marker_drawable]; // } // // } // //// NSString* size = control[@"size"]; //// if(size.length==0) //// size=@"10"; //// //// control_drawable=[[TextDrawable alloc] init:[self WindowRect2PDFRect:control_rect pdf_rect:papersize window_size:window_rect.size] source_type:@"const" source:value textAlignment:@"center" vAlign:@"middle" size:size]; // } // if(control_drawable) //// for(int l=0;l<100;l++) // [pdfPage DirectDraw:pdfContext drawable:control_drawable]; // // // // } //// NSMutableDictionary* tline1= [LineDrawable createlineTemplate:1 from:CGPointMake(20, 20) to:CGPointMake(500,500)]; //// LineDrawable* line1=nil; //// line1= [[LineDrawable alloc] init:tline1]; //// //// [pdfPage DirectDraw:pdfContext drawable:line1]; //// NSRange range = NSMakeRange(0,9999); //// [line1 Draw:pdfContext dataSource:nil ParentRect:papersize startX:0 startY:0 flipHeight:0 range:range]; // // CGContextEndPage(pdfContext); // // // [pdfPage Draw:pdfContext dataSource:nil]; //// [self drawPage:pdfContext template:page size:papersize dataSource:data]; // // //// CFBridgingRelease(page); // } // CGContextRelease(pdfContext); // CFRelease(url); // // CFRelease(myDictionary); // // // // CFRelease(cfpdfAttributes); //// //开始画pdf //// //// // NSString *temtext=[[NSString alloc]init]; //// // //// // const char *text=(char *)[temtext UTF8String]; //// // //// // int width; //// // //// // int height; //// // //// //// // [self newpage:pdfContext size:papersize]; //// //// //// //// CGContextRelease(pdfContext); // // return newFilePath; // //} @end