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

	概要：テキストオブジェクトの挿入

	Copyright 2013-2025 Antenna House, Inc.
*/

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

using namespace PdfTk;

void writeString(PtlPage& page, PtlParamString str);

int main(int argc, char* argv[])
{
	if (argc < 3) {
		printf("usage: WriteTextPageNo.exe in-pdf-file out-pdf-file\n");
		return 1;
	}
	try
	{
		PtlParamInput input(argv[1]);
		PtlParamOutput output(argv[2]);

		PtlPDFDocument doc;

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

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

		if (pages.isEmpty()) {
			printf("ページコンテナが空\n");
			return 1;
		}

		int pageno = pages.getCount();

		// 現在日時取得
		time_t now = time(NULL);
		struct tm local_time;
		errno_t err = localtime_s(&local_time, &now);
		int year = 0;
		int month = 0;
		int day = 0;
		char str[10];
		if (err == 0) {
			year = local_time.tm_year + 1900;
			month = local_time.tm_mon + 1;
			day = local_time.tm_mday;
		}

		for (int i = 0; i < pageno; i++)
		{
			// ページの取得
			PtlPage page = pages.get(i);
			
			char str[40];
			int ret = sprintf_s(str, "実行日：%d/%d/%d  ページ番号：%d/ %d", year, month, day, i + 1, pageno);

			// テキスト追加
			writeString(page, str);
		}

		// ファイルに保存します。
		doc.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;
}

//文字列出力
void writeString(PtlPage& page, PtlParamString str)
{
	//ページコンテントの取得
	PtlContent& content = page.getContent();
	PtlSize pageSize = page.getSize();

	//出力矩形
	PtlRect rect(0.0f, 0.0f, pageSize.getWidth(), pageSize.getHeight());

	//文字の描画に使うパラメータクラス
	PtlParamWriteString writestring;

	//フォント指定に使うパラメータクラス
	PtlParamFont font;

	//フォント名の設定
	font.setName("游ゴシック");

	//サイズの設定
	font.setSize(12.0f);


	//フォントの設定
	writestring.setFont(font);

	//文字色設定
	writestring.setTextColor(PtlColorDeviceRGB(1.0f, 0.0f, 0.0f));
	writestring.setOutlineColor(PtlColorDeviceRGB(0.0f, 0.0f, 1.0f));

	//文字列出力
	content.writeString(rect, PtlContent::ALIGN_TOP_RIGHT, str, writestring);
}
