// 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 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 add watermarks (in different types)
// into PDF files.


#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";

void addTextWatermark(FSPDFDoc* doc, FSPDFPage* page) {
    FSWatermarkSettings* settings = [FSWatermarkSettings new];
    settings.flags = FSWatermarkSettingsFlagASPageContents | FSWatermarkSettingsFlagOnTop;
    settings.offset_x = 0;
    settings.offset_y = 0;
    settings.opacity = 90;
    settings.position = FSPosTopRight;
    settings.rotation = -45.f;
    settings.scale_x = 1.f;
    settings.scale_y = 1.f;
    
    FSWatermarkTextProperties* text_properties = [FSWatermarkTextProperties new];
    text_properties.alignment = FSAlignmentCenter;
    text_properties.color = 0xF68C21;
    text_properties.font_style = FSWatermarkTextPropertiesFontStyleNormal;
    text_properties.line_space = 1;
    text_properties.font_size = 12.f;
    FSFont* new_font = [[FSFont alloc] initWithFont_id:FSFontStdIDTimesB];
    text_properties.font = new_font;
    
    FSWatermark* watermark = [[FSWatermark alloc] initWithDocument:doc text:@"Foxit PDF SDK\nwww.foxitsoftware.com" properties:text_properties settings:settings];
    [watermark insertToPage:page];
}

void addBitmapWatermark(FSPDFDoc* doc, FSPDFPage* page, NSString* bitmap_file_path) {
    FSWatermarkSettings* settings = [FSWatermarkSettings new];
    settings.flags = FSWatermarkSettingsFlagASPageContents | FSWatermarkSettingsFlagOnTop;
    settings.offset_x = 0.f;
    settings.offset_y = 0.f;
    settings.opacity = 60;
    settings.position = FSPosCenterLeft;
    settings.rotation = 90.f;
    
    FSImage* image = [[FSImage alloc] initWithPath:bitmap_file_path];
    FSBitmap* bitmap = [image getFrameBitmap:0];
    settings.scale_x = [page getHeight] * 1.0f / [bitmap getWidth];
    settings.scale_y = settings.scale_x;
    
    FSWatermark* watermark = [[FSWatermark alloc] initWithDocument:doc bitmap:bitmap settings:settings];
    [watermark insertToPage:page];
}

void addImageWatermark(FSPDFDoc* doc, FSPDFPage* page, NSString* image_file_path) {
    FSWatermarkSettings* settings = [FSWatermarkSettings new];
    settings.flags = FSWatermarkSettingsFlagASPageContents | FSWatermarkSettingsFlagOnTop;
    settings.offset_x = 0.f;
    settings.offset_y = 0.f;
    settings.opacity = 20;
    settings.position = FSPosCenter;
    settings.rotation = 0.0f;
    
    FSImage* image = [[FSImage alloc] initWithPath:image_file_path];
    FSBitmap* bitmap = [image getFrameBitmap:0];
    settings.scale_x = [page getWidth] * 0.618f / [bitmap getWidth];
    settings.scale_y = settings.scale_x;
    
    FSWatermark* watermark = [[FSWatermark alloc] initWithDocument:doc image:image frame_index:0 settings:settings];
    [watermark insertToPage:page];
}

void addSingleWatermark(FSPDFDoc* doc, FSPDFPage* page) {
    FSWatermarkSettings* settings = [FSWatermarkSettings new];
    settings.flags = FSWatermarkSettingsFlagASPageContents|FSWatermarkSettingsFlagOnTop;
    settings.offset_x = 0.f;
    settings.offset_y = 0.f;
    settings.opacity = 90;
    settings.position = FSPosBottomRight;
    settings.rotation = 0.0f;
    settings.scale_x = 0.1f;
    settings.scale_y = 0.1f;
    
    FSWatermark* watermark = [[FSWatermark alloc] initWithDocument:doc page:page settings:settings];
    [watermark insertToPage:page];
}

int main(int argc, const char * argv[]) {
    bool is_run_success = false;
    @autoreleasepool {
        NSString *output_directory = [output_path stringByAppendingString:@"watermark/"];

        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;
            }
            
            int page_count = [doc getPageCount];
            for (int i = 0; i < page_count; i++)
            {
                FSPDFPage* page = [doc getPage:i];
                [page startParse:FSPDFPageParsePageNormal pause:nil is_reparse:NO];
                
                addTextWatermark(doc, page);
                NSString* bmp_file_path = [NSString stringWithFormat:@"%@%@", input_path, @"watermark.bmp"];
                addBitmapWatermark(doc, page, bmp_file_path );
                NSString* image_file_path = [NSString stringWithFormat:@"%@%@", input_path, @"sdk.png"];
                addImageWatermark(doc, page, image_file_path);
                addSingleWatermark(doc, page);
            }
            
            NSString* save_pdf_name = @"watermark_add.pdf";
            NSString* save_pdf_path = [output_directory stringByAppendingPathComponent:save_pdf_name];
            
            is_run_success = [doc saveAs:save_pdf_path save_flags:FSPDFDocSaveFlagNoOriginal];
            if (is_run_success)
                NSLog(@"Add watermarks to PDF file.");
            else
                NSLog(@"Fail to save PDF file %@", save_pdf_path);
            
            page_count = [doc getPageCount];
            for (int i = 0; i < page_count; i++)
            {
                FSPDFPage* page = [doc getPage:i];
                [page startParse:FSPDFPageParsePageNormal pause:nil is_reparse:NO];
                
                if ([page hasWatermark])
                {
                    [page removeAllWatermarks];
                }
            }
            
            save_pdf_name = @"watermark_remove.pdf";
            save_pdf_path = [output_directory stringByAppendingPathComponent:save_pdf_name];
            
            is_run_success = [doc saveAs:save_pdf_path save_flags:FSPDFDocSaveFlagNoOriginal];
            if (is_run_success)
                NSLog(@"Remove watermarks from PDF file.");
            else
                NSLog(@"Fail to save PDF file %@", save_pdf_path);
        }
        @catch (NSException *e) {
            NSLog(@"Unknown Exception, %@", e);
        }
    }
    [FSLibrary destroy];
    return is_run_success? 0 : 1;
}

