/*
    Antenna House PDF Tool API V8.0
    Java Interface sample program

    概要：画像の入れ替え（ぼかす）

    本サンプルコードでは、画像処理ライブラリとして OpenCV JAVA を使用しています。
　　OpenCVは Apache License 2.0 に基づき配布されています。
　　ライセンス内容は「LICENSE_OpenCV.txt」をご確認ください。

    Copyright 2025- Antenna House, Inc.
*/

package Sample;

import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import jp.co.antenna.ptl.*;

public class ReplacingImage {
	static {
		// opencv_javaのpathは環境にあわせて指定してください
	    System.load("C:\\opencv\\build\\java\\x64\\opencv_java4140.dll");
	}

	public static void main(String[] args) {
        if (args.length < 2)
        {
            System.out.println("usage: java ReplacingImage in-pdf-file out-pdf-file");
            return;
        }

        try (PtlParamInput input = new PtlParamInput(args[0]);
    		PtlParamOutput output = new PtlParamOutput(args[1]);
    		PtlPDFDocument doc = new PtlPDFDocument();)  // ページコンテナの取得
        {

        	String imagePath = "C:\\tmp\\tmp.jpg";
        	
            // PDFファイルをロードします。
            doc.load(input);        	

            // ページコンテナの取得
            PtlPages pages = doc.getPages();

            if (pages.isEmpty()) {
            	System.out.println("ページコンテナが空");
//                return 1;
            }
            
            int pageCount = pages.getCount();
            if (pageCount >= 1)
            {
                for (int pg = 0; pg < pageCount; ++pg)
                {
                    PtlPage page = pages.get(pg);

                    PtlContent content = page.getContent();

                    // 画像を取得してボカシて入れ替える例
                    if (replaceImage(content, imagePath))
                    {
                        page.setContent(content);   // ページコンテントを置き換える

                        System.out.println("置き換え完了!");
                    }
                }
            }
            doc.save(output);
        }
        catch (PtlException pex) {
             System.out.println("PtlException : ErrorCode = " + pex.getErrorCode() + "\n  " + pex.getErrorMessage());
        }
        catch (Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
        catch (Error ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
        finally {
            System.out.println("-- 完了 --");
        }
	}

	// 画像を取得してボカシて入れ替える例
	public static boolean replaceImage(PtlContent content, String imagePath)
	{
		boolean ret = false;
	    try(PtlEditElements elems = content.getEditElements();)
	    {
	        if (elems.isEmpty()) return false;
	        int elementcount = elems.getCount();
	        for (int i = 0; i < elementcount; ++i)
	        {
	            PtlEditElement elem = elems.get(i);
	            switch (elem.getType())
	            {
	            case TYPE_FORMXOBJECT:
	            {
	                PtlEditFormXObject elemForm = (PtlEditFormXObject)elem;
	                PtlContent contentForm = elemForm.getContent();            // FormXObjectコンテント取得
	                // FormXObjectコンテントをパースして画像を置き換える
	                if (replaceImage(contentForm, imagePath))
	                {
	                    elemForm.setContent(contentForm);   // FormXObjectコンテントを置き換える
	                }
	            }
	            break;
	            case TYPE_MCCONTAINER:
	            {
	                PtlEditMCContainer elemContainer = (PtlEditMCContainer)elem;
	                PtlContent contentContainer = elemContainer.getContent();    // マークコンテント取得
	                {
	                    // マークコンテントをパースして画像を置き換える
	                    if (replaceImage(contentContainer, imagePath))
	                    {
	                        ret = true;     // 上位のPtlPageかPtlEditFormXObjectでsetContentが必要
	                    }
	                }
	            }
	            break;
	            case TYPE_IMAGE:
	            {
	                PtlEditImage elemImage = (PtlEditImage)elem;

	                //const char* pathImage = "C:\\tmp\\tmp.jpg";
	                PtlParamOutput output = new PtlParamOutput(imagePath);
					// 画像を一時ファイルとして保存する
	                elemImage.writeFile(output,PtlEditImage.OUTPUT_FORMAT.FORMAT_JPEG);

	                // 画像を読み込む
	                Mat loaded_image = load_image(imagePath);
	                // 画像をぼかす
	                Mat blur_image = blur(loaded_image);
	                // ぼかした画像を一時ファイルとして保存する
	                out_image(imagePath, blur_image);

	                // PtlEditImageの画像を直接置き換える
	                if (replaceImageWithImage(elemImage, imagePath))
	                {
	                    ret = true;
	                }
	            }
	            break;
	            default:
	                break;
	            }
	        }
	    }
	    catch (PtlException e)
	    {
            System.out.println("Error code : " + e.getErrorCode() + "\n" + e.getErrorMessage());
	        return false;
	    }
	    catch (Exception e)
	    {
            System.out.println("Error : " + e);
	        return false;
	    }
	    return ret;
	}

	// 画像を読み込む
	public static Mat load_image(String file_path) throws Exception {
		Mat loaded_image = Imgcodecs.imread(file_path, 1);
	    if (loaded_image.empty()) {
	    	throw new Exception("画像を正常に読み込めませんでした。");
	    }
	    return loaded_image;
	}

	// 画像をぼかす
	public static Mat blur(Mat image) {
	    Mat blur_image = new Mat();
	    Imgproc.blur(image, blur_image, new Size(65, 65));
	    return blur_image;
	}

	// ぼかした画像を一時ファイルとして保存する
	public static void out_image(String file_path, Mat blur) throws Exception {
		boolean result = Imgcodecs.imwrite(file_path, blur);
	    if (!result) {
	        throw new Exception("画像を正常に保存できませんでした。");
	    }
	}

	// PtlEditImageの画像を直接置き換える
	public static boolean replaceImageWithImage(PtlEditImage elemImage, String imagePath)
	{
	    try(PtlParamInput input = new PtlParamInput(imagePath);
	        PtlParamEditImage paramEditImage =new PtlParamEditImage();)
	    {
            paramEditImage.setImageStream(input);
            paramEditImage.setUseOriginalJpegQuality(true);
            elemImage.setImage(paramEditImage); // PtlParamEditImageに設定した画像で置き換え

            return true;    // Elementが所属するPtlPage若しくはPtlEditFormXObjectでsetContentが必要なのでtrueを返す
	    }
	    catch (PtlException e)
	    {
            System.out.println("Error code : " + e.getErrorCode() + "\n" + e.getErrorMessage());
	        return false;
	    }
	}



}

