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

	概要：ページ割り付け

	Copyright 2015-2021 Antenna House, Inc.
*/

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

using namespace PdfTk;

int main(int argc, char* argv[])
{
	if (argc < 3) {
		printf("usage: AllocatePages.exe in-pdf-file out-pdf-file\n");
		return 1;
	}
	try
	{
		float width = 210.0f; // A4横長
		float height = 297.0f;// A4縦長
		PtlRect rectA4V(0.0f, 0.0f, width, height);	// A4縦用紙
		PtlRect rect[4] = {PtlRect(0.0f, height/2, width/2, height),  // 上左
			               PtlRect(width/2, height/2, width, height), // 上右
						   PtlRect(0.0f, 0.0f, width/2, height/2),    // 下左
						   PtlRect(width/2, 0.0f, width, height/2)};  // 下右
		PtlParamInput input(argv[1]);
		PtlParamOutput output(argv[2]);
		PtlPDFDocument doc;
		PtlPDFDocument docNew;

		// 新規PDFのページコンテナの取得
		PtlPages& pagesNew = docNew.getPages();

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

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

		int numPages = doc.getPageCount();

		int pageNumber = 0;
		int i=0;
		while (i < numPages) {
			// 割り付けを行うA4縦ページ
			PtlPage pageTemp;
			pageTemp.setViewBox(rectA4V);
			// ページを文書に追加
			pagesNew.append(pageTemp, PtlPages::OPTION_NONE);

			// 文書からページの取得
			PtlPage pageNew = pagesNew.get(pageNumber);

			// 割り付けを行うA4縦ページのコンテント取得
			PtlContent& content = pageNew.getContent();

			// 4ページを1ページに割り付けます。
			for(int j=0; j < 4 && i < numPages; ++j,++i) {
				// 割り付けするページ
				PtlPage page = pages.get(i);
				// ページ割り付け
				content.drawForm(rect[j], PtlContent::ALIGN_CENTER, page);
			}

			++pageNumber;
		}

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

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