// Copyright (C) 2003-2026, Foxit Software Inc..
// All Rights Reserved.
//
// http://www.foxitsoftware.com
//
// The following code is copyrighted and contains proprietary information and trade secrets of Foxit Software Inc..
// You cannot distribute any part of Foxit PDF SDK to any third party or general public,
// unless there is a separate license agreement with Foxit Software Inc. which explicitly grants you such rights.
//
// This file contains an example to demonstrate how to use Foxit PDF SDK to reflow PDF pages.


#include "FSPDFObjC.h"

NSString *input_path = @"../input_files/";
NSString *output_path = @"../output_files/";

NSString* sn = @"bPxThFlBAYifO3yiW0C51bKbjPap1zHaf5aG5sX378TjFvB7Q0802A==";
NSString* key = @"8f3g1sGNtR8NAgfSNv+BvaJWy2fnrw36NZvzh8GUxYXvs+/YczAk4e34yqlOnmL4asgxGMO7+rlOcSHUSSKagx5g4G7VEXfkYLXnDDx77FOOedZPrFFcOCu1vT4+wOKzy1zkORq9cKtiFf44byH5sfRqf+OvELjep2teT9eF9yPCsSw2vRKljXlPy40DMP9XX1O5OTe+mSG3RvwKUMb0+RpG3YobM87j+/ynTDlJMMXw4vgwuTb1ZuAtlvkTdFz7HDLV81C6TYnn73ddHeGD3qYWBVsD4uJkDwyyH/SWr7QX0HSgVg8HSZqnab1VGdAUYxKY2vGWeOTJdu6qDGb5ZEb9O3kZZg+9LYAmUKzDfCYwfIsYZ8Y9LPC4wMx70kIq7JpNnzPvigrdshV8/ew1F0+qP/P5Z1EB53vDVrp2LVSuL873Wv4g3PzjZlNH+1qgT87hC+Buto4qsSUfP5Y2z0uApu+c/TfttCXbeMLSsw9TY1HQD3mkrZExMaQqRrAuXAcZWdvBnVuG3DCZmm8q0DLxJiCfYfViAU/AkbeKMIGaTJdrvIXBcssfde4nmU6qr0M4x4+Hs2ESddtY2QRtLAUBq/7h7GJlJHkEZr8ueaUy/6D/2vvAWz6wMLgmjlPbDTLqzfnCJylHCPtcJmu1SPPT9v1VreBX3+zNWcIT8HueyHEiUniqzwWkRKaotrnNb/zhnHLPpgaBSwKjyi8rOzzVwu/nY84G9ye4jsVjmkIRItKDrW7z22iS+QQuTwfqLVuMB0OD4jMkPCC2slzPfEeZnuh4+Rewln2qLRJVgI72zJ20OBWAelGSpO1Ii2Y3gOvojdmtUwx6R3Z1qFNWTTB25o9ytcux8BLOtTCkA8T8xaT4N339OTCsu/TmfahIDixKvr8cDa6F2WkBT8SOfv64W9PgiNv5B/BMOD2VWYaAl0N7yD0NkYYg/cDWRC4dfpdeip1jrr0k3mND0oSpIkxC+FicZbaYYwRdtJ9OSVWJ5OE0voLv8HgLze8mw6s4TrN3z+a2NQCveMa2VRN7YcEF7agPrvb/qU+otMwHae/wM7+f+HFAaOW+WTfzfxIVFB8/A1DN0NiEX+em4G7nO5F5ZcvfYPpaaioe8Nn33BbVLtMjXqsOBeM8AXiVfpD6YO75j7BqnBUPnivvD8BxJaaIQZvVSuQmvGm0ynt03IYwE8Rq+jYsunvsZ86jh5BiUR+Nm7sK0Qe9BdZn/7jdqohMv9czfMGUAscX+xBMunFbDpcRbWVpUADcm209L8Ndek2XY7YlCMxPgPVNvfWRF2jxehib9Tpd7zB5ZIDfAEH9zrpLfp29DLvCh2Yx8mH7xxdKG1O9Q0GdHphYHhej6smAcPm68R0GUQaTOLfXqNpueGJC1GAOI3Y4swjyt7jMTWcibnKLzwukWE5rnEDhn5n64JnyUM0ZFkRmtOiV";

NSString *output_directory = [output_path stringByAppendingString:@"pdfreflow/"];

void saveBitmap(FSBitmap* bitmap, int index, NSString* save_file_name) {
    FSRectF* margin = [[FSRectF alloc] initWithLeft1:50 bottom1:30 right1:30 top1:30];
    FSPointF* size = [FSPointF new];
    [size set:480 y:800];
    FSRectI* rect = [[FSRectI alloc] initWithLeft1:0 top1:0 right1:(int)size.x bottom1:(int)margin.top];
    
    [bitmap fillRect:0xFFFFFFFF rect:rect];
    rect = [[FSRectI alloc] initWithLeft1:0 top1:(int)(size.y - margin.bottom) right1:(int)size.x bottom1:(int)size.y];
    [bitmap fillRect:0xFFFFFFFF rect:rect];
    FSImage* image = [FSImage new];
    [image addFrame:bitmap];
    
    NSString* save_file_path = [NSString stringWithFormat:@"%@%@%@%d.bmp", output_directory, @"reflow", save_file_name, index];
    [image saveAs:save_file_path];
}

// The change for the size of the picture depends on the size of the content of reflow page.
void reflowSingle(FSPDFDoc* doc) {
    FSRectF* margin = [[FSRectF alloc] initWithLeft1:50 bottom1:30 right1:30 top1:30];
    FSPointF* size = [FSPointF new];
    [size set:480 y:800];
    int page_count = [doc getPageCount];
    for (int i=0;i<page_count;i++) {
        FSPDFPage* page = [doc getPage:i];
        // Parse PDF page.
        [page startParse:FSPDFPageParsePageNormal pause:nil is_reparse:NO];
        
        FSReflowPage* reflow_page = [[FSReflowPage alloc] initWithPage:page];
        // Set some arguments used for parsing the relfow page.
        [reflow_page setLineSpace:0];
        [reflow_page setScreenMargin:margin.left top:(int)margin.top right:(int)margin.right bottom:(int)margin.bottom];
        [reflow_page setScreenSize:size.x height:size.y];
        [reflow_page setZoom:100];
        [reflow_page setParseFlags:FSReflowPageNormal];
        
        // Parse reflow page.
        [reflow_page startParse:nil];
        
        // Get actual size of content of reflow page. The content size does not contain the margin.
        float content_width = [reflow_page getContentWidth];
        float content_height = [reflow_page getContentHeight];
        
        // Create a bitmap for rendering the reflow page. The bitmap size contains the margin.
        FSBitmap* bitmap = [[FSBitmap alloc] initWithWidth:(int)(content_width + margin.left + margin.right) height:(int)(content_height + margin.top + margin.bottom) format:FSBitmapDIBArgb buffer:nil pitch:0];
        [bitmap fillRect:0xFFFFFFFF rect:nil];
        
        // Render reflow page.
        FSRenderer* renderer = [[FSRenderer alloc] initWithBitmap:bitmap is_rgb_order:NO];
        FSMatrix2D* matrix = [reflow_page getDisplayMatrix:0 offset_y:0 width:(int)content_width height:(int)content_height rotate:0];
        [renderer startRenderReflowPage:reflow_page matrix:matrix pause:nil];
        NSString* file_name = @"_single_";
        saveBitmap(bitmap, i, file_name);
    }
    
}

// Fixed bitmap size, just to simulate split screen situation.
void reflowContinuous(FSPDFDoc* doc) {
    FSRectF* margin = [[FSRectF alloc] initWithLeft1:50 bottom1:30 right1:30 top1:30];
    FSPointF* size = [FSPointF new];
    [size set:480 y:800];
    float display_height = size.y - margin.top - margin.bottom;
    FSBitmap* bitmap = [[FSBitmap alloc] initWithWidth:(int)size.x height:(int)size.y format:FSBitmapDIBArgb buffer:nil pitch:0];
    float offset_y = 0;
    int page_count = [doc getPageCount];
    int bitmap_index = 0;
    for(int i=0;i<page_count;i++)
    {
        FSPDFPage* page = [doc getPage:i];
        
        // Parse PDF page.
        [page startParse:FSPDFPageParsePageNormal pause:nil is_reparse:NO];
        
        FSReflowPage* reflow_page = [[FSReflowPage alloc] initWithPage:page];
        // Set some arguments used for parsing the relfow page.
        [reflow_page setLineSpace:0];
        [reflow_page setScreenMargin:(int)margin.left top:(int)margin.top right:(int)margin.right bottom:(int)margin.bottom];
        [reflow_page setScreenSize:size.x height:size.y];
        [reflow_page setZoom:100];
        [reflow_page setParseFlags:FSReflowPageWithImage];
        
        [reflow_page setTopSpace:offset_y];
        
        // Parse reflow page.
        [reflow_page startParse:nil];
        
        // Get actual size of content of reflow page.
        // The content size does not contain the margin but contains the top space.
        float content_height = [reflow_page getContentHeight];
        float content_width = [reflow_page getContentWidth];
        // Render reflow page.
        FSRenderer* renderer = [[FSRenderer alloc] initWithBitmap:bitmap is_rgb_order:NO];
        FSMatrix2D* matrix = [reflow_page getDisplayMatrix:0 offset_y:0 width:(int)content_width height:(int)content_height rotate:0];
        [renderer startRenderReflowPage:reflow_page matrix:matrix pause:nil];
        
        int rate_need_screen_count = static_cast<int>(ceil(MAX(content_height - display_height, 0.0f) / display_height));
        if (rate_need_screen_count > 0) {
            // Before do next rendering, save current bitmap first.
            NSString* file_name = @"_continuous_";
            saveBitmap(bitmap, bitmap_index++,file_name);
            
            float has_display_height = display_height;
            for (int j = 0; j < rate_need_screen_count; j++) {
                // Clear the bitmap and used it to do next rendering.
                [bitmap fillRect:0xFFFFFFFF rect:nil];
                // Render reflow page.
                FSRenderer* renderer = [[FSRenderer alloc] initWithBitmap:bitmap is_rgb_order:NO];
                FSMatrix2D* matrix = [reflow_page getDisplayMatrix:0 offset_y:-has_display_height width:(int)content_width height:(int)content_height rotate:0];
                [renderer startRenderReflowPage:reflow_page matrix:matrix pause:nil];
                if (j != rate_need_screen_count - 1) {
                    has_display_height += display_height;
                    saveBitmap(bitmap,  bitmap_index++,file_name);
                } else {
                    offset_y = content_height - rate_need_screen_count * display_height;
                }
            }
        } else {
            offset_y = content_height;
        }
    }
    NSString* file_name = @"_continuous_";
    saveBitmap(bitmap,  bitmap_index++,file_name);
    
}

int main(int argc, const char * argv[]) {
	bool is_run_success = false;
	@autoreleasepool {
        NSFileManager *fileManager = [NSFileManager defaultManager];
		BOOL isDir = NO;
		if ([fileManager fileExistsAtPath:output_directory isDirectory:&isDir]) {
			if (!isDir) {
				NSError *error = nil;
				if (![fileManager removeItemAtPath:output_directory error:&error] || error) {
					return -1;
				}
				if (![fileManager createDirectoryAtPath:output_directory withIntermediateDirectories:YES attributes:nil error:&error] || error) {
					return -1;
				}
			}
		} else {
			NSError *error = nil;
			if (![fileManager createDirectoryAtPath:output_directory withIntermediateDirectories:YES attributes:nil error:&error] || error) {
				return -1;
			}
		}
    
		// Initialize library
		FSErrorCode errorCode = [FSLibrary initialize:sn key:key];
		if (errorCode != FSErrSuccess) {
			NSLog(@"Library Initialize Error: %ld", errorCode);
			return -1;
		}
		
		@try {
            NSString* input_pdf_name = @"AboutFoxit.pdf";
            NSString* input_pdf_path = [input_path stringByAppendingPathComponent:input_pdf_name];
            
            FSPDFDoc* doc = [[FSPDFDoc alloc] initWithPath:input_pdf_path];
            FSErrorCode errorCode = [doc load:nil];
            if (errorCode != FSErrSuccess) {
                NSLog(@"The Doc [%@] Error: %ld", input_pdf_path, errorCode);
                return -1;
            }
            
            reflowContinuous(doc);
            reflowSingle(doc);
            
            NSLog(@"Reflow test.");
            is_run_success = true;
		}
		@catch (NSException *e) {
			NSLog(@"Unknown Exception, %@", e);
		}
	}
	[FSLibrary destroy];
    return is_run_success ? 0 : 1;
}

