123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292 |
- //
- // KMOCTool.m
- // PDF Reader Pro
- //
- // Created by liujiajie on 2023/11/15.
- //
- #import "KMOCTool.h"
- #import <Foundation/Foundation.h>
- #import <PDF_Reader_Pro-Swift.h>
- @implementation KMOCTool
- + (void)createPDFFile:(NSString *)filePath imagePaths:(NSArray *)paths results:(NSArray *)resultsArray scale:(CGFloat)scale {
- if (paths.count < 1) {
- return;
- }
-
- CFStringRef path = (__bridge CFStringRef)filePath;
- CFURLRef url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0);
- CFMutableDictionaryRef myDictionary = CFDictionaryCreateMutable(NULL,
- 0,
- &kCFTypeDictionaryKeyCallBacks,
- &kCFTypeDictionaryValueCallBacks);
- CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("Kdan Mobile PDF Reader"));
-
- CGContextRef pdfContext = CGPDFContextCreateWithURL(url, &CGRectZero, myDictionary);
- CGContextSetRGBFillColor(pdfContext, 1.0, 0.0, 0.0, 0.0);
- CGContextSetTextDrawingMode(pdfContext, kCGTextFill);
-
- CFRelease(myDictionary);
- CFRelease(url);
-
- for (int i=0; i<paths.count; i++) {
- NSString *path = [paths objectAtIndex:i];
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
- CIImage *imageCIImage = [CIImage imageWithContentsOfURL:[NSURL fileURLWithPath:path]];
- NSSize size = [imageCIImage extent].size;
- CGRect pageRect = CGRectMake(0, 0, size.width/scale, size.height/scale);
-
- CFMutableDictionaryRef pageDictionary = CFDictionaryCreateMutable(NULL,
- 0,
- &kCFTypeDictionaryKeyCallBacks,
- &kCFTypeDictionaryValueCallBacks);
- CFDataRef boxData = CFDataCreate(NULL,(const UInt8 *)&pageRect, sizeof (CGRect));
- CFDictionarySetValue(pageDictionary, kCGPDFContextMediaBox, boxData);
- CGPDFContextBeginPage (pdfContext, pageDictionary);
- NSData *imageData = [NSData dataWithContentsOfFile:path];
- CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
- CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
- CGContextSaveGState(pdfContext);
- CGContextDrawImage(pdfContext, pageRect, imageRef);
- CGContextRestoreGState(pdfContext);
- CGImageRelease(imageRef);
-
- [NSGraphicsContext saveGraphicsState];
- [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:pdfContext flipped:NO]];
- NSArray *results = nil;
- if (i < resultsArray.count) {
- results = resultsArray[i];
- CGFloat newScale = scale;
- if([KMGOCRManager defaultManager].OCRType == KMOCRType_Apple)
- newScale = 1;
- if (results.count == 1) {
- KMGOCRResult *result = results[0];
- NSRect bounds = NSMakeRect((result.textBounds.origin.x)/newScale,
- pageRect.size.height-(result.textBounds.origin.y+result.textBounds.size.height)/newScale,
- (result.textBounds.size.width)/newScale,
- (result.textBounds.size.height)/newScale);
- NSDictionary *dic = @{NSFontAttributeName:FontWithSize(result.text, CGSizeMake(result.textBounds.size.width/newScale, result.textBounds.size.height/newScale)),
- NSForegroundColorAttributeName:[NSColor clearColor]};
- [result.text drawInRect:bounds withAttributes:dic];
- } else {
- for (int i=1; i<results.count; i++) {
- KMGOCRResult *result = results[i];
- NSRect bounds = NSMakeRect((result.textBounds.origin.x)/newScale,
- pageRect.size.height-(result.textBounds.origin.y+result.textBounds.size.height)/newScale,
- (result.textBounds.size.width)/newScale,
- (result.textBounds.size.height)/newScale);
- NSDictionary *dic = @{NSFontAttributeName:FontWithSize(result.text, CGSizeMake(result.textBounds.size.width/newScale, result.textBounds.size.height/newScale)),
- NSForegroundColorAttributeName:[NSColor clearColor]};
- [result.text drawInRect:bounds withAttributes:dic];
- }
- }
- }
- [NSGraphicsContext restoreGraphicsState];
-
- CGPDFContextEndPage (pdfContext);
-
- CFRelease(pageDictionary);
- CFRelease(boxData);
- image = nil;
- }
-
- CGPDFContextClose(pdfContext);
- CGContextRelease (pdfContext);
- }
- + (CGRect)localCropRectForWindow:(CGWindowID)wNumber withBounds:(CGRect)bounds{
- CFArrayRef tarray = CGWindowListCreate(kCGWindowListOptionOnScreenOnly,
- (CGWindowID)wNumber);
- CFArrayRef array = CGWindowListCreateDescriptionFromArray(tarray);
- CFRelease(tarray);
-
- CGRect cropRect = bounds;
- for (NSDictionary *windowInfo in CFBridgingRelease(array)) {
- if ([windowInfo[(__bridge NSString*)kCGWindowNumber] integerValue] == wNumber) {
- NSDictionary *rectInfo = windowInfo[(__bridge NSString*)kCGWindowBounds];
-
- NSScreen *mainScreen = nil;
- for (NSScreen *screen in [NSScreen screens]) {
- if (CGPointEqualToPoint(screen.frame.origin, CGPointZero))
- mainScreen = screen;
- }
-
- CGPoint center = CGPointMake([rectInfo[@"X"] floatValue] + [rectInfo[@"Width"] floatValue]/2,
- mainScreen.frame.size.height - [rectInfo[@"Y"] floatValue] - [rectInfo[@"Height"] floatValue]/2);
-
- NSScreen *curScreen = nil;
- for (NSScreen *screen in [NSScreen screens]) {
- if (CGRectContainsPoint(screen.frame, center)) {
- curScreen = screen;
- break;
- }
- }
- if (!curScreen) {
- center = CGPointMake([rectInfo[@"X"] floatValue],
- mainScreen.frame.size.height - [rectInfo[@"Y"] floatValue]);
-
- for (NSScreen *screen in [NSScreen screens]) {
- if (CGRectContainsPoint(screen.frame, center)) {
- curScreen = screen;
- break;
- }
- }
-
- if (!curScreen) {
- center = CGPointMake([rectInfo[@"X"] floatValue] + [rectInfo[@"Width"] floatValue],
- mainScreen.frame.size.height - [rectInfo[@"Y"] floatValue]);
-
- for (NSScreen *screen in [NSScreen screens]) {
- if (CGRectContainsPoint(screen.frame, center)) {
- curScreen = screen;
- break;
- }
- }
- }
- }
- if (curScreen) {
- float y = mainScreen.frame.size.height - [rectInfo[@"Y"] floatValue] - curScreen.frame.origin.y;
- cropRect = CGRectMake([rectInfo[@"X"] floatValue] - curScreen.frame.origin.x,
- y - [rectInfo[@"Height"] floatValue],
- [rectInfo[@"Width"] floatValue],
- [rectInfo[@"Height"] floatValue]);
- }else {
-
- }
- break;
- }
- }
- return cropRect;
- }
- +(NSAttributedString *)transformAttr:(NSAttributedString *)astring withString:(NSString *)str{
- NSUInteger i, l = [str length];
- NSRange r = NSMakeRange(0, l);
- while (NSNotFound != (i = NSMaxRange([str rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] options:NSAnchoredSearch range:r])))
- r = NSMakeRange(i, l - i);
- while (NSNotFound != (i = [str rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] options:NSBackwardsSearch | NSAnchoredSearch range:r].location))
- r.length = i - r.location;
- if (r.length == 0)
- astring = nil;
- else if (NSMaxRange(r) < l)
- astring = [astring attributedSubstringFromRange:r];
-
- return astring;
- }
- + (id)nonWhitespaceAndNewlineCharacterSet {
- static NSCharacterSet *nonWhitespaceAndNewlineCharacterSet = nil;
- if (nonWhitespaceAndNewlineCharacterSet == nil)
- nonWhitespaceAndNewlineCharacterSet = [[[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet] copy];
- return nonWhitespaceAndNewlineCharacterSet;
- }
- +(NSData*)convertStringsToPDFWithString:(NSArray *)strings{
- return convertStringsToPDF(strings);
- }
- static inline NSFont * FontWithSize(NSString *strChar, CGSize size) {
- CGFloat fontsize = 1.0;
- NSFont *font = [NSFont systemFontOfSize:fontsize];
- CGSize strSize = [strChar sizeWithAttributes:@{NSFontAttributeName:font}];
- while ((fontsize<127) && (strSize.width<size.width || strSize.height<size.height)) {
- fontsize += 1.0;
- font = [NSFont systemFontOfSize:fontsize];
- strSize = [strChar sizeWithAttributes:@{NSFontAttributeName:font}];
- }
- return [NSFont systemFontOfSize:fontsize-1];
- }
- static NSData *convertStringsToPDF(NSArray<NSAttributedString *> *strings)
- {
- NSMutableData *pdfData = [[NSMutableData alloc] init];
- CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);
- CFMutableDictionaryRef myDictionary = CFDictionaryCreateMutable(NULL,
- 0,
- &kCFTypeDictionaryKeyCallBacks,
- &kCFTypeDictionaryValueCallBacks);
- CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("PDF Reader Pro"));
-
- CGRect mediaBox = CGRectMake(0, 0, 595, 842);
- CGContextRef pdfContext = CGPDFContextCreate(consumer, &mediaBox, myDictionary);
- CGContextSetRGBFillColor(pdfContext, 1.0, 0.0, 0.0, 0.0);
- CGContextSetTextDrawingMode(pdfContext, kCGTextFill);
-
- CFRelease(myDictionary);
-
- for (NSAttributedString *attributeString in strings) {
- if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_10) {
- NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributeString];
- NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
- [textStorage addLayoutManager:layoutManager];
- while (YES) {
- NSSize contentSize = NSMakeSize(mediaBox.size.width-40,
- mediaBox.size.height-40);
- NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:contentSize];
- [layoutManager addTextContainer:textContainer];
- NSRange rang = [layoutManager glyphRangeForTextContainer:textContainer];
- if (rang.length <= 0 ||
- rang.length + rang.location > attributeString.length) {
- break;
- }
- NSAttributedString *attStr = [attributeString attributedSubstringFromRange:rang];
-
- [NSGraphicsContext saveGraphicsState];
- // [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:pdfContext flipped:NO]];
- [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:pdfContext flipped:NO]];
- CGContextBeginPage(pdfContext, &mediaBox);
- [attStr drawInRect:CGRectMake(20, 20,
- mediaBox.size.width-40,
- mediaBox.size.height-40)];
- CGContextEndPage(pdfContext);
- [NSGraphicsContext restoreGraphicsState];
- }
- } else {
- [NSGraphicsContext saveGraphicsState];
- [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:pdfContext flipped:NO]];
- CGContextBeginPage(pdfContext, &mediaBox);
- [attributeString drawInRect:CGRectMake(20, 20,
- mediaBox.size.width-40,
- mediaBox.size.height-40)];
- CGContextEndPage(pdfContext);
- [NSGraphicsContext restoreGraphicsState];
- }
- }
-
- CGPDFContextClose(pdfContext);
- CGContextRelease (pdfContext);
-
- return pdfData;
- }
- + (NSDictionary *)convertExcelToPdfFilePath:(NSString *)filePath savePath:(NSString *)savePath{
- NSString * convertString = [NSString stringWithFormat:@"set filePath to\"%@\"\n",filePath];
- convertString = [convertString stringByAppendingFormat:@"set savePath to \"%@\"\n",savePath];
- convertString = [convertString stringByAppendingFormat:@"set tFile to (POSIX path of filePath) as POSIX file\n"];
-
- convertString = [convertString stringByAppendingFormat:@"tell application \"Microsoft Excel\"\n"];
- convertString = [convertString stringByAppendingFormat:@"set isRun to running\n"];
- convertString = [convertString stringByAppendingFormat:@"set wkbk1 to open workbook workbook file name tFile\n"];
- convertString = [convertString stringByAppendingFormat:@"alias savePath\n"];
- convertString = [convertString stringByAppendingFormat:@"save workbook as wkbk1 filename savePath file format PDF file format with overwrite\n"];
- convertString = [convertString stringByAppendingFormat:@"close wkbk1 saving no\n"];
- convertString = [convertString stringByAppendingFormat:@"if not isRun then quit\n"];
- convertString = [convertString stringByAppendingFormat:@"end tell\n"];
-
- NSDictionary * dic = nil;
- NSAppleScript *docScript = [[NSAppleScript alloc] initWithSource:convertString];
- [docScript executeAndReturnError:&dic];
- return dic;
- }
- + (NSDictionary *)convertOfficeFileToPdf:(NSString *)convertString{
- NSDictionary * dic = nil;
- NSAppleScript *docScript = [[NSAppleScript alloc] initWithSource:convertString];
- [docScript executeAndReturnError:&dic];
- return dic;
- }
- @end
|