/*
	Antenna House PDF Tool API V7.0
	C++ Interface sample program

	概要：ページ抽出

	Copyright 2013-2021 Antenna House, Inc.
*/

#include < PdfTk.h >
#include < stdio.h >

using namespace PdfTk;

int main(int argc, char* argv[])
{
	if (argc < 3) {
		printf("usage: ExtractPage.exe in-pdf-file out-folder\n");
		return 1;
	}
	try
	{
		const int MAX_PATH = 260;
		char outputfile[MAX_PATH];

		PtlParamString inputfile(argv[1]);		// 抽出元となるファイル名
		PtlParamString outputfolder(argv[2]);	// 出力するフォルダ名

		PtlParamInput input(inputfile);
		PtlPDFDocument doc;

		// PDFファイルをロードします。
		doc.load(input);

		// 文書プロパティの取得
		PtlDocProperty& docproperty = doc.getDocProperty();

		// 文書情報の取得
		PtlDocInfo& docinfo = docproperty.getDocInfo();

		for(int i=0; i < doc.getPageCount(); i++)
		{
			PtlPDFDocument doc_ext;
			PtlPages& pages = doc_ext.getPages();

			// 文書プロパティの取得
			PtlDocProperty& docproperty_ext = doc_ext.getDocProperty();

			// 文書情報の取得
			PtlDocInfo& docinfo_ext = docproperty_ext.getDocInfo();

			// タイトルをコピー
			docinfo_ext.setTitle(docinfo.getTitle());

			// 著者をコピー
			docinfo_ext.setAuthor(docinfo.getAuthor());

			// サブジェクトをコピー
			docinfo_ext.setSubject(docinfo.getSubject());

			// キーワードをコピー
			docinfo_ext.setKeywords(docinfo.getKeywords());

			// クリエータをコピー
			docinfo_ext.setCreator(docinfo.getCreator());

			// プロデューサをコピー
			docinfo_ext.setProducer(docinfo.getProducer());

			// 作成日付をコピー
			docinfo_ext.setCreationDate(docinfo.getCreationDate());

			// 更新日付をコピー
			docinfo_ext.setModDate(docinfo.getModDate());

			// ページ挿入オプション
			// OPTION_COPY_OUTLINES = 0x00000004 ページ挿入時にあわせてしおりをコピーします。
			// OPTION_COPY_ATTACHEDFILES	= 0x00000008ページ挿入時にあわせて添付ファイルをコピーします。
			int insertoption = (PtlPages::OPTION_COPY_OUTLINES | PtlPages::OPTION_COPY_ATTACHEDFILES);

			// ページの追加(iページから1P)
			pages.append(doc, i, 1, insertoption);

			// 出力ファイル名
		#ifdef WIN32
			sprintf_s(outputfile, "%s\\output_%d.pdf", outputfolder.c_str(), i);
		#else
			sprintf_s(outputfile, "%s/output_%d.pdf", outputfolder.c_str(), i);
		#endif
			PtlParamOutput output(outputfile);

			// ファイルに保存します。
			doc_ext.save(output);
		}

		printf("完了!\n");
	}
	catch (const PtlException &e)
	{
		fprintf(stderr, "Error code : %d\n %s\n", e.getErrorCode(), e.getErrorMessage().c_str());
		return 1;
	}	
	return 0;
}
