SQLの窓

2013年09月07日


WPF アプリケーション(VS2010/C#) の Window 間の扱いを知る為のテンプレート

SkyDrive へ移動


テンプレートを 『C:\Users\ユーザID\Documents\Visual Studio 2010\Templates\ProjectTemplates\Visual C#\Windows』にコピーします。Windows フォルダは C# の中に作成して下さい。



Window と ページ

▼ MyMain ボタンから下のウインドウを開きます ■ 右側の枠は Frame です( Page が表示されます ) ■ Frame 内から MyMain を参照しています
▼ Window2 メニューバーのサンプル付きです( プログラム終了と、ファイルを開くダイアログ ) ■ ダイアログとして呼ばれた時の結果の戻し方 ■ ここからさらに Window を開いて、その中の表示をこちらから変更します
▼ Window3 ■ Navigate Windows です ■ Web ページや Page オブジェクトを表示できます
▼ Window3 ■ Navigate Window に Page を表示したところです
WPF では、Form アプリケーションのように、Owner を取得する事ができないようなので、名前で Windows を参照する為のメソッドを App クラスの static メソッドに作成しています。( 同じ名前の Window を複数作成しないという前提です ) App.xaml.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

namespace WpfForm
{
    public partial class App : Application
    {
        public static Window GetWindow(String name ) {
            Window TargetWindow = null;

            WindowCollection AppWindows = Application.Current.Windows;
            foreach (Window Win in AppWindows)
            {
                if (Win.Name == name)
                {
                    TargetWindow = Win;
                    break;
                }
            }
            return TargetWindow;
        }
    }
}


MainWindow.xaml.cs
namespace WpfForm
{
    public partial class MyMain : Window
    {
        public MyMain()
        {
            InitializeComponent();
            this.frame1.Navigate(new MyPage());
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Window2 normalWindow = new Window2();
            normalWindow.Show();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Window2 normalWindow = new Window2();
            bool? result = normalWindow.ShowDialog();
            if (!(bool)result)
            {
                MessageBox.Show("キャンセル");
            }
        }
    }
}

Null 許容 bool? 型 が使用されています

Window2.xaml.cs
namespace WpfForm
{
    public partial class Window2 : Window
    {
        private Window3 normalWindow = null;

        public Window2()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MyMain owner = Application.Current.MainWindow as MyMain;
            Debug.WriteLine(owner.Title);

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            normalWindow = new Window3();
            normalWindow.Show();

        }

        private void Command_Open_Click(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("メニューがクリックされました");

            // Form 用のクラスの WPF ラッパー
            OpenFileDialog ofg = new OpenFileDialog();
            ofg.Filter = "JPEG|*.jpg*;*.jpg";
            ofg.FilterIndex = 0;
            ofg.FileName = "";

            // Null 許容 bool? 型
            bool? result = ofg.ShowDialog();
            if ((bool)result)
            {
                // パスを表示
                MessageBox.Show(ofg.FileName);
            }

        }

        private void Command_Exit_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("終了しますか?", "終了確認", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                // ダイアログとして呼ばれた時のみ有効
                // ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
                try
                {
                    this.DialogResult = true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                // ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
                // ダイアログとして呼ばれた時のみ有効

                Application.Current.Shutdown();
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                normalWindow.Close();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                normalWindow.Navigate(new MyPage());
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
    }
}

Frame 内の参照は、WEB ページの IFRAME と同様で以下のようになります
(this.frame1.Content as MyPage).button1.Content.ToString()
posted by lightbox at 2013-09-07 23:20 | VS(C#) | このブログの読者になる | 更新情報をチェックする

google-gson(Java) を使って、JSON を 定義済みクラスのオブジェクトに一括変換する

JSON_ENTRY 内を JSON の内容に合わせて作成しておくだけで、一行の処理で全てセットしてくれます。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.google.gson.Gson;

public class HttpAndGet {

	public static void main(String[] args) {

		String http_string = HttpGet();
		System.out.println(http_string);
		
		// Gson を作成
		Gson gson = new Gson();
		
		// 全体の文字列を JSON_ENTRY クラスに投入
		// ( 未定義のものは無視されます )
		JSON_ENTRY je = gson.fromJson(http_string,JSON_ENTRY.class);

		// 一覧表示
		for( int i = 0; i < je.winofsql.length; i++ ) {
			System.out.println(je.winofsql[i]);
		}
	}

	// ******************************************************************
	// JSON を インターネットから取得する
	// ******************************************************************
	public static String HttpGet() {
		String json_string = "";
		
		try {
			// JSON の URL
			URL url = new URL("http://toolbox.winofsql.jp/json/sample2.json");
			// 接続オブジェクト
			HttpURLConnection http = (HttpURLConnection)url.openConnection();
			http.setRequestMethod("GET");
			// 接続 
			http.connect();
			
			// UTF-8 でリーダーを作成
			InputStreamReader isr = new InputStreamReader(http.getInputStream(), "UTF-8");
			
			json_string = new TextReader().getText(new BufferedReader(isr)); 
			
			isr.close();
			http.disconnect();
			
		}
		catch( Exception e ) {
			e.printStackTrace();
			json_string = "{ \"winofsql\" : [\"error\"] }";
		}
		
		return json_string;
		
	}

	// ******************************************************************
	// BufferedReader から テキストを取得
	// ******************************************************************
	static class TextReader {
		public String getText(BufferedReader br) throws IOException {

			String result_string = "";
			String line_buffer = null;   
			// BufferedReader は、readLine が null を返すと読み込み終了   
			while ( null != (line_buffer = br.readLine() ) ) {   
				// コマンドプロンプトに表示   
				result_string += line_buffer;
			}
 
			// 閉じる   
			br.close();
			
			return result_string;
		
		}
	}
	
	static class JSON_ENTRY {
		String[] winofsql;
	}

}

関連する記事

VS(C#) : Json.NET を使用して文字列形式の JSON をプログラムで参照する具代的な方法



posted by lightbox at 2013-09-07 16:46 | java : 通信関連 | このブログの読者になる | 更新情報をチェックする

2013年09月06日


iText( itextsharp-all-5.4.3 / C# ) で簡単に PDF 出力をする。

※ itextsharp-dll-core しか使用していません



Java 用のものから移行しました。Java => C# なので殆ど変更するところはありませんでしたが、メソッドの頭を大文字にするのと、getter を プロパティに変更する作業が殆どでした。

itextsharp.dll は、プロジェクトを作成して NuGet コンソールで 『Install-Package iTextSharp』と実行すると packages というフォルダが作成されて中にインストールされます。

ビルドは、Visual Studio で作って動作確認したものを、バッチファイルでビルドするようにしたのがダウンロードファイルです。ですから、中には、ファイルが4つ入っているだけです。これに加えて『itextsharp.dll』と『iTextSharp.xml』を配置して build.bat を実行すると itext.exe が作成されます。

prompt cs$G
setlocal
set PATH=C:\Windows\Microsoft.NET\Framework\v4.0.30319;%PATH%

csc.exe itext.cs /r:itextsharp.dll

endlocal
※ このパスは、VS2010( Framework4.0 )用です。 出来上がる pdf は、Java もそうですが、埋め込みで行っています。『埋め込む』と言う事は、OS 上にそのフォントが無くても正しく表示されるという事です( 反面、pdf の大きさは大きくなります ) 使い方としては、フォントにはフリーフォント(埋め込む事を著作者が許可しているフォント)を使って pdf を作成するといいと思います。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				itext();
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
			Console.WriteLine("処理が終了しました");

		}

		static void itext()
		{
			string thisPath = Assembly.GetExecutingAssembly().Location;
			string thisDir = Path.GetDirectoryName(thisPath);
			Console.WriteLine(thisDir);

			string pdf = thisDir + @"\pdftest.pdf";

			Document doc = new Document();

			// 出力先を指定し、文書をPDFとして出力
			PdfWriter pw = PdfWriter.GetInstance(
				doc,
				new FileStream(pdf, FileMode.Create)
			);

			// 出力開始
			doc.Open();

			// Windows ディレクトリを取得
			string windir = System.Environment.GetEnvironmentVariable("windir");
			Console.WriteLine(windir);

			// 日本語フォントの設定
			Font font = new Font( 
				BaseFont.CreateFont(
					windir + @"\Fonts\meiryo.ttc,0", 
					BaseFont.IDENTITY_H, 
					BaseFont.EMBEDDED
				 )
			);
/*
// フリーフォントでテスト
// ttf の場合は ファイル名だけで指定します( ttc は複数のフォントが入っています )
			Font font = new Font( 
				BaseFont.CreateFont(
					@"C:\Users\lightbox\Desktop\作業\FONT\ArmedBanana\ArmedBanana\ArmedBanana.ttf", 
					BaseFont.IDENTITY_H, 
					BaseFont.EMBEDDED
				 )
			);
*/

			Font font2 = new Font(
				BaseFont.CreateFont(
					windir + @"\Fonts\meiryo.ttc,1",
					BaseFont.IDENTITY_H,
					BaseFont.EMBEDDED
				 )
			);
			// *****************************************************************
			// 座標指定する為のオブジェクト
			// *****************************************************************
			// 一番上のレイヤー
			PdfContentByte pcb = pw.DirectContent;

			// 一番上のレイヤーに直線を引く
			pcb.MoveTo(0, 820);
			pcb.LineTo(595, 820);
			pcb.Stroke();

			ColumnText ct = new ColumnText(pcb);

			Phrase myText = null;
			String line_text = null;

			int x1 = 400;
			int x2 = 595;

			line_text = "1234567890123456789012345678901234567890";

			myText = new Phrase(line_text, font);
			ct.SetSimpleColumn(
				myText,
				x1, 0,		// 書き込み対象の左下の座標
				x2, 810,	// 書き込み対象の右上の座標
				20,			// 行間
				Element.ALIGN_LEFT
			);
			ct.Go();

			line_text = "ニ行目";

			myText = new Phrase(line_text, font);
			ct.SetSimpleColumn(
				myText,
				x1, 0,
				x2, 750,
				0,
				Element.ALIGN_LEFT
			);
			ct.Go();

			line_text = "三行目";

			myText = new Phrase(line_text, font);
			ct.SetSimpleColumn(
				myText,
				x1, 0,
				x2, 735,
				0,
				Element.ALIGN_LEFT
			);
			ct.Go();

			line_text = "四行目";

			// *****************************************************************
			// 右寄せ
			// *****************************************************************
			int right_offset = 50;
			myText = new Phrase(line_text, font);
			ct.SetSimpleColumn(
				myText,
				x1, 0,
				x2 - right_offset, 720,
				0,
				Element.ALIGN_LEFT
			);
			ct.Go();

			int top = 700;
			myText = new Phrase("left:" + doc.PageSize.Left, font2);
			ct.SetSimpleColumn(
				myText,
				x1, 0,
				x2 - right_offset, top,
				0,
				Element.ALIGN_RIGHT
			);
			ct.Go();

			top -= 10;
			myText = new Phrase("right:" + doc.PageSize.Right, font2);
			ct.SetSimpleColumn(
				myText,
				x1, 0,
				x2 - right_offset, top,
				0,
				Element.ALIGN_RIGHT
			);
			ct.Go();

			top -= 10;
			myText = new Phrase("top:" + doc.PageSize.Top, font2);
			ct.SetSimpleColumn(
				myText,
				x1, 0,
				x2 - right_offset, top,
				0,
				Element.ALIGN_RIGHT
			);
			ct.Go();

			top -= 10;
			myText = new Phrase("bottom:" + doc.PageSize.Bottom, font2);
			ct.SetSimpleColumn(
				myText,
				x1, 0,
				x2 - right_offset, top,
				0,
				Element.ALIGN_RIGHT
			);
			ct.Go();

			// *****************************************************************
			// 真ん中のレイヤー( 通常の文字列や画像・グラフィックの追加 )
			// *****************************************************************

			Image img = Image.GetInstance("_img.jpg");
			img.SetAbsolutePosition(140, 620);
			img.ScalePercent(50);
			doc.Add(img);

			doc.Add(new Paragraph(" ", font));	// 改行
			doc.Add(new Paragraph(" ", font));
			doc.Add(new Paragraph(" ", font));
			doc.Add(new Paragraph(" ", font));
			doc.Add(new Paragraph(" ", font));

			doc.Add(new Paragraph("文を 一行出力", font));
			doc.Add(new Paragraph("文を 一行出力", font));
			doc.Add(new Paragraph("文を 一行出力", font));
			doc.Add(new Paragraph("文を 一行出力", font));
			doc.Add(new Paragraph("文を 一行出力", font));

			doc.Add(new Paragraph(" ", font));

			Paragraph p = new Paragraph();
			for (int i = 0; i < 25; i++)
			{
				p.Add(
					new Chunk(
						"日本語表示の一般テキストを繰り返し表示しています。"
						, font
					)
				);
			}
			doc.Add(p);

			// 出力終了
			doc.Close();

		}
	}
}

itextsharp-all

ダウンロード



posted by lightbox at 2013-09-06 20:04 | VS(C#) | このブログの読者になる | 更新情報をチェックする

JSONLint サービスを使って、JSON が正しいかどうかをチェックして整形する。



http://jsonlint.com/ で JSON 文字列を貼り付けて実行するだけなのですが、以下のように URL を直接渡す事ができます

http://jsonlint.com/?json=http%3A%2F%2Ftoolbox.winofsql.jp%2Fjson%2Fsample1.json

テキストエリアの中に URL を貼り付けて実行してもかまいません
{
    "id": 91500526,
    "simple_array": [
        1,
        2,
        3,
        4,
        5
    ],
    "object_array": [
        {
            "high": 1,
            "middle": 2,
            "low": 3
        },
        {
            "high": 21,
            "middle": 22,
            "low": 23
        },
        {
            "high": 31,
            "middle": 32,
            "low": 33
        }
    ],
    "object_data": {
        "sworc": "lightbox"
    },
    "profile_background_tile": false,
    "notifications": false,
    "profile_sidebar_fill_color": "FFF7CC",
    "location": "大阪府",
    "screen_name": "sworc",
    "profile_image_url": "http://a0.twimg.com/profile_images/2388651010/zmq5cwm5nsvngpfrtr3f_normal.png"
}


タグ:JSON
posted by lightbox at 2013-09-06 14:40 | WEBサービス | このブログの読者になる | 更新情報をチェックする

2013年09月05日


コンソールアプリケーション(C#) で、クラス、デリゲート、イベント、ラムダ式の振舞いを理解する

コンソールアプリケーションで、ループしてコマンド毎に処理を行うと言うのは昔から良く書かれたコードですが、クラスを使ってクラスのメソッド内でループし、コマンドに対応する処理はイベント扱いにして、クラスのインスタンスを作成した側でイベント登録して処理を実装しています。

❶ public delegate void AppHandler( string cmd );

イベント( メソッド ) の形式を定義しています。

❷ public event AppHandler DisplayArg = null;

delegate を使って定義されたイベントを格納する為の公開変数を定義しています

❸ DisplayArg(line);

DisplayArg イベントをクラス内から呼び出しています。

❹ app.DisplayArg += arg1; と app.DisplayArg += arg2;

二つのメソッドをイベントとして追加し、クラス内の呼び出し記述は一つですが、二つとも呼び出されます。

❺ app.Select += (string cmd) => {}

メソッドの定義をせずに、ラムダ式を使って匿名のメソッドを作成してその場に記述しています

▼ エントリポイント
using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
	public class Program
	{
		// 引数
		public static string[] args;
		// DB接続文字列
		static string cs = "Driver={MySQL ODBC 5.2 Unicode Driver};" +
			"Server=localhost;" +
			"Database=lightbox;" +
			"Uid=root;" + 
			"Pwd=パスワード;";

		static void Main(string[] args)
		{
			// 引数を保存
			Program.args = args;

			App app = new App();
			// 単純にメソッドを追加
			app.DisplayArg += arg1;
			app.DisplayArg += arg2;
			// イベントの追加を明示する
			app.OpenDb += new App.AppHandler(open);

			// ラムダ式による実装( 手間を考えると、new は省いたほうが良い )
			app.Select += (string cmd) =>
			{
				Console.WriteLine(cmd + " が実行されました");

				// select の結果を表示する
			};

			// ******************************************
			// 終了せずに、コマンドプロンプトを保持する。
			// ( "q" で終了 )
			// ******************************************
			app.Loop();

		}

		// ******************************************
		// 引数の表示を行うイベント
		// ******************************************
		static private void arg1( string cmd )
		{
			Console.WriteLine(cmd + " が実行されました");

			// 引数の数
			Console.WriteLine("引数の数 : " + Program.args.Length);

		}
		static private void arg2(string cmd)
		{
			// 引数を全て表示
			int len = Program.args.Length;
			for (int i = 0; i < len; i++)
			{
				Console.WriteLine(Program.args[i]);
			}

		}

		// ******************************************
		// データーベースを開くイベント
		// ******************************************
		static private void open(string cmd )
		{
			Console.WriteLine(cmd + " が実行されました");

			using (OdbcConnection cn = new OdbcConnection(Program.cs))
			{
				try
				{
					cn.Open();
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
				Console.WriteLine("State={0}", cn.State);
			}
			Console.WriteLine("処理が終了しました");
		}
	}
}


▼ クラス
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
	class App
	{
		public delegate void AppHandler( string cmd );
		public event AppHandler DisplayArg = null;
		public event AppHandler OpenDb = null;
		public event AppHandler Select = null;

		// ******************************************
		// コンストラクタ
		// ******************************************
		public App()
		{
		}

		// ******************************************
		// 終了せずに、コマンドプロンプトを保持する。
		// ******************************************
		public void Loop()
		{
			while (true)
			{
				// 専用プロンプト
				Console.Write("app>");
				string line = Console.ReadLine();

				// 終了コマンド
				if (line == "q")
				{
					break;
				}

				// 引数情報表示
				if (line == "arg")
				{
					if (DisplayArg != null)
					{
						DisplayArg(line);
					}
				}

				// DBを開く
				if (line == "open")
				{
					if (OpenDb != null)
					{
						OpenDb(line);
					}
				}

				// select 実行の表示
				if (line == "select")
				{
					if (Select != null)
					{
						Select(line);
					}
				}

			}
		}
	}
}

関連する記事

+= new EventHandler(Method) vs += Method
( どちらでも同じだという英文の記事です )


posted by lightbox at 2013-09-05 22:47 | VS(C#) | このブログの読者になる | 更新情報をチェックする

2013年09月03日


iText( itextpdf-5.4.3 / Java ) で簡単に PDF 出力をする。

作成した PDF へのリンク


ビルド用バッチファイル
prompt java$G
setlocal
set PATH=C:\Program Files\Java\jdk1.6.0_24\bin;%PATH%
set CLASSPATH=.;itextpdf-5.4.3.jar

javac Main.java

endlocal
実行用バッチファイル
prompt java$G
setlocal
set PATH=C:\Program Files\Java\jdk1.6.0_24\bin;%PATH%
set CLASSPATH=.;itextpdf-5.4.3.jar

REM 実行
java Main

endlocal
iText ダウンロード iText メインページ iText ドキュメント iText サンプルページ ダウンロードした itextpdf-5.4.3.jar は、テストコードと同じディレクトリに置いて、JDK のインストール先(ここでは C:\Program Files\Java\jdk1.6.0_24)を書き換えてビルドすれば、実行後 pdftest.pdf が作成されます。
// http://api.itextpdf.com/itext/index.html?com/itextpdf/text/pdf/ColumnText.html
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.*;

import java.io.FileOutputStream;

public class Main {

	// *****************************************************
	// エントリポイント
	// *****************************************************
	public static void main(String[] args) {
		Main thisClass = new Main();
	}

	// *****************************************************
	// コンストラクタ
	// *****************************************************
	public Main() {
		super();
		my_acton();
	}

	// *****************************************************
	// 初期処理
	// *****************************************************
	private void my_acton() {

		System.out.println("処理開始");


		String pdf = "pdftest.pdf";

		Document doc = new Document(); 

		try {
			// 出力先を指定し、文書をPDFとして出力
			PdfWriter pw = PdfWriter.getInstance(doc, new FileOutputStream(pdf));
			// 出力開始
			doc.open();

			// 日本語フォントの設定

			// メイリオ
			Font font = new Font(
				BaseFont.createFont(
					"C:\\WINDOWS\\Fonts\\meiryo.ttc,0",
					BaseFont.IDENTITY_H,
					BaseFont.EMBEDDED));

			// メイリオボールド
			Font font2 = new Font(
				BaseFont.createFont(
					"C:\\WINDOWS\\Fonts\\meiryob.ttc,0",
					BaseFont.IDENTITY_H,
					BaseFont.EMBEDDED));


			// *****************************************************************
			// 座標指定する為のオブジェクト
			// *****************************************************************
			// 一番上のレイヤー
			PdfContentByte pcb = pw.getDirectContent();

			// 一番上のレイヤーに直線を引く
			pcb.moveTo( 0, 820 );
			pcb.lineTo( 595, 820 );
			pcb.stroke();

			ColumnText ct = new ColumnText(pcb);

			Phrase myText = null;
			String line_text = null;

			int x1 = 400;
			int x2 = 595;

			line_text = "1234567890123456789012345678901234567890";

			myText = new Phrase(line_text,font);
			ct.setSimpleColumn(
				myText,
				x1,0,		// 書き込み対象の左下の座標
				x2, 810,	// 書き込み対象の右上の座標
				20,			// 行間
				Element.ALIGN_LEFT
			);
			ct.go();

			line_text = "ニ行目";

			myText = new Phrase(line_text,font);
			ct.setSimpleColumn(
				myText,
				x1,0,
				x2, 750,
				0,
				Element.ALIGN_LEFT
			);
			ct.go();

			line_text = "三行目";

			myText = new Phrase(line_text,font);
			ct.setSimpleColumn(
				myText,
				x1,0,
				x2, 735,
				0,
				Element.ALIGN_LEFT
			);
			ct.go();

			line_text = "四行目";

			// *****************************************************************
			// 右寄せ
			// *****************************************************************
			int right_offset = 50;
			myText = new Phrase(line_text,font);
			ct.setSimpleColumn(
				myText,
				x1,0,
				x2-right_offset, 720,
				0,
				Element.ALIGN_LEFT
			);
			ct.go();

			int top = 700;
			myText = new Phrase("left:"+doc.getPageSize().getLeft(),font2);
			ct.setSimpleColumn(
				myText,
				x1, 0,
				x2-right_offset, top,
				0,
				Element.ALIGN_RIGHT
			);
			ct.go();

			top -= 10;
			myText = new Phrase("right:"+doc.getPageSize().getRight(),font2);
			ct.setSimpleColumn(
				myText,
				x1, 0,
				x2-right_offset, top,
				0,
				Element.ALIGN_RIGHT
			);
			ct.go();

			top -= 10;
			myText = new Phrase("top:"+doc.getPageSize().getTop(),font2);
			ct.setSimpleColumn(
				myText,
				x1,0,
				x2-right_offset, top,
				0,
				Element.ALIGN_RIGHT
			);
			ct.go();

			top -= 10;
			myText = new Phrase("bottom:"+doc.getPageSize().getBottom(),font2);
			ct.setSimpleColumn(
				myText,
				x1,0,
				x2-right_offset, top,
				0,
				Element.ALIGN_RIGHT
			);
			ct.go();

			// *****************************************************************
			// 真ん中のレイヤー( 通常の文字列や画像・グラフィックの追加 )
			// *****************************************************************

			Image img = Image.getInstance("_img.jpg");
			img.setAbsolutePosition(140, 620);
			img.scalePercent(50);
			doc.add(img);

			doc.add( new Paragraph(" ", font) );	// 改行
			doc.add( new Paragraph(" ", font) );
			doc.add( new Paragraph(" ", font) );
			doc.add( new Paragraph(" ", font) );
			doc.add( new Paragraph(" ", font) );

			doc.add( new Paragraph("文を 一行出力", font) );
			doc.add( new Paragraph("文を 一行出力", font) );
			doc.add( new Paragraph("文を 一行出力", font) );
			doc.add( new Paragraph("文を 一行出力", font) );
			doc.add( new Paragraph("文を 一行出力", font) );

			doc.add( new Paragraph(" ", font) );

			Paragraph p = new Paragraph();
			for (int i = 0; i < 25; i++) {
				p.add(
					new Chunk(
						"日本語表示の一般テキストを繰り返し表示しています。"
						,font
					)
				);
			}
			doc.add(p);

			// 出力終了
			doc.close();

		}
		catch (Exception e) {
			e.printStackTrace();
		}


		System.out.println("処理終了");

	}

}

メイリオについて

meiryo.ttc,0 を meiryo.ttc,1 にすればメイリオイタリックになります。(ボールドのほうも同様です)

レイヤーについて

レイヤーはもう一枚、一番下にありますが通常の文書では必要無いと思います。

setSimpleColumn について

矩形を指定しますが、開始が左下隅で、終了が右上隅になります。6番目の引数は行間を示し、矩形からあふれるばあいに使用される行間です。

ページのサイズ について

真ん中のレイヤーである、Document に対して以下のメソッドを実行して取得しています
getPageSize().getLeft()
getPageSize().getRight()
getPageSize().getTop()
getPageSize().getBottom()

Document 内の改行について

doc.add( new Paragraph(" ", font) ); で改行します( スペースを出力します )

一般的な出力について

単純なテキスト印刷の場合であれば、Document のみで問題無いと思いますが、文書としてのフォーマットを固定部分として定義して、中身にテキストを出力するように場合、getDirectContent を使って取得した PdfContentByte を使って出力すると良いと思います。もう一枚のレイヤーは、さらに背景にバリエーションを与える必要がある場合に使用するといいと思います。( getDirectContentUnder() で取得します )


posted by lightbox at 2013-09-03 15:50 | Java | このブログの読者になる | 更新情報をチェックする
Seesaa の各ページの表示について
Seesaa の 記事がたまに全く表示されない場合があります。その場合は、設定> 詳細設定> ブログ設定 で 最新の情報に更新の『実行ボタン』で記事やアーカイブが最新にビルドされます。

Seesaa のページで、アーカイブとタグページは要注意です。タグページはコンテンツが全く無い状態になりますし、アーカイブページも歯抜けページはコンテンツが存在しないのにページが表示されてしまいます。

また、カテゴリページもそういう意味では完全ではありません。『カテゴリID-番号』というフォーマットで表示されるページですが、実際存在するより大きな番号でも表示されてしまいます。

※ インデックスページのみ、実際の記事数を超えたページを指定しても最後のページが表示されるようです

対処としては、このようなヘルプ的な情報を固定でページの最後に表示するようにするといいでしょう。具体的には、メインの記事コンテンツの下に『自由形式』を追加し、アーカイブとカテゴリページでのみ表示するように設定し、コンテンツを用意するといいと思います。


※ エキスパートモードで表示しています

アーカイブとカテゴリページはこのように簡単に設定できますが、タグページは HTML 設定を直接変更して、以下の『タグページでのみ表示される内容』の記述方法で設定する必要があります

<% if:page_name eq 'archive' -%>
アーカイブページでのみ表示される内容
<% /if %>

<% if:page_name eq 'category' -%>
カテゴリページでのみ表示される内容
<% /if %>

<% if:page_name eq 'tag' -%>
タグページでのみ表示される内容
<% /if %>
この記述は、以下の場所で使用します
container 終わり



フリーフォントで簡単ロゴ作成
フリーフォントでボタン素材作成
フリーフォントで吹き出し画像作成
フリーフォントではんこ画像作成
ほぼ自由に利用できるフリーフォント
フリーフォントの書体見本とサンプル
画像を大きく見る為のウインドウを開くボタンの作成

CSS ドロップシャドウの参考デモ
イラストAC
ぱくたそ
写真素材 足成
フリーフォント一覧
utf8 文字ツール
右サイド 終わり
base 終わり