/*
    Antenna House PDF Tool API V8.0
    Java Interface sample program

    概要：ファイル添付とセキュリティ設定

    Copyright 2026- Antenna House, Inc.
*/

package Sample;

import jp.co.antenna.ptl.*;

public class CombiEmbeddedEncrypt {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        if (args.length < 3)
        {
            System.out.println("usage: java CombiEmbeddedEncrypt in-pdf-file out-pdf-file embedded-file");
            return;
        }

        try (PtlParamInput inputFile = new PtlParamInput(args[0]);
             PtlParamOutput outputFile = new PtlParamOutput(args[1]);
             PtlPDFDocument doc = new PtlPDFDocument())
        {
            String embeddedfilename = args[2];

            // PDFファイルをロード
            doc.load(inputFile);
            
            // 添付ファイルコンテナの取得
            try (PtlEmbeddedFiles embeddedfiles = doc.getEmbeddedFiles();
                // PDFの添付ファイル
        		PtlEmbeddedFile embeddedfile = new PtlEmbeddedFile();
                PtlParamInput inputEmbed = new PtlParamInput(embeddedfilename);)
            {
                // 添付ファイル名の設定
                embeddedfile.setFileName(embeddedfilename);

                // 添付するファイルの読み込み
                embeddedfile.readFile(inputEmbed);

                // 添付ファイルの追加
                embeddedfiles.append(embeddedfile);
            }

            
    		// 256 bit AES
            try (PtlEncryptStandard256AES enc = new PtlEncryptStandard256AES();
            		PtlEncryptPermissionType2 permissionType2 = new PtlEncryptPermissionType2();)
            {	
	    		// 文書の全てのコンテンツを暗号化
	    		enc.setEncryptComponent(PtlEncrypt.ENCRYPT_COMPONENT.ENCRYPT_ALL);
	
	    		// オーナーパスワード値の設定
	    		enc.setOwnerPassword("pass123");
	
	    		// 印刷権限の設定
	    		// PERM_PRINT_LOW = 1, /* 低解像度 */
	    		permissionType2.setPrint(PtlEncryptPermissionType2.PERMISSION_PRINT.PERM_PRINT_LOW);
	
	    		// テキスト、画像、その他の内容のコピーを有効にするかどうかの設定
	    		permissionType2.setCopy(true);
	
	    		// ユーザアクセス許可フラグの設定
	    		enc.setPermission(permissionType2);
	
	    		// 暗号化設定
	    		doc.setEncrypt(enc);
            }
            
            // ファイルに保存します。
            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("-- 完了 --");
        }
    }
}
