第05回 PDFファイルの内容を表示する

今回の処理は作ろうとしているツールとは無関係ですが、
前回までに抜き出したPDFファイル内のテキスト情報を画面表示します。

フォーム上にPictureBoxを配置して、そこにGraphicsとして描く形で表示しました。
マウスクリックでページを進む/戻るが可能です。

■Form1.cs
using System.Drawing;
using System.Windows.Forms;

namespace Pdf2Pdf
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();

			PDFTextReader pr = new PDFTextReader();
			bool ret = pr.Read(@"c:\N9442CW.pdf");


			PictureBox pictureBox1 = new PictureBox();
			pictureBox1.Parent = this;
			pictureBox1.Dock = DockStyle.Fill;


			int nPage = 0;

			Bitmap bmp = new Bitmap(Width, Height);
			DrawPage(pr, nPage, bmp);
			pictureBox1.Image = bmp;


			pictureBox1.MouseUp += (sender, e) =>
			{
				if (e.Button == MouseButtons.Left)
					nPage++;
				else if (e.Button == MouseButtons.Right)
					nPage--;
				else
					return;

				bmp = new Bitmap(Width, Height);

				while (true)
				{
					ret = DrawPage(pr, nPage, bmp);
					if (ret)
						break;

					nPage++;
					if (nPage >= pr.Pages.Count)
						break;
				}

				pictureBox1.Image.Dispose();
				pictureBox1.Image = bmp;
			};
		}

		//横書きに変換表示
		bool DrawPage(PDFTextReader pr, int nPage, Bitmap bmp)
		{
			if (nPage < 0 || nPage >= pr.Pages.Count)
				return false;

			PDFPage page = pr.Pages[nPage];

			using (Graphics g = Graphics.FromImage(bmp))
			using (Font font = new Font("MS ゴシック", 10))
			{
				foreach (object obj in page.Items)
				{
					if (obj.GetType() != typeof(PDFText))
						continue;

					//(0,0)はページ左下
					//A4縦は(595,842)がページ右上
					//A4横は(842,595)がページ右上

					float x = (obj as PDFText).fX;
					float y = (obj as PDFText).fY;

					//ページ番号は描画しない
					//ページ番号のy座標は56.7?
					if ((int)(y) == 56)
						continue;


					x = 842 - x;
					y = 595 - y;
					g.DrawString((obj as PDFText).strText, font, System.Drawing.Brushes.Black, y, x);
				}
			}
			return true;
		}

	}
}

プロジェクトファイルをダウンロード



カテゴリー「PDFを処理する(C#)」 のエントリー