/*
    Antenna House PDF Tool API V7.0
    Java Interface sample program

    概要：画像の描画

    Copyright 2015-2021 Antenna House, Inc.
*/

package Sample;

import jp.co.antenna.ptl.*;

public class DrawImage {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        if (args.length < 3)
        {
            System.out.println("usage: java DrawImage in-pdf-file out-pdf-file insert-image-file");
            return;
        }

        try (PtlParamInput inputFile = new PtlParamInput(args[0]);
             PtlParamOutput outputFile = new PtlParamOutput(args[1]);
             PtlPDFDocument doc = new PtlPDFDocument())
        {
            // PDFファイルをロードします。
            doc.load(inputFile);

            try (PtlPages pages = doc.getPages()) // ページコンテナの取得
            {
                // ページコンテナが空かどうか
                if (pages.isEmpty())
                {
                    System.out.println("ページコンテナが空");
                    return;
                }
                    
                // １ページ目の取得
                try (PtlPage page = pages.get(0))
                {
                    // 画像の描画
                    drawImage(page, args[2]);
                }
            }

            // ファイルに保存します。
            doc.save(outputFile);
        }
        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 void drawImage(PtlPage page, String pathImage) throws PtlException, Exception, Error
    {
        try (PtlContent content = page.getContent(); // ページコンテントの取得
             PtlSize pageSize = page.getSize()) // ページサイズ
        {
            try (PtlParamDrawImage paramDrawImage = new PtlParamDrawImage(); // 画像の描画に使うパラメータクラス
                 PtlParamInput insertImage = new PtlParamInput(pathImage);  //挿入する画像
                 PtlRect rect = new PtlRect(10.0f, 10.0f, pageSize.getWidth() - 10.0f, pageSize.getHeight() - 10.0f)) // 描画矩形
            {
                //入力画像ストリームの設定
                paramDrawImage.setImageStream(insertImage);

                //マルチTiffのページ番号の設定（Tiffファイルにのみ有効） 
                paramDrawImage.setImagePageNumber(0);

                // 画像の描画
                content.drawImage(rect, PtlContent.ALIGN.ALIGN_TOP_LEFT, paramDrawImage);
            }
        }
    }
}
