前の10件 1  2  3  4  5  6  7  8  9  10  11

記事一覧

第15回 スレッドで処理する

複数のPDFファイルを一度に変換すると、変換中はUI動作が固まります。
それを防ぐため、変換処理をスレッド上で実行するように変更します。

今回はTaskを利用しました。
処理の開始中はドラッグアンドドロップを禁止し、新たな処理が開始されるのを防いでいます。

■Form1.cs
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

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

			Label label1 = new Label();
			label1.Parent = this;
			label1.Dock = DockStyle.Fill;
			label1.TextAlign = ContentAlignment.MiddleCenter;
			label1.Text = "ここに\"小説家になろう\"縦書きPDFをドラッグアンドドロップしてください";

			label1.AllowDrop = true;

			label1.DragEnter += (sender, e) =>
			{
				if (e.Data.GetDataPresent(DataFormats.FileDrop))
				{
					e.Effect = DragDropEffects.Copy;
				}
			};

			label1.DragDrop += (sender, e) =>
			{
				if (e.Data.GetDataPresent(DataFormats.FileDrop))
				{
					string[] items = (string[])e.Data.GetData(DataFormats.FileDrop);


					//タスク(スレッド)で実行
					Task.Run(() =>
					{
						string strLabel = label1.Text;		//ラベル文字を処理中は退避

						Invoke((MethodInvoker)delegate
						{
							label1.AllowDrop = false;		//処理中は新たなドラッグアンドドロップを禁止する
							label1.Text = "変換処理を開始します。\n処理合計ファイル数:" + items.Length;
						});

						for (int i = 0; i < items.Length; i++)
						{
							string file = items[i];

							if (File.Exists(file) == false)
								continue;

							//「小説家になろう」縦書きPDFを読み込む
							PDFTextReader pr = new PDFTextReader();
							bool ret = pr.Read(file);

							string strTitle = "";

							//読み込んだ縦書きPDFに含まれる小説のタイトルを取得
							//(タイトルは最初のページの最初のstrText)
							foreach (PDFPage page in pr.Pages)
							{
								foreach (object obj in page.Items)
								{
									if (obj.GetType() != typeof(PDFText))
										continue;

									strTitle = (obj as PDFText).strText;
									if (strTitle != "")
										break;
								}
								if (strTitle != "")
									break;
							}

							//小説タイトルをファイル名にする
							// →ファイル名に使えない文字を除去
							{
								//ありがちな文字は決め打ちで全角に
								strTitle = strTitle.Replace('*', '*');
								strTitle = strTitle.Replace('\\', '¥');
								strTitle = strTitle.Replace(':', ':');
								strTitle = strTitle.Replace('<', '<');
								strTitle = strTitle.Replace('>', '>');
								strTitle = strTitle.Replace('?', '?');
								strTitle = strTitle.Replace('|', '|');

								char[] pcbInvalid = Path.GetInvalidFileNameChars();

								//使えない文字除去
								foreach (char c in pcbInvalid)
								{
									strTitle = strTitle.Replace(c.ToString(), "");
								}

								//タイトルがなくなったら、元々のPDFのファイル名に"_cnv"を付加
								if (strTitle == "")
									strTitle = Path.GetFileNameWithoutExtension(file + "_cnv");
							}

							string strNewFile = "";

							//書き出したいファイル名がすでに存在していたら、上書きしないように存在しないファイル名を生成
							while (true)
							{
								strNewFile = Path.GetDirectoryName(file) + "\\" + strTitle + ".pdf";
								if (File.Exists(strNewFile) == false)
									break;

								strTitle += "_" + DateTime.Now.Ticks;
							}

							//横書きPDFを書き出す
							PDFTextWriter pw = new PDFTextWriter();
							pw.ConvertPDFFile(strNewFile, pr);

							Invoke((MethodInvoker)delegate
							{
								label1.Text = "変換処理中です。\n残りファイル数:" + (items.Length - i - 1);
							});
						}

						Invoke((MethodInvoker)delegate
						{
							label1.AllowDrop = true;		//ドラッグアンドドロップ受付可能にする
							label1.Text = strLabel;			//ラベル文字を元に戻す
						});
					});

				}
			};

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

第14回 ドラッグアンドドロップで処理する

これまではソースコード内で直接ファイル名を指定した形で処理していました。
今回はウインドウにドラッグアンドドロップしたPDFを処理するように変更します。

「小説家になろう」の縦書きPDFは最初のページの最初のテキストがその小説のタイトルになっています。
そこから小説のタイトルを抜き出し、ファイル名として使えない文字がある場合はそれを置換し、
小説のタイトルを変換後のファイル名としてPDFを書き出すようにします。

また、今までウインドウに表示していた小説表示機能は削除します。

これにより複数のファイルを一度に変換可能になりました。

■Form1.cs
using System;
using System.Drawing;
using System.IO;
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");


			//PDFTextWriter pw = new PDFTextWriter();
			//pw.ConvertPDFFile("test.pdf", pr);


			Label label1 = new Label();
			label1.Parent = this;
			label1.Dock = DockStyle.Fill;
			label1.TextAlign = ContentAlignment.MiddleCenter;
			label1.Text = "ここに\"小説家になろう\"縦書きPDFをドラッグアンドドロップしてください";

			label1.AllowDrop = true;

			label1.DragEnter += (sender, e) =>
			{
				if (e.Data.GetDataPresent(DataFormats.FileDrop))
				{
					e.Effect = DragDropEffects.Copy;
				}
			};

			label1.DragDrop += (sender, e) =>
			{
				if (e.Data.GetDataPresent(DataFormats.FileDrop))
				{
					string[] items = (string[])e.Data.GetData(DataFormats.FileDrop);

					foreach (string file in items)
					{
						if (File.Exists(file) == false)
							continue;

						//「小説家になろう」縦書きPDFを読み込む
						PDFTextReader pr = new PDFTextReader();
						bool ret = pr.Read(file);

						string strTitle = "";

						//読み込んだ縦書きPDFに含まれる小説のタイトルを取得
						//(タイトルは最初のページの最初のstrText)
						foreach (PDFPage page in pr.Pages)
						{
							foreach (object obj in page.Items)
							{
								if (obj.GetType() != typeof(PDFText))
									continue;

								strTitle = (obj as PDFText).strText;
								if (strTitle != "")
									break;
							}
							if (strTitle != "")
								break;
						}

						//小説タイトルをファイル名にする
						// →ファイル名に使えない文字を除去
						{
							//ありがちな文字は決め打ちで全角に
							strTitle = strTitle.Replace('*', '*');
							strTitle = strTitle.Replace('\\', '¥');
							strTitle = strTitle.Replace(':', ':');
							strTitle = strTitle.Replace('<', '<');
							strTitle = strTitle.Replace('>', '>');
							strTitle = strTitle.Replace('?', '?');
							strTitle = strTitle.Replace('|', '|');

							char[] pcbInvalid = Path.GetInvalidFileNameChars();

							//使えない文字除去
							foreach (char c in pcbInvalid)
							{
								strTitle = strTitle.Replace(c.ToString(), "");
							}

							//タイトルがなくなったら、元々のPDFのファイル名に"_cnv"を付加
							if (strTitle == "")
								strTitle = Path.GetFileNameWithoutExtension(file + "_cnv");
						}

						string strNewFile = "";

						//書き出したいファイル名がすでに存在していたら、上書きしないように存在しないファイル名を生成
						while (true)
						{
							strNewFile = Path.GetDirectoryName(file) + "\\" + strTitle + ".pdf";
							if (File.Exists(strNewFile) == false)
								break;

							strTitle += "_" + DateTime.Now.Ticks;
						}

						//横書きPDFを書き出す
						PDFTextWriter pw = new PDFTextWriter();
						pw.ConvertPDFFile(strNewFile, pr);
					}
				}
			};


			//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;
		//}
	}
}

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

2016年04月03日

第13回 小説家になろう縦書きPDFを変換する

今回はようやく目的の機能実装です。

「小説家になろう」からダウンロードした縦書きPDFファイルを読み込む処理は以前に作成しました。
そこに含まれるテキスト情報を横書きPDFとして変換しながら書き出します。
PDFの書き台処理もこれまでに作成したものがそのまま利用できるため、体裁を整える作業のみです。

DSC_1343.JPG
「小説家になろう」からダウンロードした縦書きPDFに対してAcrobatでフォントを埋め込んで、Kindleに転送/表示した状態がこれ。

文字が小さく表示が薄いなど読みにくい状態。

フォントの埋め込み処理もかなり時間がかかります。


DSC_1342.JPG
今回作成した処理で縦書きPDFから横書きPDFへ変換した状態がこれ。

かなり改善して読みやすくなりました。変換速度も気になるほど遅くありません。

難はルビ位置。ルビが正しい位置に表示されません。

■Form1.cs
		public Form1()
		{
			InitializeComponent();

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

			PDFTextWriter pw = new PDFTextWriter();
			pw.ConvertPDFFile("test.pdf", pr);

			PictureBox pictureBox1 = new PictureBox();
			pictureBox1.Parent = this;
			pictureBox1.Dock = DockStyle.Fill;
■PDFTextWriter.cs
		/// <summary>
		/// "小説家になろう"の縦書きPDF変換処理
		/// </summary>
		public bool ConvertPDFFile(string strFile, PDFTextReader srcPDF)
		{
			Close();

			int nObjIndex = 1;

			using (FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write))
			using (PDFRawWriter bw = new PDFRawWriter(fs))
			{
				//ヘッダー出力
				bw.WriteLine("%PDF-1.7");

				//フォント出力
				int nResourceIndex;
				{
					nResourceIndex = nObjIndex;



					//フォント埋め込み
					{
						List<KeyValuePair<string, int>> listFonts = new List<KeyValuePair<string, int>>();

						{
							string strFontObjName = "F0";
							listFonts.Add(new KeyValuePair<string, int>(strFontObjName, nObjIndex));
							WriteFont_EmbeddedUnicode(bw, ref nObjIndex, strFontObjName, "MS-Gothic", "MS Gothic", @"msgothic.otf");
						}

						//フォント一覧のみのリソース
						nResourceIndex = nObjIndex;
						_listnXref.Add(bw.BaseStream.Position);
						{
							bw.WriteLine("" + nObjIndex + " 0 obj");
							bw.WriteLine("<</Font");
							bw.WriteLine("<<");
							foreach (KeyValuePair<string, int> pair in listFonts)
							{
								bw.WriteLine("/" + pair.Key + " " + pair.Value + " 0 R");
							}
							bw.WriteLine(">>");
							bw.WriteLine(">>");
							bw.WriteLine("endobj");
						}
						nObjIndex++;
					}
				}

				//カタログ出力
				int nRoot = nObjIndex;
				{
					WriteCatalog(bw, ref nObjIndex, nObjIndex + 1);
				}

				//ページ出力
				{
					List<int> listPage = new List<int>();

					//全ページのインデックスを出力
					int nPagesReferenceIndex = nObjIndex;
					{
						for (int i = 0; i < srcPDF.Pages.Count; i++)
						{
							listPage.Add(nObjIndex + 1 + i * 2);	//iページ目のインデックスを渡す
						}

						WritePages(bw, ref nObjIndex, listPage);
					}


					//サイズは適当に決定
					int nWidth = 455;
					int nHeight = 615;

					//ページ出力
					for (int i = 0; i < srcPDF.Pages.Count; i++)
					{
						PDFPage page = srcPDF.Pages[i];

						WritePageContentsIndex(bw, ref nObjIndex, nPagesReferenceIndex, nResourceIndex, nObjIndex + 1, nWidth, nHeight);

						//ページテキスト出力
						{
							List<PDFText> listTexts = new List<PDFText>();

							//テキストの準備
							{
								float y = nHeight - 5;
								foreach (object item in page.Items)
								{
									if (item.GetType() != typeof(PDFText))
										continue;

									PDFText text = (PDFText)item;

									//ページ番号は左下に表示
									if ((int)(text.fY) == 56)		//"小説家になろう"PDFのページ番号y座標は56.7?
									{
										listTexts.Add(new PDFText("F0", text.fPoint, 5, 5, text.strText));
										continue;
									}

									//表紙(i == 0)と最終ページ以外はオリジナルの行間隔で表示
									if (i > 0 && i < srcPDF.Pages.Count - 1)
										y = (int)(text.fX * nHeight / 842.0);
									else
										y -= 17;		//表紙(i == 0)と最終ページは固定行間隔で表示

									listTexts.Add(new PDFText("F0", text.fPoint, 10, y, text.strText));
								}
							}




							//コンテンツの書き出し
							using (MemoryStream ms = new MemoryStream())
							using (BinaryWriter bwms = new BinaryWriter(ms))
							{
								//文字データをPDF出力用に準備
								PrepareTextContents(ms, listTexts);

								//Kindleはコンテンツ内容によって勝手にズーム表示しちゃうから、
								//すべてのページに枠線を描くことで勝手にズームしないようにする
								//座標固定で枠線を描く
								PrepareLineContents(ms, 2, 2, 2, nHeight - 2);
								PrepareLineContents(ms, 2, 2, nWidth - 2, 2);
								PrepareLineContents(ms, nWidth - 2, 2, nWidth - 2, nHeight - 2);
								PrepareLineContents(ms, 2, nHeight - 2, nWidth - 2, nHeight - 2);

								ms.Flush();

								byte[] data = ms.ToArray();

								//ページコンテンツの出力
								WriteFlateData(bw, ref nObjIndex, data);
							}
						}
					}
				}

				//クロスリファレンス/トレーラー出力
				WriteXrefTrailer(bw, nRoot);
			}

			return true;
		}


		/// <summary>
		/// ストリームに線データを書き込む
		/// </summary>
		void PrepareLineContents(Stream strm, int x1, int y1, int x2, int y2)
		{
			byte[] data = Encoding.ASCII.GetBytes(string.Format("{0} {1} m {2} {3} l S\r", x1, y1, x2, y2));
			strm.Write(data, 0, data.Length);
		}

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

第12回 PDF内で複数のフォントを扱う

これまではPDF内のテキストは1つのフォントのみ利用可能でした。
今回は複数のフォントを利用できるようにします。

ついでに書き出すページも2ページに増やしておきました。
ここまで処理ができればツールの作成も目前です。

■PDFTextWriter.cs
		public bool CreatePDFFile(string strFile)
		{
			Close();

			int nObjIndex = 1;

			using (FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write))
			using (PDFRawWriter bw = new PDFRawWriter(fs))
			{
				//ヘッダー出力
				bw.WriteLine("%PDF-1.7");

				//フォント出力
				int nResourceIndex;
				{
					nResourceIndex = nObjIndex;


					//フォント埋め込み
					{
						List<KeyValuePair<string, int>> listFonts = new List<KeyValuePair<string, int>>();

						{
							string strFontObjName = "F0";
							listFonts.Add(new KeyValuePair<string, int>(strFontObjName, nObjIndex));
							WriteFont_EmbeddedUnicode(bw, ref nObjIndex, strFontObjName, "MS-Gothic", "MS Gothic", @"msgothic.otf");
						}
						{
							string strFontObjName = "F1";
							listFonts.Add(new KeyValuePair<string, int>(strFontObjName, nObjIndex));
							WriteFont_Ascii(bw, ref nObjIndex, "Times-Italic", strFontObjName);						//欧文フォント指定
						}
						{
							string strFontObjName = "F2";
							listFonts.Add(new KeyValuePair<string, int>(strFontObjName, nObjIndex));
							WriteFont_UnicodeJapanese(bw, ref nObjIndex, "KozMinPr6N-Regular", strFontObjName);		//日本語フォント指定(フォント埋め込みなし)
						}

						//埋め込みフォント一覧のみのリソース
						nResourceIndex = nObjIndex;
						_listnXref.Add(bw.BaseStream.Position);
						{
							bw.WriteLine("" + nObjIndex + " 0 obj");
							bw.WriteLine("<</Font");
							bw.WriteLine("<<");
							foreach (KeyValuePair<string, int> pair in listFonts)
							{
								bw.WriteLine("/" + pair.Key + " " + pair.Value + " 0 R");
							}
							bw.WriteLine(">>");
							bw.WriteLine(">>");
							bw.WriteLine("endobj");
						}
						nObjIndex++;
					}
				}

				//カタログ出力
				int nRoot = nObjIndex;
				{
					WriteCatalog(bw, ref nObjIndex, nObjIndex + 1);
				}

				//ページ出力
				{
					List<int> listPage = new List<int>();

					//全ページのインデックスを出力
					int nPagesReferenceIndex = nObjIndex;
					{
						listPage.Add(nObjIndex + 1);				//1ページ目のインデックスを渡す
						listPage.Add(nObjIndex + 3);				//2ページ目のインデックスを渡す
						WritePages(bw, ref nObjIndex, listPage);
					}


					//1ページ出力
					{
						WritePageContentsIndex(bw, ref nObjIndex, nPagesReferenceIndex, nResourceIndex, nObjIndex + 1, 595, 842);

						//ページテキスト出力
						{
							List<PDFText> listTexts = new List<PDFText>();

							listTexts.Add(new PDFText("F0", 40, 50, 540, @"abcあいうえお漢字123"));
							listTexts.Add(new PDFText("F1", 40, 50, 590, @"abAAA23 timesItalic"));
							listTexts.Add(new PDFText("F2", 40, 50, 640, @"abAAA2てすと3 "));


							//コンテンツの書き出し
							using (MemoryStream ms = new MemoryStream())
							using (BinaryWriter bwms = new BinaryWriter(ms))
							{
								//文字データをPDF出力用に準備
								PrepareTextContents(ms, listTexts);

								ms.Flush();

								byte[] data = ms.ToArray();

								//ページコンテンツの出力
								WriteFlateData(bw, ref nObjIndex, data);
							}
						}
					}

					//2ページ出力
					{
						WritePageContentsIndex(bw, ref nObjIndex, nPagesReferenceIndex, nResourceIndex, nObjIndex + 1, 595, 842);

						//ページテキスト出力
						{
							List<PDFText> listTexts = new List<PDFText>();

							listTexts.Add(new PDFText("F0", 40, 50, 540, @"ぺーじ2.abcあいうえお3"));
							listTexts.Add(new PDFText("F1", 40, 50, 590, @"page2 abAAA23 timesItalic"));
							listTexts.Add(new PDFText("F2", 40, 50, 640, @"abAAA2てすと3 "));


							//コンテンツの書き出し
							using (MemoryStream ms = new MemoryStream())
							using (BinaryWriter bwms = new BinaryWriter(ms))
							{
								//文字データをPDF出力用に準備
								PrepareTextContents(ms, listTexts);

								ms.Flush();

								byte[] data = ms.ToArray();

								//ページコンテンツの出力
								WriteFlateData(bw, ref nObjIndex, data);
							}
						}
					}
				}

				//クロスリファレンス/トレーラー出力
				WriteXrefTrailer(bw, nRoot);
			}

			return true;
		}
		/// <summary>
		/// 欧文フォントの指定
		/// 
		/// デフォルトで用意されているフォントを利用する場合はこれで指定、
		/// 使えるフォント名(strFont)は↓
		/// Times-Roman
		/// Helvetica
		/// Courier
		/// Symbol
		/// Times-Bold
		/// Helvetica-Bold
		/// Courier-Bold
		/// ZapfDingbats
		/// Times-Italic
		/// Helvetica-Oblique
		/// Courier-Oblique
		/// Times-BoldItalic
		/// Helvetica-BoldOblique
		/// Courier-BoldOblique
		/// </summary>
		void WriteFont_Ascii(PDFRawWriter bw, ref int nObjIndex, string strFont, string strFontObjName)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				//bw.WriteLine("<</Font");
				//bw.WriteLine("<</" + strFontObjName);
					bw.WriteLine("<<");
						bw.WriteLine("/Type /Font");
						bw.WriteLine("/BaseFont /" + strFont);
						bw.WriteLine("/Subtype /Type1");
					bw.WriteLine(">>");
				//bw.WriteLine(">>");
				//bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;

			//フォント情報の保存
			_mapFontType.Add(strFontObjName, FONT_TYPE.ASCII);
		}



		/// <summary>
		/// 日本語フォントの指定(フォント埋め込みなし)
		/// 
		/// フォント名は↓
		/// https://www.adobe.com/jp/support/type/aj1-6.html
		/// 小塚明朝 Std Rは「KozMinStd-Regular」
		/// 小塚明朝 Pro Rは「KozMinPro-Regular」
		/// 小塚明朝 Pr6N Rは「KozMinPr6N-Regular」
		/// りょう Text PlusN Rは「RyoTextPlusN-Regular」
		/// </summary>
		void WriteFont_UnicodeJapanese(PDFRawWriter bw, ref int nObjIndex, string strFont, string strFontObjName)
		{
			_listnXref.Add(bw.BaseStream.Position);

			bw.WriteLine("" + nObjIndex + " 0 obj");
			//bw.WriteLine("<</Font");
			//bw.WriteLine("<</" + strFontObjName);
			bw.WriteLine("<<");
			bw.WriteLine("/Type /Font");
			bw.WriteLine("/BaseFont /" + strFont);
			bw.WriteLine("/Subtype /Type0");
			bw.WriteLine("/Encoding /UniJIS-UTF16-H");			//ユニコード(big endian)
			bw.WriteLine("/DescendantFonts [" + (nObjIndex + 1) + " 0 R]");
			bw.WriteLine(">>");
			//bw.WriteLine(">>");
			//bw.WriteLine(">>");
			bw.WriteLine("endobj");

			nObjIndex++;

			_listnXref.Add(bw.BaseStream.Position);

			bw.WriteLine("" + nObjIndex + " 0 obj");
			bw.WriteLine("<</Type /Font");
			bw.WriteLine("/Subtype /CIDFontType0");
			bw.WriteLine("/BaseFont /" + strFont);
			bw.WriteLine("/CIDSystemInfo <<");
			bw.WriteLine("/Registry (Adobe)");
			//bw.WriteLine("/Ordering (UCS)");
			bw.WriteLine("/Ordering (Japan1)");
			bw.WriteLine("/Supplement 6");
			bw.WriteLine(">>");
			bw.WriteLine("/FontDescriptor " + (nObjIndex + 1) + " 0 R");
			bw.WriteLine(">>");
			bw.WriteLine("endobj");

			nObjIndex++;

			_listnXref.Add(bw.BaseStream.Position);

			bw.WriteLine("" + nObjIndex + " 0 obj");
			bw.WriteLine("<<");
			bw.WriteLine("/Type /FontDescriptor");
			bw.WriteLine("/FontName /" + strFont);
			bw.WriteLine("/Flags 4");
			//bw.WriteLine("/FontBBox [-437 -340 1147 1317]");
			bw.WriteLine("/FontBBox [0 0 0 0]");			//↓この辺どう取得したらいいのか不明
			bw.WriteLine("/ItalicAngle 0");
			bw.WriteLine("/Ascent 1317");
			bw.WriteLine("/Descent -349");
			bw.WriteLine("/CapHeight 742");
			bw.WriteLine("/StemV 80");
			bw.WriteLine(">>");
			bw.WriteLine("endobj");

			nObjIndex++;


			//フォント情報の保存
			_mapFontType.Add(strFontObjName, FONT_TYPE.ADOBE_JPN1_6);
		}
		/// <summary>
		/// 与えられたテキストデータをストリームに以下の形式で書き込む
		/// "BT /F0 10 Tf 150 200 Td (hello) Tj ET\r";
		/// </summary>
		void PrepareTextContents(Stream strm, List<PDFText> listTexts)
		{
			using (MemoryStream ms = new MemoryStream())
			using (BinaryWriter bwms = new BinaryWriter(ms))
			{
				foreach (PDFText text in listTexts)
				{
					bool ret;
					FONT_TYPE type;

					ret = _mapFontType.TryGetValue(text.strFont, out type);
					if (ret == false)
					{
						//フォントの種類特定失敗
						Debug.Assert(false);
						continue;
					}

					IDictionary<ushort, byte[]> cmap = null;

					if (type == FONT_TYPE.EMBEDDED)
					{
						cmap = _cmapFonts[text.strFont];
						if (cmap == null)
						{
							//cmap取得失敗
							Debug.Assert(false);
							continue;
						}
					}


					string strText = text.strText;

					byte[] raw2 = null;

					{
						byte[] tmp = null;

						//フォントに応じてエンコーディング
						if (type == FONT_TYPE.ASCII)
							tmp = Encoding.ASCII.GetBytes(strText);
						else if (type == FONT_TYPE.ADOBE_JPN1_6)
							tmp = Encoding.BigEndianUnicode.GetBytes(strText);
						else if (type == FONT_TYPE.EMBEDDED)
							tmp = ConvertStringByCMap(strText, cmap);
						else
						{
							Debug.Assert(false);
						}

						// 「()\」をエスケープする
						using (MemoryStream ms_esc = new MemoryStream())
						{
							foreach (byte cb in tmp)
							{
								if (cb == 0x28		//'('
									|| cb == 0x29	//')'
									|| cb == 0x5c)	//'\'
								{
									ms_esc.WriteByte(0x5c);		//'\'
								}
								ms_esc.WriteByte(cb);
							}
							ms_esc.Flush();

							raw2 = ms_esc.ToArray();
						}
					}


					string strData = "BT /" + text.strFont + " " + text.fPoint + " Tf " + text.fX + " " + text.fY + " Td (";
					byte[] raw1 = Encoding.ASCII.GetBytes(strData);
					byte[] raw3 = Encoding.ASCII.GetBytes(") Tj ET");

					bwms.Write(raw1);
					bwms.Write(raw2);
					bwms.Write(raw3);
					bwms.Write('\r');
				}
				ms.Flush();

				byte[] data = ms.ToArray();
				strm.Write(data, 0, data.Length);
			}
		}

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


第11回 フォントファイルからCMAP変換表を取り出す

今回はopen type fontのフォントファイルから変換表を取り出し、利用する処理を実装します。

これまではttfdump.exeでcmap_msgothic.txtを手動作成していました。
この処理を自動化します。
取り出す変換表はplatformID == 3 && encodingID == 1のもののみに対応します。

open type fontの仕様を見ると、
https://www.microsoft.com/typography/otspec/otff.htm

ファイル先頭に4バイトのsfnt version、続いて2バイトのnumTables(テーブル数)、2バイトのsearchRange、2バイトのentrySelector、2バイトのrangeShiftが格納されており、

続いてnumTablesの分だけ「テーブル」が並びます。
1つのテーブルはtag、checkSum、offset、lengthがそれぞれ4バイト、合計16バイト分あり、

tagが"cmap"のテーブルの(ファイル先頭からの)offset位置に変換表が用意されています。


変換表の仕様を見ると、
https://www.microsoft.com/typography/otspec/cmap.htm

先頭から、2バイトのversion、2バイトのnumTables(テーブル数)があり、
続いてnumTablesの分だけ「テーブル」が並びます。
1つのテーブルは2バイトのplatformIDとencodingID、4バイトのoffsetの合計8バイト分あり、

(ファイル先頭ではなく"cmap"の先頭からの)offset位置に、platformIDとencodingIDの示す変換表が格納されています。
変換表の先頭には2バイトのformatがあり、このformatの値により変換表の格納形式が異なります。

今回利用する変換表はplatformIDが3、encodingIDが1なので、format=4(Format 4: Segment mapping to delta values)の形式で格納されています。

format 4の変換表の中には様々な情報が格納されていますが、その中で以下の3つの配列が必要になります。
・startCount[]
・endCount[]
・idDelta[]

例えばユニコードで0x5511を変換する場合には、
 startCount[n] <= 0x5511 <= endCount[n]
を満たす n の値を探し、以下のように変換します。
変換後の値=0x5511 + dDelta[n]

今回はユニコードで0x0000~0xFFFFまですべての文字についての変換表が欲しいので、
すべての値において上記の計算を行って変換表を作成しています。

■PDFTextWriter.cs
		public void Close()
		{
			_cmapFonts.Clear();
			_listnXref.Clear();
			_mapFontType.Clear();
		}
		/// <summary>
		/// フォントの埋め込み
		/// </summary>
		void WriteFont_EmbeddedUnicode(PDFRawWriter bw, ref int nObjIndex, string strFontObjName, string strFont, string strFontFamily, string strFontFile)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Font");
				bw.WriteLine("/BaseFont /" + strFont);
				bw.WriteLine("/Subtype /Type0");
				bw.WriteLine("/Encoding /Identity-H");			//PDF独自のエンコード
				bw.WriteLine("/DescendantFonts [" + (nObjIndex + 1) + " 0 R]");
				bw.WriteLine("/ToUnicode " + (nObjIndex + 4) + " 0 R");		//ToUnicode変換表
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;


			int nDescendantFontsObjIndex = nObjIndex;
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Font");
				bw.WriteLine("/Subtype /CIDFontType0");
				bw.WriteLine("/BaseFont /" + strFont);
				//bw.WriteLine("/CIDToGIDMap/Identity");
				bw.WriteLine("/CIDSystemInfo <<");
				bw.WriteLine("/Registry (Adobe)");
				bw.WriteLine("/Ordering (Identity)");		//Japan1にはしない
				bw.WriteLine("/Supplement 0");				//6にした方がいい?
				bw.WriteLine(">>");
				bw.WriteLine("/FontDescriptor " + (nObjIndex + 1) + " 0 R");
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;



			ushort nRangeMin = 0xFFFF;
			ushort nRangeMax = 0;



			//opentypeフォントファイルからcmapを読み込む
			IDictionary<ushort, byte[]> cmap = LoadCMap(strFontFile, out nRangeMin, out nRangeMax);
			_cmapFonts.Add(strFontObjName, cmap);


			////CMAPの準備
			////{
			//	string strFontCMapFile = @"cmap_msgothic.txt";

			//	//
			//	//CMAPの読み込み
			//	//
			//	//以下を実行してcmap.txtを取得、その中から「Char 30D6 -> Index 2121」というようなunicode用のcmapテーブルを抜き出してcmap_msgothic.txtに保存
			//	// ttfdump.exe HuiFont29.ttf -tcmap -nx >cmap.txt
			//	//
			//	// ttfdump.exeは以下からダウンロード(fonttools.exeに含まれる)
			//	// https://www.microsoft.com/typography/tools/tools.aspx
			//	// https://download.microsoft.com/download/f/f/a/ffae9ec6-3bf6-488a-843d-b96d552fd815/FontTools.exe
			//	//
			//	//
			//	//	//本当なら↓のコードで簡単にフォントからcmapを取得できるはずだけど、
			//	//	//きちんとした対応にならない???
			//	//	{
			//	//		//「PresentationCore」への参照追加
			//	//		GlyphTypeface gtf = new GlyphTypeface(new Uri(strFontFile));
			//	//		var cmap = gtf.CharacterToGlyphMap;
			//	//	}
			//	//

			//	IDictionary<ushort, byte[]> cmap = new Dictionary<ushort, byte[]>();
			//	_cmapFonts.Add(strFontObjName, cmap);

			//	using (FileStream fs = new FileStream(strFontCMapFile, FileMode.Open, FileAccess.Read))
			//	using (StreamReader sr = new StreamReader(fs))
			//	{
			//		string strCMap = sr.ReadToEnd();

			//		Regex re = new Regex(@"Char ([ABCDEFabcdef\d]+) -> Index (\d+)", RegexOptions.IgnoreCase);
			//		Match m = re.Match(strCMap);
			//		while (m.Success)
			//		{
			//			try
			//			{
			//				string strChar = m.Groups[1].Value;
			//				string strIndex = m.Groups[2].Value;

			//				ushort nChar = Convert.ToUInt16(strChar, 16);
			//				ushort nIndex = ushort.Parse(strIndex);

			//				//ビッグエンディアン変換
			//				byte tmp;
			//				byte[] bytes = BitConverter.GetBytes(nIndex);
			//				tmp = bytes[1];
			//				bytes[1] = bytes[0];
			//				bytes[0] = tmp;

			//				cmap.Add(nChar, bytes);

			//				//indexの最小値最大値を保存しておく
			//				if (nIndex < nRangeMin)
			//					nRangeMin = nIndex;
			//				if (nIndex > nRangeMax)
			//					nRangeMax = nIndex;
			//			}
			//			catch (Exception)
			//			{
			//			}

			//			m = m.NextMatch();
			//		}
			//	}
			////}



			int nFontDescriptorObjIndex = nObjIndex;
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /FontDescriptor");
				bw.WriteLine("/FontName /" + strFont);
				bw.WriteLine("/FontFamily(" + strFontFamily + ")");
				//bw.WriteLine(@"/Style<</Panose <0801020B0609070205080204> >>");		//The font family class and subclass ID bytes, given in the sFamilyClass field of the “OS/2” table in a TrueType font. This field is documented in Microsoft’s TrueType 1.0 Font Files Technical Specification

				//bw.WriteLine("/CIDSet 15 0 R");				//CID表
				bw.WriteLine("/FontFile2 " + (nObjIndex + 1) + " 0 R");
				bw.WriteLine("/Flags 6");									//Font uses the Adobe standard Latin character set or a subset of it
				bw.WriteLine("/FontBBox [0 0 0 0]");																		//だから0 0 0 0で自動にする
				//bw.WriteLine("/FontBBox [-437 -340 1147 1317]");															//指定例
				bw.WriteLine("/ItalicAngle 0");			//PostScriptHeaaderの値?面倒だからスルー
				//bw.WriteLine("/Lang/ja");				//日本語指定しておく?
				bw.WriteLine("/Ascent 1317");
				bw.WriteLine("/Descent -349");
				bw.WriteLine("/CapHeight 742");			//取得方法不明
				bw.WriteLine("/StemV 80");				//取得方法不明
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;




			int nFontFileObjIndex = nObjIndex;
			_listnXref.Add(bw.BaseStream.Position);
			{
				long nEncodedLength;
				long nDecodedLength;
				byte[] data;

				using (FileStream fs = new FileStream(strFontFile, FileMode.Open, FileAccess.Read))
				using (BinaryReader br = new BinaryReader(fs))
				{
					nDecodedLength = fs.Length;
					data = br.ReadBytes((int)nDecodedLength);
				}

				byte[] compress = CompressDeflate(data);

				nEncodedLength = compress.Length;

				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Filter /FlateDecode /Length " + nEncodedLength + " /Length1 " + nDecodedLength + ">>");
				bw.WriteLine("stream");
				{
					byte[] header = new byte[2];
					header[0] = 0x78;
					header[1] = 0x9c;
					bw.Write(header);
				}
				bw.Write(compress);
				bw.Write0x0a();
				bw.WriteLine("endstream");
				bw.WriteLine("endobj");
			}
			nObjIndex++;




			//ToUnicode変換表
			if (nRangeMin <= nRangeMax)
			{
				byte[] data;

				using (MemoryStream ms = new MemoryStream())
				using (StreamWriter bwms = new StreamWriter(ms, Encoding.ASCII))
				{
					//	/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo <<
					//	/Registry (TT1+0) /Ordering (T42UV) /Supplement 0 >> def
					//	/CMapName /TT1+0 def
					//	/CMapType 2 def
					//	1 begincodespacerange <0003> <0836> endcodespacerange		//<index>の最小最大値
					//	6 beginbfchar				//続く行数
					//	<0003> <0020>				//<index> <unicode>
					//	<001d> <003A>
					//	<0044> <0061>
					//	<0057> <0074>
					//	<005b> <0078>
					//	<0836> <3042>
					//	endbfchar
					//	1 beginbfrange				//続く行数
					//	<0010> <001a> <002D>		//いっぱいあるとき用。<0010> <001a> が<002D>に対応
					//	endbfrange
					//	endcmap CMapName currentdict /CMap defineresource pop end end

					bwms.Write("/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo <<\r");
					bwms.Write("/Registry (" + strFontObjName + "+0) /Ordering (T42UV) /Supplement 0 >> def\r");
					bwms.Write("/CMapName /" + strFontObjName + "+0 def\r");
					bwms.Write("/CMapType 2 def\r");
					bwms.Write("1 begincodespacerange <" + ConvertToHex_BE(nRangeMin) + "> <" + ConvertToHex_BE(nRangeMax) + "> endcodespacerange\r");

					bwms.Write("" + cmap.Count + " beginbfchar\r");
					foreach (KeyValuePair<ushort, byte[]> pair in cmap)
					{
						string value = String.Format("{0:X2}", pair.Value[0]) + String.Format("{0:X2}", pair.Value[1]);
						bwms.Write("<" + value + "> <" + ConvertToHex_BE(pair.Key) + ">\r");
					}
					bwms.Write("endbfchar\r");
					bwms.Write("endcmap CMapName currentdict /CMap defineresource pop end end\r");
					bwms.Flush();

					data = ms.ToArray();
				}

				if (data.Length > 0)
				{
					//17 0 obj
					//<</Filter/FlateDecode/Length 269>>stream
					_listnXref.Add(bw.BaseStream.Position);
					{
						long nEncodedLength;

						byte[] compress = CompressDeflate(data);

						nEncodedLength = compress.Length;

						bw.WriteLine("" + nObjIndex + " 0 obj");
						bw.WriteLine("<</Filter /FlateDecode /Length " + nEncodedLength + ">>");
						bw.WriteLine("stream");
						{
							byte[] header = new byte[2];
							header[0] = 0x78;
							header[1] = 0x9c;
							bw.Write(header);
						}
						bw.Write(compress);
						bw.Write0x0a();
						bw.WriteLine("endstream");
						bw.WriteLine("endobj");
					}
					nObjIndex++;
				}
			}

			//フォント情報の保存
			_mapFontType.Add(strFontObjName, FONT_TYPE.EMBEDDED);
		}


		string ConvertToHex_BE(ushort value)
		{
			byte[] bytes = BitConverter.GetBytes(value);

			return String.Format("{0:X2}", bytes[1]) + String.Format("{0:X2}", bytes[0]);
		}










		/// <summary>
		/// open type fontファイルからcmapを読み取る
		/// 
		/// open type fontの仕様通りにファイルを読むだけ
		/// マジックナンバーなどでファイルチェックをするべきだがしていない
		/// 
		/// 仕様
		/// https://www.microsoft.com/typography/otspec/otff.htm
		/// </summary>
		IDictionary<ushort, byte[]> LoadCMap(string strFontFile, out ushort nRangeMin, out ushort nRangeMax)//, out int nBBXMin, out int nBBXMax, out int nBBYMin, out int nBBYMax, out int nAscender, out int nDescender)
		{
			IDictionary<ushort, byte[]> cmap = new Dictionary<ushort, byte[]>();

			nRangeMin = 0xFFFF;
			nRangeMax = 0;

			int nBBXMin = 0;
			int nBBXMax = 0;
			int nBBYMin = 0;
			int nBBYMax = 0;

			int nAscender = 0;
			int nDescender = 0;

			using (FileStream fs = new FileStream(strFontFile, FileMode.Open, FileAccess.Read))
			using (BinaryReader br = new BinaryReader(fs))
			{
				// https://www.microsoft.com/typography/otspec/otff.htm
				byte[] sfntVer = br.ReadBytes(4);
				uint nTableCount = ByteToUInt_BE(br.ReadBytes(2));
				uint nSearchRange = ByteToUInt_BE(br.ReadBytes(2));
				uint nEntrySelector = ByteToUInt_BE(br.ReadBytes(2));
				uint nRangeShift = ByteToUInt_BE(br.ReadBytes(2));

				uint nCMapOffset = 0;
				uint nCMapLength = 0;

				uint nHeadOffset = 0;
				uint nHeadLength = 0;

				uint nHheaOffset = 0;
				uint nHheaLength = 0;

				uint nOS2Offset = 0;
				uint nOS2Length = 0;

				for (uint i = 0; i < nTableCount; i++)
				{
					byte[] tag = br.ReadBytes(4);
					uint checkSum = ByteToUInt_BE(br.ReadBytes(4));
					uint offset = ByteToUInt_BE(br.ReadBytes(4));		//	Offset from beginning of TrueType font file.
					uint length = ByteToUInt_BE(br.ReadBytes(4));

					string strTag = Encoding.ASCII.GetString(tag);
					if (strTag == "cmap")
					{
						nCMapOffset = offset;
						nCMapLength = length;
					}
					if (strTag == "head")
					{
						nHeadOffset = offset;
						nHeadLength = length;
					}
					if (strTag == "hhea")
					{
						nHheaOffset = offset;
						nHheaLength = length;
					}
					if (strTag == "OS/2")
					{
						nOS2Offset = offset;
						nOS2Length = length;
					}
				}


				if (nHheaOffset > 0 && nHheaLength > 0)
				{
					fs.Seek(nHheaOffset, SeekOrigin.Begin);

					// https://www.microsoft.com/typography/otspec/hhea.htm
					byte[] version = br.ReadBytes(4);
					nAscender = ByteToInt_BE(br.ReadBytes(2));
					nDescender = ByteToInt_BE(br.ReadBytes(2));
					int LineGap = ByteToInt_BE(br.ReadBytes(2));
					uint advanceWidthMax = ByteToUInt_BE(br.ReadBytes(2));
					int minLeftSideBearing = ByteToInt_BE(br.ReadBytes(2));
					int minRightSideBearing = ByteToInt_BE(br.ReadBytes(2));
					int xMaxExtent = ByteToInt_BE(br.ReadBytes(2));
					int caretSlopeRise = ByteToInt_BE(br.ReadBytes(2));
					int caretSlopeRun = ByteToInt_BE(br.ReadBytes(2));
					int caretOffset = ByteToInt_BE(br.ReadBytes(2));
					int reserved1 = ByteToInt_BE(br.ReadBytes(2));
					int reserved2 = ByteToInt_BE(br.ReadBytes(2));
					int reserved3 = ByteToInt_BE(br.ReadBytes(2));
					int reserved4 = ByteToInt_BE(br.ReadBytes(2));
					int metricDataFormat = ByteToInt_BE(br.ReadBytes(2));
					uint numberOfHMetrics = ByteToUInt_BE(br.ReadBytes(2));
				}


				if (nOS2Offset > 0 && nOS2Length > 0)
				{
					fs.Seek(nOS2Offset, SeekOrigin.Begin);

					// https://www.microsoft.com/typography/otspec/os2.htm
					uint version = ByteToUInt_BE(br.ReadBytes(2));
					int xAvgCharWidth = ByteToInt_BE(br.ReadBytes(2));
					uint usWeightClass = ByteToUInt_BE(br.ReadBytes(2));
					uint usWidthClass = ByteToUInt_BE(br.ReadBytes(2));
					uint fsType = ByteToUInt_BE(br.ReadBytes(2));
					int ySubscriptXSize = ByteToInt_BE(br.ReadBytes(2));
					int ySubscriptYSize = ByteToInt_BE(br.ReadBytes(2));
					int ySubscriptXOffset = ByteToInt_BE(br.ReadBytes(2));
					int ySubscriptYOffset = ByteToInt_BE(br.ReadBytes(2));
					int ySuperscriptXSize = ByteToInt_BE(br.ReadBytes(2));
					int ySuperscriptYSize = ByteToInt_BE(br.ReadBytes(2));
					int ySuperscriptXOffset = ByteToInt_BE(br.ReadBytes(2));
					int ySuperscriptYOffset = ByteToInt_BE(br.ReadBytes(2));
					int yStrikeoutSize = ByteToInt_BE(br.ReadBytes(2));
					int yStrikeoutPosition = ByteToInt_BE(br.ReadBytes(2));
					int sFamilyClass = ByteToInt_BE(br.ReadBytes(2));
					byte[] panose = br.ReadBytes(10);
					uint ulUnicodeRange1 = ByteToUInt_BE(br.ReadBytes(4));
					uint ulUnicodeRange2 = ByteToUInt_BE(br.ReadBytes(4));
					uint ulUnicodeRange3 = ByteToUInt_BE(br.ReadBytes(4));
					uint ulUnicodeRange4 = ByteToUInt_BE(br.ReadBytes(4));
					byte[] achVendID = br.ReadBytes(4);
					uint fsSelection = ByteToUInt_BE(br.ReadBytes(2));
					uint usFirstCharIndex = ByteToUInt_BE(br.ReadBytes(2));
					uint usLastCharIndex = ByteToUInt_BE(br.ReadBytes(2));
					int sTypoAscender = ByteToInt_BE(br.ReadBytes(2));
					int sTypoDescender = ByteToInt_BE(br.ReadBytes(2));
					int sTypoLineGap = ByteToInt_BE(br.ReadBytes(2));
					uint usWinAscent = ByteToUInt_BE(br.ReadBytes(2));
					uint usWinDescent = ByteToUInt_BE(br.ReadBytes(2));
					uint ulCodePageRange1 = ByteToUInt_BE(br.ReadBytes(4));
					uint ulCodePageRange2 = ByteToUInt_BE(br.ReadBytes(4));
					int sxHeight = ByteToInt_BE(br.ReadBytes(2));
					int sCapHeight = ByteToInt_BE(br.ReadBytes(2));
					uint usDefaultChar = ByteToUInt_BE(br.ReadBytes(2));
					uint usBreakChar = ByteToUInt_BE(br.ReadBytes(2));
					uint usMaxContext = ByteToUInt_BE(br.ReadBytes(2));
					uint usLowerOpticalPointSize = ByteToUInt_BE(br.ReadBytes(2));
					uint usUpperOpticalPointSize = ByteToUInt_BE(br.ReadBytes(2));
				}


				if (nHeadOffset > 0 && nHeadLength > 0)
				{
					fs.Seek(nHeadOffset, SeekOrigin.Begin);

					// https://www.microsoft.com/typography/otspec/head.htm
					byte[] version = br.ReadBytes(4);
					byte[] fontRevision = br.ReadBytes(4);
					uint checkSumAdjustment = ByteToUInt_BE(br.ReadBytes(4));
					uint magicNumber = ByteToUInt_BE(br.ReadBytes(4));
					uint flags = ByteToUInt_BE(br.ReadBytes(2));
					uint unitsPerEm = ByteToUInt_BE(br.ReadBytes(2));
					byte[] created = br.ReadBytes(8);
					byte[] modified = br.ReadBytes(8);

					nBBXMin = ByteToInt_BE(br.ReadBytes(2));
					nBBYMin = ByteToInt_BE(br.ReadBytes(2));
					nBBXMax = ByteToInt_BE(br.ReadBytes(2));
					nBBYMax = ByteToInt_BE(br.ReadBytes(2));

					uint macStyle = ByteToUInt_BE(br.ReadBytes(2));
					uint lowestRecPPEM = ByteToUInt_BE(br.ReadBytes(2));
					int fontDirectionHint = ByteToInt_BE(br.ReadBytes(2));
					int indexToLocFormat = ByteToInt_BE(br.ReadBytes(2));
					int glyphDataFormat = ByteToInt_BE(br.ReadBytes(2));
				}

				if (nCMapOffset > 0 && nCMapLength > 0)
				{
					fs.Seek(nCMapOffset, SeekOrigin.Begin);

					// https://www.microsoft.com/typography/otspec/cmap.htm
					uint version = ByteToUInt_BE(br.ReadBytes(2));
					uint numTables = ByteToUInt_BE(br.ReadBytes(2));

					uint nCMap31Offset = 0;

					for (uint i = 0; i < numTables; i++)
					{
						uint platformID = ByteToUInt_BE(br.ReadBytes(2));
						uint encodingID = ByteToUInt_BE(br.ReadBytes(2));
						uint offset = ByteToUInt_BE(br.ReadBytes(4));		//	Byte offset from beginning of table to the subtable for this encoding.

						if (platformID == 3 && encodingID == 1)		//ユニコードはWindows(3)の(1)
						{
							nCMap31Offset = offset;
							break;
						}
					}

					if (nCMap31Offset > 0)
					{
						fs.Seek(nCMapOffset, SeekOrigin.Begin);			//cmap先頭に移動してから
						fs.Seek(nCMap31Offset, SeekOrigin.Current);		//テーブルに移動

						//Format 4: Segment mapping to delta values		//16bitユニコードは4
						uint format = ByteToUInt_BE(br.ReadBytes(2));

						if (format == 4)		//16bitユニコードは4
						{
							uint length = ByteToUInt_BE(br.ReadBytes(2));
							uint language = ByteToUInt_BE(br.ReadBytes(2));

							uint segCountX2 = ByteToUInt_BE(br.ReadBytes(2));
							uint searchRange = ByteToUInt_BE(br.ReadBytes(2));
							uint entrySelector = ByteToUInt_BE(br.ReadBytes(2));
							uint rangeShift = ByteToUInt_BE(br.ReadBytes(2));

							uint[] endCount = new uint[segCountX2 / 2];
							for (uint i = 0; i < endCount.Length; i++)
							{
								endCount[i] = ByteToUInt_BE(br.ReadBytes(2));
							}

							uint reservedPad = ByteToUInt_BE(br.ReadBytes(2));

							uint[] startCount = new uint[segCountX2 / 2];
							for (uint i = 0; i < startCount.Length; i++)
							{
								startCount[i] = ByteToUInt_BE(br.ReadBytes(2));
							}

							int[] idDelta = new int[segCountX2 / 2];
							for (int i = 0; i < idDelta.Length; i++)
							{
								byte[] data = new byte[2];
								data[0] = br.ReadByte();
								data[1] = br.ReadByte();
								idDelta[i] = ByteToInt_BE(data);
							}

							uint[] idRangeOffset = new uint[segCountX2 / 2];
							for (uint i = 0; i < idRangeOffset.Length; i++)
							{
								idRangeOffset[i] = ByteToUInt_BE(br.ReadBytes(2));
							}


							for (uint i = 0; i < startCount.Length; i++)
							{
								for (uint charCode = startCount[i]; charCode <= endCount[i]; charCode++)
								{
									if (charCode == 0xFFFF)
										continue;

									int index = (int)((short)charCode + (short)idDelta[i]);
									if (index < 0)
										index = (index & 0xFFFF);			//uint16で無理やり処理

									//Console.WriteLine("	Char {0:X4} -> Index {1}", charCode, index);

									//ビッグエンディアン変換
									byte tmp;
									byte[] bytes = BitConverter.GetBytes((ushort)index);
									tmp = bytes[1];
									bytes[1] = bytes[0];
									bytes[0] = tmp;

									cmap.Add((ushort)charCode, bytes);

									//indexの最小値最大値を保存しておく
									if (index < nRangeMin)
										nRangeMin = (ushort)index;
									if (index > nRangeMax)
										nRangeMax = (ushort)index;
								}
							}



						}

					}
				}
			}
			return cmap;
		}




		int ByteToInt_BE(byte[] data)
		{
			if (data == null || data.Length == 0)
				return 0;

			if (data.Length == 2)
			{
				ushort ret = 0;
				foreach (byte cb in data)
				{
					ret <<= 8;
					ret += cb;
				}

				return (short)ret;
			}

			if (data.Length == 4)
			{
				uint ret = 0;
				foreach (byte cb in data)
				{
					ret <<= 8;
					ret += cb;
				}
				return (int)ret;
			}

			Debug.Assert(false);
			return (int)ByteToUInt_BE(data);
		}


		uint ByteToUInt_BE(byte[] data)
		{
			if (data == null || data.Length == 0)
				return 0;

			uint ret = 0;
			foreach (byte cb in data)
			{
				ret <<= 8;
				ret += cb;
			}
			return ret;
		}

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

第10回 PDF内の文字をコピペできるようにする

前回作成したPDFでは、文字を選択してクリップボードにコピー、そしてメモ帳にペーストしようとすると文字化けします。
これはユニコードへの「変換表」をPDF内に埋め込んでいないためです。

今回はこの変換表の埋め込み処理を追加します。
と言っても、オブジェクトを1つ用意するだけです。

■PDFTextWriter.cs
		/// <summary>
		/// フォントの埋め込み
		/// </summary>
		void WriteFont_EmbeddedUnicode(PDFRawWriter bw, ref int nObjIndex, string strFontObjName, string strFont, string strFontFamily, string strFontFile)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Font");
				bw.WriteLine("/BaseFont /" + strFont);
				bw.WriteLine("/Subtype /Type0");
				bw.WriteLine("/Encoding /Identity-H");			//PDF独自のエンコード
				bw.WriteLine("/DescendantFonts [" + (nObjIndex + 1) + " 0 R]");
				bw.WriteLine("/ToUnicode " + (nObjIndex + 4) + " 0 R");		//ToUnicode変換表
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;


			int nDescendantFontsObjIndex = nObjIndex;
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Font");
				bw.WriteLine("/Subtype /CIDFontType0");
				bw.WriteLine("/BaseFont /" + strFont);
				//bw.WriteLine("/CIDToGIDMap/Identity");
				bw.WriteLine("/CIDSystemInfo <<");
				bw.WriteLine("/Registry (Adobe)");
				bw.WriteLine("/Ordering (Identity)");		//Japan1にはしない
				bw.WriteLine("/Supplement 0");				//6にした方がいい?
				bw.WriteLine(">>");
				bw.WriteLine("/FontDescriptor " + (nObjIndex + 1) + " 0 R");
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;



			ushort nRangeMin = 0xFFFF;
			ushort nRangeMax = 0;



			//CMAPの準備
			//{
				string strFontCMapFile = @"cmap_msgothic.txt";

				//
				//CMAPの読み込み
				//
				//以下を実行してcmap.txtを取得、その中から「Char 30D6 -> Index 2121」というようなunicode用のcmapテーブルを抜き出してcmap_msgothic.txtに保存
				// ttfdump.exe HuiFont29.ttf -tcmap -nx >cmap.txt
				//
				// ttfdump.exeは以下からダウンロード(fonttools.exeに含まれる)
				// https://www.microsoft.com/typography/tools/tools.aspx
				// https://download.microsoft.com/download/f/f/a/ffae9ec6-3bf6-488a-843d-b96d552fd815/FontTools.exe
				//
				//
				//	//本当なら↓のコードで簡単にフォントからcmapを取得できるはずだけど、
				//	//きちんとした対応にならない???
				//	{
				//		//「PresentationCore」への参照追加
				//		GlyphTypeface gtf = new GlyphTypeface(new Uri(strFontFile));
				//		var cmap = gtf.CharacterToGlyphMap;
				//	}
				//

				IDictionary<ushort, byte[]> cmap = new Dictionary<ushort, byte[]>();
				_cmapFonts.Add(strFontObjName, cmap);

				using (FileStream fs = new FileStream(strFontCMapFile, FileMode.Open, FileAccess.Read))
				using (StreamReader sr = new StreamReader(fs))
				{
					string strCMap = sr.ReadToEnd();

					Regex re = new Regex(@"Char ([ABCDEFabcdef\d]+) -> Index (\d+)", RegexOptions.IgnoreCase);
					Match m = re.Match(strCMap);
					while (m.Success)
					{
						try
						{
							string strChar = m.Groups[1].Value;
							string strIndex = m.Groups[2].Value;

							ushort nChar = Convert.ToUInt16(strChar, 16);
							ushort nIndex = ushort.Parse(strIndex);

							//ビッグエンディアン変換
							byte tmp;
							byte[] bytes = BitConverter.GetBytes(nIndex);
							tmp = bytes[1];
							bytes[1] = bytes[0];
							bytes[0] = tmp;

							cmap.Add(nChar, bytes);

							//indexの最小値最大値を保存しておく
							if (nIndex < nRangeMin)
								nRangeMin = nIndex;
							if (nIndex > nRangeMax)
								nRangeMax = nIndex;
						}
						catch (Exception)
						{
						}

						m = m.NextMatch();
					}
				}
			//}



			int nFontDescriptorObjIndex = nObjIndex;
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /FontDescriptor");
				bw.WriteLine("/FontName /" + strFont);
				bw.WriteLine("/FontFamily(" + strFontFamily + ")");
				//bw.WriteLine(@"/Style<</Panose <0801020B0609070205080204> >>");		//The font family class and subclass ID bytes, given in the sFamilyClass field of the “OS/2” table in a TrueType font. This field is documented in Microsoft’s TrueType 1.0 Font Files Technical Specification

				//bw.WriteLine("/CIDSet 15 0 R");				//CID表
				bw.WriteLine("/FontFile2 " + (nObjIndex + 1) + " 0 R");
				bw.WriteLine("/Flags 6");									//Font uses the Adobe standard Latin character set or a subset of it
				bw.WriteLine("/FontBBox [0 0 0 0]");																		//だから0 0 0 0で自動にする
				//bw.WriteLine("/FontBBox [-437 -340 1147 1317]");															//指定例
				bw.WriteLine("/ItalicAngle 0");			//PostScriptHeaaderの値?面倒だからスルー
				//bw.WriteLine("/Lang/ja");				//日本語指定しておく?
				bw.WriteLine("/Ascent 1317");
				bw.WriteLine("/Descent -349");
				bw.WriteLine("/CapHeight 742");			//取得方法不明
				bw.WriteLine("/StemV 80");				//取得方法不明
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;




			int nFontFileObjIndex = nObjIndex;
			_listnXref.Add(bw.BaseStream.Position);
			{
				long nEncodedLength;
				long nDecodedLength;
				byte[] data;

				using (FileStream fs = new FileStream(strFontFile, FileMode.Open, FileAccess.Read))
				using (BinaryReader br = new BinaryReader(fs))
				{
					nDecodedLength = fs.Length;
					data = br.ReadBytes((int)nDecodedLength);
				}

				byte[] compress = CompressDeflate(data);

				nEncodedLength = compress.Length;

				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Filter /FlateDecode /Length " + nEncodedLength + " /Length1 " + nDecodedLength + ">>");
				bw.WriteLine("stream");
				{
					byte[] header = new byte[2];
					header[0] = 0x78;
					header[1] = 0x9c;
					bw.Write(header);
				}
				bw.Write(compress);
				bw.Write0x0a();
				bw.WriteLine("endstream");
				bw.WriteLine("endobj");
			}
			nObjIndex++;




			//ToUnicode変換表
			if (nRangeMin <= nRangeMax)
			{
				byte[] data;

				using (MemoryStream ms = new MemoryStream())
				using (StreamWriter bwms = new StreamWriter(ms, Encoding.ASCII))
				{
					//	/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo <<
					//	/Registry (TT1+0) /Ordering (T42UV) /Supplement 0 >> def
					//	/CMapName /TT1+0 def
					//	/CMapType 2 def
					//	1 begincodespacerange <0003> <0836> endcodespacerange		//<index>の最小最大値
					//	6 beginbfchar				//続く行数
					//	<0003> <0020>				//<index> <unicode>
					//	<001d> <003A>
					//	<0044> <0061>
					//	<0057> <0074>
					//	<005b> <0078>
					//	<0836> <3042>
					//	endbfchar
					//	1 beginbfrange				//続く行数
					//	<0010> <001a> <002D>		//いっぱいあるとき用。<0010> <001a> が<002D>に対応
					//	endbfrange
					//	endcmap CMapName currentdict /CMap defineresource pop end end

					bwms.Write("/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo <<\r");
					bwms.Write("/Registry (" + strFontObjName + "+0) /Ordering (T42UV) /Supplement 0 >> def\r");
					bwms.Write("/CMapName /" + strFontObjName + "+0 def\r");
					bwms.Write("/CMapType 2 def\r");
					bwms.Write("1 begincodespacerange <" + ConvertToHex_BE(nRangeMin) + "> <" + ConvertToHex_BE(nRangeMax) + "> endcodespacerange\r");

					bwms.Write("" + cmap.Count + " beginbfchar\r");
					foreach (KeyValuePair<ushort, byte[]> pair in cmap)
					{
						string value = String.Format("{0:X2}", pair.Value[0]) + String.Format("{0:X2}", pair.Value[1]);
						bwms.Write("<" + value + "> <" + ConvertToHex_BE(pair.Key) + ">\r");
					}
					bwms.Write("endbfchar\r");
					bwms.Write("endcmap CMapName currentdict /CMap defineresource pop end end\r");
					bwms.Flush();

					data = ms.ToArray();
				}

				if (data.Length > 0)
				{
					//17 0 obj
					//<</Filter/FlateDecode/Length 269>>stream
					_listnXref.Add(bw.BaseStream.Position);
					{
						long nEncodedLength;

						byte[] compress = CompressDeflate(data);

						nEncodedLength = compress.Length;

						bw.WriteLine("" + nObjIndex + " 0 obj");
						bw.WriteLine("<</Filter /FlateDecode /Length " + nEncodedLength + ">>");
						bw.WriteLine("stream");
						{
							byte[] header = new byte[2];
							header[0] = 0x78;
							header[1] = 0x9c;
							bw.Write(header);
						}
						bw.Write(compress);
						bw.Write0x0a();
						bw.WriteLine("endstream");
						bw.WriteLine("endobj");
					}
					nObjIndex++;
				}
			}

			//フォント情報の保存
			_mapFontType.Add(strFontObjName, FONT_TYPE.EMBEDDED);
		}


		string ConvertToHex_BE(ushort value)
		{
			byte[] bytes = BitConverter.GetBytes(value);

			return String.Format("{0:X2}", bytes[1]) + String.Format("{0:X2}", bytes[0]);
		}

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

第09回 PDFファイルにフォントを埋め込む

今回は前回取得したopen type fontに関する情報を利用してPDFファイルにフォントを埋め込みます。

まず、前回の方法で変換表だけを抜き出したテキストファイル「cmap_msgothic.txt」を作成します。
Windows7に含まれていたMSゴシックでは1万5747行になりました。

■cmap_msgothic.txt
		   1. Char 0000 -> Index 1
		   2. Char 000D -> Index 2
		   3. Char 0020 -> Index 3
		      Char 0021 -> Index 4
		      Char 0022 -> Index 5
		      Char 0023 -> Index 6
		      Char 0024 -> Index 7
		      Char 0025 -> Index 8
		      Char 0026 -> Index 9
		      Char 0027 -> Index 10
		      Char 0028 -> Index 11
		      Char 0029 -> Index 12
		      Char 002A -> Index 13

		      Char FFE6 -> Index 15740
		4357. Char FFE8 -> Index 15741
		      Char FFE9 -> Index 15742
		      Char FFEA -> Index 15743
		      Char FFEB -> Index 15744
		      Char FFEC -> Index 15745
		      Char FFED -> Index 15746
		      Char FFEE -> Index 15747

作成したcmap_msgothic.txtと、フォントファイルであるmsgothic.otfの2ファイルを、プロジェクトの実行フォルダ(debugフォルダ)へコピーしておきます。


そしてフォント埋め込みのコード作成。

本来であれば、PDF内で使われている文字分だけのフォントを埋め込むべきですが、
それをするのが面倒なため、msgothic.otfを丸ごとオブジェクトとして埋め込みました。
そして表示する文章はcmap_msgothic.txtを参照して、ユニコードからインデックス値に変換して書き出しています。

これでフォントを埋め込んだPDFが作成できました。
PDF内で文字を選択してクリップボードにコピー、そしてメモ帳にペーストしようとすると文字化けします。
これはインデックス値からユニコードへと変換する表を埋め込んでいないためです。これは次回以降へ持ち越し。

また、今は変換表をcmap_msgothic.txtという形で手動で用意しています。
これをフォントファイルから直接読み取る処理も次回以降です。

■PdfTextWriter.cs
using System;									//追加
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.RegularExpressions;			//追加

namespace Pdf2Pdf
{
	class PDFTextWriter
	{
		enum FONT_TYPE
		{
			ASCII,
			ADOBE_JPN1_6,
			EMBEDDED
		}



		//クロスリファレンス生成用データ(各オブジェクトの位置を保存)
		List<long> _listnXref = new List<long>();

		//フォントの種類保存用
		IDictionary<string, FONT_TYPE> _mapFontType = new Dictionary<string, FONT_TYPE>();



		public void Close()
		{
			_listnXref.Clear();
			_mapFontType.Clear();
		}


		public bool CreatePDFFile(string strFile)
		{
			Close();

			int nObjIndex = 1;

			using (FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write))
			using (PDFRawWriter bw = new PDFRawWriter(fs))
			{
				//ヘッダー出力
				bw.WriteLine("%PDF-1.7");

				//フォント出力
				int nResourceIndex;
				{
					nResourceIndex = nObjIndex;

					//WriteFont_Ascii(bw, ref nObjIndex, "Times-Italic", "F0");						//欧文フォント指定
					//WriteFont_UnicodeJapanese(bw, ref nObjIndex, "KozMinPr6N-Regular", "F0");		//日本語フォント指定(フォント埋め込みなし)


					//フォント埋め込み
					{
						List<KeyValuePair<string, int>> listFonts = new List<KeyValuePair<string, int>>();

						{
							string strFontObjName = "F0";
							listFonts.Add(new KeyValuePair<string, int>(strFontObjName, nObjIndex));
							WriteFont_EmbeddedUnicode(bw, ref nObjIndex, "F0", "MS-Gothic", "MS Gothic", @"msgothic.otf");
						}

						//埋め込みフォント一覧のみのリソース
						nResourceIndex = nObjIndex;
						_listnXref.Add(bw.BaseStream.Position);
						{
							bw.WriteLine("" + nObjIndex + " 0 obj");
							bw.WriteLine("<</Font");
							bw.WriteLine("<<");
							foreach (KeyValuePair<string, int> pair in listFonts)
							{
								bw.WriteLine("/" + pair.Key + " " + pair.Value + " 0 R");
							}
							bw.WriteLine(">>");
							bw.WriteLine(">>");
							bw.WriteLine("endobj");
						}
						nObjIndex++;
					}
				}

				//カタログ出力
				int nRoot = nObjIndex;
				{
					WriteCatalog(bw, ref nObjIndex, nObjIndex + 1);
				}

				//ページ出力
				{
					List<int> listPage = new List<int>();

					//全ページのインデックスを出力
					int nPagesReferenceIndex = nObjIndex;
					{
						listPage.Add(nObjIndex + 1);				//1ページ目のインデックスを渡す
						WritePages(bw, ref nObjIndex, listPage);
					}


					//1ページ出力
					{
						WritePageContentsIndex(bw, ref nObjIndex, nPagesReferenceIndex, nResourceIndex, nObjIndex + 1, 595, 842);

						//ページテキスト出力
						{
							List<PDFText> listTexts = new List<PDFText>();

							listTexts.Add(new PDFText("F0", 40, 50, 540, @"abcあいうえお漢字123"));


							//コンテンツの書き出し
							using (MemoryStream ms = new MemoryStream())
							using (BinaryWriter bwms = new BinaryWriter(ms))
							{
								//文字データをPDF出力用に準備
								PrepareTextContents(ms, listTexts);

								ms.Flush();

								byte[] data = ms.ToArray();

								//ページコンテンツの出力
								WriteFlateData(bw, ref nObjIndex, data);
							}
						}
					}
				}

				//クロスリファレンス/トレーラー出力
				WriteXrefTrailer(bw, nRoot);
			}

			return true;
		}

		//フォントごとのcmap変換表を保管
		IDictionary<string, IDictionary<ushort, byte[]>> _cmapFonts = new Dictionary<string, IDictionary<ushort, byte[]>>();



		/// <summary>
		/// フォントの埋め込み
		/// </summary>
		void WriteFont_EmbeddedUnicode(PDFRawWriter bw, ref int nObjIndex, string strFontObjName, string strFont, string strFontFamily, string strFontFile)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Font");
				bw.WriteLine("/BaseFont /" + strFont);
				bw.WriteLine("/Subtype /Type0");
				bw.WriteLine("/Encoding /Identity-H");			//PDF独自のエンコード
				bw.WriteLine("/DescendantFonts [" + (nObjIndex + 1) + " 0 R]");
				//bw.WriteLine("/ToUnicode " + (nObjIndex + 4) + " 0 R");		//ToUnicode変換表
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;


			int nDescendantFontsObjIndex = nObjIndex;
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Font");
				bw.WriteLine("/Subtype /CIDFontType0");
				bw.WriteLine("/BaseFont /" + strFont);
				//bw.WriteLine("/CIDToGIDMap/Identity");
				bw.WriteLine("/CIDSystemInfo <<");
				bw.WriteLine("/Registry (Adobe)");
				bw.WriteLine("/Ordering (Identity)");		//Japan1にはしない
				bw.WriteLine("/Supplement 0");				//6にした方がいい?
				bw.WriteLine(">>");
				bw.WriteLine("/FontDescriptor " + (nObjIndex + 1) + " 0 R");
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;



			ushort nRangeMin = 0xFFFF;
			ushort nRangeMax = 0;



			//CMAPの準備
			{
				string strFontCMapFile = @"cmap_msgothic.txt";

				//
				//CMAPの読み込み
				//
				//以下を実行してcmap.txtを取得、その中から「Char 30D6 -> Index 2121」というようなunicode用のcmapテーブルを抜き出してcmap_msgothic.txtに保存
				// ttfdump.exe HuiFont29.ttf -tcmap -nx >cmap.txt
				//
				// ttfdump.exeは以下からダウンロード(fonttools.exeに含まれる)
				// https://www.microsoft.com/typography/tools/tools.aspx
				// https://download.microsoft.com/download/f/f/a/ffae9ec6-3bf6-488a-843d-b96d552fd815/FontTools.exe
				//
				//
				//	//本当なら↓のコードで簡単にフォントからcmapを取得できるはずだけど、
				//	//きちんとした対応にならない???
				//	{
				//		//「PresentationCore」への参照追加
				//		GlyphTypeface gtf = new GlyphTypeface(new Uri(strFontFile));
				//		var cmap = gtf.CharacterToGlyphMap;
				//	}
				//

				IDictionary<ushort, byte[]> cmap = new Dictionary<ushort, byte[]>();
				_cmapFonts.Add(strFontObjName, cmap);

				using (FileStream fs = new FileStream(strFontCMapFile, FileMode.Open, FileAccess.Read))
				using (StreamReader sr = new StreamReader(fs))
				{
					string strCMap = sr.ReadToEnd();

					Regex re = new Regex(@"Char ([ABCDEFabcdef\d]+) -> Index (\d+)", RegexOptions.IgnoreCase);
					Match m = re.Match(strCMap);
					while (m.Success)
					{
						try
						{
							string strChar = m.Groups[1].Value;
							string strIndex = m.Groups[2].Value;

							ushort nChar = Convert.ToUInt16(strChar, 16);
							ushort nIndex = ushort.Parse(strIndex);

							//ビッグエンディアン変換
							byte tmp;
							byte[] bytes = BitConverter.GetBytes(nIndex);
							tmp = bytes[1];
							bytes[1] = bytes[0];
							bytes[0] = tmp;

							cmap.Add(nChar, bytes);

							//indexの最小値最大値を保存しておく
							if (nIndex < nRangeMin)
								nRangeMin = nIndex;
							if (nIndex > nRangeMax)
								nRangeMax = nIndex;
						}
						catch (Exception)
						{
						}

						m = m.NextMatch();
					}
				}
			}



			int nFontDescriptorObjIndex = nObjIndex;
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /FontDescriptor");
				bw.WriteLine("/FontName /" + strFont);
				bw.WriteLine("/FontFamily(" + strFontFamily + ")");
				//bw.WriteLine(@"/Style<</Panose <0801020B0609070205080204> >>");		//The font family class and subclass ID bytes, given in the sFamilyClass field of the “OS/2” table in a TrueType font. This field is documented in Microsoft’s TrueType 1.0 Font Files Technical Specification

				//bw.WriteLine("/CIDSet 15 0 R");				//CID表
				bw.WriteLine("/FontFile2 " + (nObjIndex + 1) + " 0 R");
				bw.WriteLine("/Flags 6");									//Font uses the Adobe standard Latin character set or a subset of it
				bw.WriteLine("/FontBBox [0 0 0 0]");																		//だから0 0 0 0で自動にする
				//bw.WriteLine("/FontBBox [-437 -340 1147 1317]");															//指定例
				bw.WriteLine("/ItalicAngle 0");			//PostScriptHeaaderの値?面倒だからスルー
				//bw.WriteLine("/Lang/ja");				//日本語指定しておく?
				bw.WriteLine("/Ascent 1317");
				bw.WriteLine("/Descent -349");
				bw.WriteLine("/CapHeight 742");			//取得方法不明
				bw.WriteLine("/StemV 80");				//取得方法不明
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;




			int nFontFileObjIndex = nObjIndex;
			_listnXref.Add(bw.BaseStream.Position);
			{
				long nEncodedLength;
				long nDecodedLength;
				byte[] data;

				using (FileStream fs = new FileStream(strFontFile, FileMode.Open, FileAccess.Read))
				using (BinaryReader br = new BinaryReader(fs))
				{
					nDecodedLength = fs.Length;
					data = br.ReadBytes((int)nDecodedLength);
				}

				byte[] compress = CompressDeflate(data);

				nEncodedLength = compress.Length;

				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Filter /FlateDecode /Length " + nEncodedLength + " /Length1 " + nDecodedLength + ">>");
				bw.WriteLine("stream");
				{
					byte[] header = new byte[2];
					header[0] = 0x78;
					header[1] = 0x9c;
					bw.Write(header);
				}
				bw.Write(compress);
				bw.Write0x0a();
				bw.WriteLine("endstream");
				bw.WriteLine("endobj");
			}
			nObjIndex++;


			//フォント情報の保存
			_mapFontType.Add(strFontObjName, FONT_TYPE.EMBEDDED);
		}








		void WritePageContentsIndex(PDFRawWriter bw, ref int nObjIndex, int nParentObjIndex, int nResourcesObjIndex, int nContentsObjIndex, float fWidth, float fHeight)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Page");
				bw.WriteLine("/Parent " + nParentObjIndex + " 0 R");
				bw.WriteLine("/Resources " + nResourcesObjIndex + " 0 R");
				bw.WriteLine("/MediaBox [0 0 " + fWidth + " " + fHeight + "]");
				bw.WriteLine("/Contents " + nContentsObjIndex + " 0 R");
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;
		}




		/// <summary>
		/// 与えられたテキストデータをストリームに以下の形式で書き込む
		/// "BT /F0 10 Tf 150 200 Td (hello) Tj ET\r";
		/// </summary>
		void PrepareTextContents(Stream strm, List<PDFText> listTexts)
		{
			using (MemoryStream ms = new MemoryStream())
			using (BinaryWriter bwms = new BinaryWriter(ms))
			{
				foreach (PDFText text in listTexts)
				{
					bool ret;
					FONT_TYPE type;

					ret = _mapFontType.TryGetValue(text.strFont, out type);
					if (ret == false)
					{
						//フォントの種類特定失敗
						Debug.Assert(false);
						continue;
					}

					IDictionary<ushort, byte[]> cmap = _cmapFonts[text.strFont];
					if (cmap == null)
					{
						//cmap取得失敗
						Debug.Assert(false);
						continue;
					}


					string strText = text.strText;

					byte[] raw2 = null;

					{
						byte[] tmp = null;

						//フォントに応じてエンコーディング
						if (type == FONT_TYPE.ASCII)
							tmp = Encoding.ASCII.GetBytes(strText);
						if (type == FONT_TYPE.ADOBE_JPN1_6)
							tmp = Encoding.BigEndianUnicode.GetBytes(strText);
						else if (type == FONT_TYPE.EMBEDDED)
							tmp = ConvertStringByCMap(strText, cmap);
						else
						{
							Debug.Assert(false);
						}

						// 「()\」をエスケープする
						using (MemoryStream ms_esc = new MemoryStream())
						{
							foreach (byte cb in tmp)
							{
								if (cb == 0x28		//'('
									|| cb == 0x29	//')'
									|| cb == 0x5c)	//'\'
								{
									ms_esc.WriteByte(0x5c);		//'\'
								}
								ms_esc.WriteByte(cb);
							}
							ms_esc.Flush();

							raw2 = ms_esc.ToArray();
						}
					}


					string strData = "BT /" + text.strFont + " " + text.fPoint + " Tf " + text.fX + " " + text.fY + " Td (";
					byte[] raw1 = Encoding.ASCII.GetBytes(strData);
					byte[] raw3 = Encoding.ASCII.GetBytes(") Tj ET");

					bwms.Write(raw1);
					bwms.Write(raw2);
					bwms.Write(raw3);
					bwms.Write('\r');
				}
				ms.Flush();

				byte[] data = ms.ToArray();
				strm.Write(data, 0, data.Length);
			}
		}



		/// <summary>
		/// 文字列をcmapにもとづいて変換する
		/// </summary>
		byte[] ConvertStringByCMap(string strText, IDictionary<ushort, byte[]> cmap)
		{
			byte[] data;

			using (MemoryStream ms = new MemoryStream())
			using (BinaryWriter bw = new BinaryWriter(ms))
			{
				foreach (ushort c in strText)
				{
					bool bFind = false;

					byte[] value;
					bFind = cmap.TryGetValue(c, out value);
					if (bFind)
						bw.Write(value);

					//文字が見つからなかったら「.」を代わりに出力
					if (bFind == false)
					{
						bFind = cmap.TryGetValue('.', out value);
						if (bFind)
							bw.Write(value);
					}
				}
				bw.Flush();

				return ms.ToArray();
			}
		}


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

第08回 PDF埋め込みフォントの概要

今回はPDFへのフォント埋め込みの概要~というかフォントについてです。

フォントファイルはいわゆるtrue type fontと、open type fontがあります。
true type fontは少し複雑なので、ここではopen type fontのみを扱うことにします。



フォントファイルというのは文字の「形」を収録したファイルです。
フォントファイルの中には複数の文字の「形」が収録されています。
あまりに当たり前な話ですが、これが埋め込みに際して重要になります。


「A」という文字は1番目の位置に収録されている
「B」という文字は2番目の位置に収録されている
「C」という文字は3番目の位置に収録されている
 ・
 ・
 ・
「を」という文字は999番目の位置に収録されている
「ん」という文字は1000番目の位置に収録されている

フォントを埋め込む際には、
このような"文字"とそれが何番目に収録されているかという対応表が必要になり、

埋め込むテキストはユニコードやshift-jisといった一般的な形式でPDF内に出力するのではなく、
この対応表に基づいた変換結果を入れる必要があります。
(例えば「ABC」という文字列を書き込む場合は「0x0001 0x0002 0x0003」という変換結果のバイナリを書き込みます)




実際に「対応表」を見てみることにします。

まずはフォントファイルの準備。
"C:Windows\Fonts\"フォルダーの中にある「MS ゴシック 標準」(ファイル名:msgothic.ttc)を適当なフォルダにコピーします。

このファイルはtrue type fontのため、open type fontに変換します。
オンラインで変換してくれるこのサイトで、output formatを「otf - OpenType font」として変換します。
https://www.fontconverter.org/
そして変換した結果できたopen type fontファイル「msgothic.otf」をダウンロード/保存します。

次に対応表を見るためのツールをダウンロード。
Microsoftが用意しているttfdumpというツールを利用します。
以下にある「fonttools.exe」をダウンロードし、この中にある「TTFDump.zip」を解凍すると「ttfdump.exe」があるので保存します。
https://www.microsoft.com/en-us/typography/tools.aspx
https://download.microsoft.com/download/f/f/a/ffae9ec6-3bf6-488a-843d-b96d552fd815/FontTools.exe

ついでにopen type fontの情報を見るためのツールもダウンロード。
以下にある「lcdf-typetools-w32」をダウンロードし、「otfinfo.exe」を解凍/保存します。
https://www.lcdf.org/type/index.html
ftp://akagi.ms.u-tokyo.ac.jp/pub/TeX/win32/lcdf-typetools-w32.tar.xz

これらの作業で集まった以下のファイルを同じフォルダに入れます。
・msgothic.otf
・ttfdump.exe
・otfinfo.exe

そして以下のようにしたbatファイルを実行。

otfinfo -i msgothic.otf > otf_info.txt
ttfdump.exe msgothic.otf -tcmap -nx  > otf_cmap.txt
pause


するとファイルが出力されます。
otf_info.txt を見ると、フォントの名前情報が。
otf_cmap.txt には変換表があります。
どちらもPDF埋め込みの際に必要になる情報です。

ユニコード以外からもフォントを扱えるように、変換表は複数入っているのが普通です。
この中から、Platform ID == 3、Specific ID == 1のものを抜き出します。

■otf_info.txt
Family:              MS Gothic				//フォントファミリー名
Subfamily:           Regular
Full name:           MS Gothic
PostScript name:     MS-Gothic				//フォント名
Version:             Version 5.01
Unique ID:           Microsoft:MS Gothic:2009
Trademark:           MS Gothic is a registered trademark of the Microsoft Corporation.
Copyright:           (C)2009 data:RICOH Co.,Ltd. typeface:RYOBI IMAGIX CO.
Vendor ID:           RICO
■otf_cmap.txt
		     Char 253 -> Index 451
		     Char 254 -> Index 449
		     Char 255 -> Index 440
  
Subtable  4.   Platform ID:   3				//Platform ID == 3 はWindows、Specific ID == 1 はユニコードを示す
               Specific ID:   1				//つまりこのセクションにあるのが対応表
               'cmap' Offset: 0x0000002C
	      ->Format:	4 : Segment mapping to delta values
		Length:		34880
		Version:	0
		segCount:	4358  (X2 = 8716)
		searchRange:	8192
		entrySelector:	12
		rangeShift:	524
		Seg   1 : St = 0000, En = 0000, D =      1, RO =     0, gId# = N/A
		Seg   2 : St = 000D, En = 000D, D =    -11, RO =     0, gId# = N/A
		Seg   3 : St = 0020, En = 007E, D =    -29, RO =     0, gId# = N/A
		Seg   4 : St = 00A0, En = 017F, D =    -62, RO =     0, gId# = N/A
		Seg   5 : St = 0192, En = 0193, D =    -80, RO =     0, gId# = N/A

		Seg 4353 : St = FDFC, En = FDFC, D =  16088, RO =     0, gId# = N/A
		Seg 4354 : St = FE45, En = FE46, D =  16016, RO =     0, gId# = N/A
		Seg 4355 : St = FF01, En = FF9F, D =  15830, RO =     0, gId# = N/A
		Seg 4356 : St = FFE0, En = FFE6, D =  15766, RO =     0, gId# = N/A
		Seg 4357 : St = FFE8, En = FFEE, D =  15765, RO =     0, gId# = N/A
		Seg 4358 : St = FFFF, En = FFFF, D =      1, RO =     0, gId# = N/A

		Which Means:
		   1. Char 0000 -> Index 1		//対応表開始
		   2. Char 000D -> Index 2		//ユニコードで0x000Dの文字は、2番目にあるという意味
		   3. Char 0020 -> Index 3		//ユニコードで0x0020の文字は、3番目にあるという意味
		      Char 0021 -> Index 4		//ユニコードで0x0021の文字は、4番目にあるという意味
		      Char 0022 -> Index 5
		      Char 0023 -> Index 6
		      Char 0024 -> Index 7
		      Char 0025 -> Index 8
		      Char 0026 -> Index 9
		      Char 0027 -> Index 10
		      Char 0028 -> Index 11
		      Char 0029 -> Index 12
		      Char 002A -> Index 13
		      Char 002B -> Index 14
		      Char 002C -> Index 15
		      Char 002D -> Index 16
		      Char 002E -> Index 17

		4356. Char FFE0 -> Index 15734
		      Char FFE1 -> Index 15735
		      Char FFE2 -> Index 15736
		      Char FFE3 -> Index 15737
		      Char FFE4 -> Index 15738
		      Char FFE5 -> Index 15739
		      Char FFE6 -> Index 15740
		4357. Char FFE8 -> Index 15741
		      Char FFE9 -> Index 15742
		      Char FFEA -> Index 15743
		      Char FFEB -> Index 15744
		      Char FFEC -> Index 15745
		      Char FFED -> Index 15746
		      Char FFEE -> Index 15747		//対応表終了
  
Subtable  5.   Platform ID:   3
               Specific ID:   10
               'cmap' Offset: 0x0000886C
	      ->Format:	12 : Segmented coverage (32 bit)
		Length:		55732
		Version:	0
		Seg   1 : startCharCode = 00000000, endCharCode = 00000000, startGlyphCode = 1
		Seg   2 : startCharCode = 0000000D, endCharCode = 0000000D, startGlyphCode = 2
		Seg   3 : startCharCode = 00000020, endCharCode = 0000007E, startGlyphCode = 3

ここまで情報が揃ったらフォントの埋め込み処理はできたも同然です。

第07回 PDFに日本語を書き出す

今回は書き出すPDFのフォントに日本語を指定します。

shift-jis指定での書き込みもできるのですが、shift-jisを使うのも今更なのでユニコード(ビッグエンディアン)にしました。
文字列をユニコードで書き込むので日本語も何も必要ないのでは?
とも思うのですが日本語限定です。

フォント埋め込みは次回以降です。

■PDFTextWriter.cs
	class PDFTextWriter
	{
		enum FONT_TYPE
		{
			ASCII,
			ADOBE_JPN1_6,
		}


		//クロスリファレンス生成用データ(各オブジェクトの位置を保存)
		List<long> _listnXref = new List<long>();

		//フォントの種類保存用
		IDictionary<string, FONT_TYPE> _mapFontType = new Dictionary<string, FONT_TYPE>();


		public void Close()
		{
			_listnXref.Clear();
			_mapFontType.Clear();
		}


		public bool CreatePDFFile(string strFile)
		{
			Close();

			int nObjIndex = 1;

			using (FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write))
			using (PDFRawWriter bw = new PDFRawWriter(fs))
			{
				//ヘッダー出力
				bw.WriteLine("%PDF-1.7");

				//フォント出力
				int nResourceIndex;
				{
					nResourceIndex = nObjIndex;

					//WriteFont_Ascii(bw, ref nObjIndex, "Times-Italic", "F0");						//欧文フォント指定
					WriteFont_UnicodeJapanese(bw, ref nObjIndex, "KozMinPr6N-Regular", "F0");		//日本語フォント指定(フォント埋め込みなし)
				}

				//カタログ出力
				int nRoot = nObjIndex;
				{
					WriteCatalog(bw, ref nObjIndex, nObjIndex + 1);
				}

				//ページ出力
				{
					List<int> listPage = new List<int>();

					//全ページのインデックスを出力
					int nPagesReferenceIndex = nObjIndex;
					{
						listPage.Add(nObjIndex + 1);				//1ページ目のインデックスを渡す
						WritePages(bw, ref nObjIndex, listPage);
					}


					//1ページ出力
					{
						WritePageContentsIndex(bw, ref nObjIndex, nPagesReferenceIndex, nResourceIndex, nObjIndex + 1, 595, 842);

						//ページテキスト出力
						{
							List<PDFText> listTexts = new List<PDFText>();

							listTexts.Add(new PDFText("F0", 40, 50, 540, @"abcあいうえお漢字123"));			//変更


							//コンテンツの書き出し
							using (MemoryStream ms = new MemoryStream())
							using (BinaryWriter bwms = new BinaryWriter(ms))
							{
								//文字データをPDF出力用に準備
								PrepareTextContents(ms, listTexts);

								ms.Flush();

								byte[] data = ms.ToArray();

								//ページコンテンツの出力
								WriteFlateData(bw, ref nObjIndex, data);
							}
						}
					}
				}

				//クロスリファレンス/トレーラー出力
				WriteXrefTrailer(bw, nRoot);
			}

			return true;
		}
		/// <summary>
		/// 日本語フォントの指定(フォント埋め込みなし)
		/// 
		/// フォント名は↓
		/// https://www.adobe.com/jp/support/type/aj1-6.html
		/// 小塚明朝 Std Rは「KozMinStd-Regular」
		/// 小塚明朝 Pro Rは「KozMinPro-Regular」
		/// 小塚明朝 Pr6N Rは「KozMinPr6N-Regular」
		/// りょう Text PlusN Rは「RyoTextPlusN-Regular」
		/// </summary>
		void WriteFont_UnicodeJapanese(PDFRawWriter bw, ref int nObjIndex, string strFont, string strFontObjName)
		{
			_listnXref.Add(bw.BaseStream.Position);

			bw.WriteLine("" + nObjIndex + " 0 obj");
			bw.WriteLine("<</Font");
			bw.WriteLine("<</" + strFontObjName);
			bw.WriteLine("<<");
			bw.WriteLine("/Type /Font");
			bw.WriteLine("/BaseFont /" + strFont);
			bw.WriteLine("/Subtype /Type0");
			bw.WriteLine("/Encoding /UniJIS-UTF16-H");			//ユニコード(big endian)
			bw.WriteLine("/DescendantFonts [" + (nObjIndex + 1) + " 0 R]");
			bw.WriteLine(">>");
			bw.WriteLine(">>");
			bw.WriteLine(">>");
			bw.WriteLine("endobj");

			nObjIndex++;

			_listnXref.Add(bw.BaseStream.Position);

			bw.WriteLine("" + nObjIndex + " 0 obj");
			bw.WriteLine("<</Type /Font");
			bw.WriteLine("/Subtype /CIDFontType0");
			bw.WriteLine("/BaseFont /" + strFont);
			bw.WriteLine("/CIDSystemInfo <<");
			bw.WriteLine("/Registry (Adobe)");
			//bw.WriteLine("/Ordering (UCS)");
			bw.WriteLine("/Ordering (Japan1)");
			bw.WriteLine("/Supplement 6");
			bw.WriteLine(">>");
			bw.WriteLine("/FontDescriptor " + (nObjIndex + 1) + " 0 R");
			bw.WriteLine(">>");
			bw.WriteLine("endobj");

			nObjIndex++;

			_listnXref.Add(bw.BaseStream.Position);

			bw.WriteLine("" + nObjIndex + " 0 obj");
			bw.WriteLine("<<");
			bw.WriteLine("/Type /FontDescriptor");
			bw.WriteLine("/FontName /" + strFont);
			bw.WriteLine("/Flags 4");
			//bw.WriteLine("/FontBBox [-437 -340 1147 1317]");
			bw.WriteLine("/FontBBox [0 0 0 0]");			//↓この辺どう取得したらいいのか不明
			bw.WriteLine("/ItalicAngle 0");
			bw.WriteLine("/Ascent 1317");
			bw.WriteLine("/Descent -349");
			bw.WriteLine("/CapHeight 742");
			bw.WriteLine("/StemV 80");
			bw.WriteLine(">>");
			bw.WriteLine("endobj");

			nObjIndex++;


			//フォント情報の保存
			_mapFontType.Add(strFontObjName, FONT_TYPE.ADOBE_JPN1_6);
		}


		void WritePageContentsIndex(PDFRawWriter bw, ref int nObjIndex, int nParentObjIndex, int nResourcesObjIndex, int nContentsObjIndex, float fWidth, float fHeight)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Page");
				bw.WriteLine("/Parent " + nParentObjIndex + " 0 R");
				bw.WriteLine("/Resources " + nResourcesObjIndex + " 0 R");
				bw.WriteLine("/MediaBox [0 0 " + fWidth + " " + fHeight + "]");
				bw.WriteLine("/Contents " + nContentsObjIndex + " 0 R");
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;
		}


		/// <summary>
		/// 与えられたテキストデータをストリームに以下の形式で書き込む
		/// "BT /F0 10 Tf 150 200 Td (hello) Tj ET\r";
		/// </summary>
		void PrepareTextContents(Stream strm, List<PDFText> listTexts)
		{
			using (MemoryStream ms = new MemoryStream())
			using (BinaryWriter bwms = new BinaryWriter(ms))
			{
				foreach (PDFText text in listTexts)
				{
					bool ret;
					FONT_TYPE type;

					ret = _mapFontType.TryGetValue(text.strFont, out type);
					if (ret == false)
					{
						//フォントの種類特定失敗
						Debug.Assert(false);
						continue;
					}


					string strText = text.strText;

					byte[] raw2 = null;

					{
						byte[] tmp = null;

						//フォントに応じてエンコーディング
						if (type == FONT_TYPE.ASCII)
							tmp = Encoding.ASCII.GetBytes(strText);
						if (type == FONT_TYPE.ADOBE_JPN1_6)
							tmp = Encoding.BigEndianUnicode.GetBytes(strText);
						else
						{
							Debug.Assert(false);
						}

						// 「()\」をエスケープする
						using (MemoryStream ms_esc = new MemoryStream())
						{
							foreach (byte cb in tmp)
							{
								if (cb == 0x28		//'('
									|| cb == 0x29	//')'
									|| cb == 0x5c)	//'\'
								{
									ms_esc.WriteByte(0x5c);		//'\'
								}
								ms_esc.WriteByte(cb);
							}
							ms_esc.Flush();

							raw2 = ms_esc.ToArray();
						}
					}

					string strData = "BT /" + text.strFont + " " + text.fPoint + " Tf " + text.fX + " " + text.fY + " Td (";
					byte[] raw1 = Encoding.ASCII.GetBytes(strData);
					byte[] raw3 = Encoding.ASCII.GetBytes(") Tj ET");

					bwms.Write(raw1);
					bwms.Write(raw2);
					bwms.Write(raw3);
					bwms.Write('\r');
				}
				ms.Flush();

				byte[] data = ms.ToArray();
				strm.Write(data, 0, data.Length);
			}
		}

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

第06回 簡単なPDFファイルを作成する


今回はPDFを作成します。
PDFは1ページのみで、内容は半角英数字のテキストのみ、フォントの埋め込みもなしです。

構成内容がこれだけの簡単なPDFです。

・PDFヘッダー
・フォントオブジェクト
・カタログオブジェクト(/Type /Catalog)
・ページインデックスオブジェクト(/Type /Pages)
・ページコンテンツインデックスオブジェクト(/Type /Page)
・ページコンテンツオブジェクト(stream情報)
・クロスリファレンス
・トレーラー
・PDFヘッダー

各所でオブジェクトのインデックスが参照されるので、nObjIndexとして管理。
クロスリファレンス作成用に_listnXrefを用意して、各オブジェクトを書き込む前にそのseekポジションを保存しました。
コンテンツ内容のstreamは圧縮する必要はないのですが、今後のことも考えてDeflateStreamで圧縮しています。

---
まずは別に作らなくていいのですが、PDFRawReaderを作ってしまったので、それに合わせて、PDFRawWriterクラスを作ります。
「プロジェクト」メニューから「クラスの追加」を選択し、「PDFRawWriter.cs」というクラスを追加。

同様にPDFTextReaderに合わせて、PDFTextWriterクラスを作ります。
「プロジェクト」メニューから「クラスの追加」を選択し、「PDFTextWriter.cs」というクラスを追加。

最後にForm1.csからPDFTextWriter.CreatePDFFile()を呼び出すようにすれば完成です。

■PDFRawWriter.cs
using System.IO;
using System.Text;

namespace Pdf2Pdf
{
	class PDFRawWriter : BinaryWriter
	{
		public PDFRawWriter(Stream strm)
			: base(strm)
		{
		}


		/// <summary>
		/// asciiエンコーディングで書き込む!
		/// </summary>
		public void WriteLine(string strText)
		{
			byte[] data = Encoding.ASCII.GetBytes(strText);
			Write(data);
			Write0x0a();
		}


		public void Write0x0a()
		{
			Write('\r');
		}
	}
}

■PDFTextWrite.cs
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace Pdf2Pdf
{
	class PDFTextWriter
	{
		enum FONT_TYPE
		{
			ASCII,
		}



		//クロスリファレンス生成用データ(各オブジェクトの位置を保存)
		List<long> _listnXref = new List<long>();

		//フォントの種類保存用
		IDictionary<string, FONT_TYPE> _mapFontType = new Dictionary<string, FONT_TYPE>();



		public void Close()
		{
			_listnXref.Clear();
			_mapFontType.Clear();
		}


		public bool CreatePDFFile(string strFile)
		{
			Close();

			int nObjIndex = 1;

			using (FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write))
			using (PDFRawWriter bw = new PDFRawWriter(fs))
			{
				//ヘッダー出力
				bw.WriteLine("%PDF-1.7");

				//フォント出力
				int nResourceIndex;
				{
					nResourceIndex = nObjIndex;
					WriteFont_Ascii(bw, ref nObjIndex, "Times-Italic", "F0");
				}

				//カタログ出力
				int nRoot = nObjIndex;
				{
					WriteCatalog(bw, ref nObjIndex, nObjIndex + 1);
				}

				//ページ出力
				{
					List<int> listPage = new List<int>();

					//全ページのインデックスを出力
					int nPagesReferenceIndex = nObjIndex;
					{
						listPage.Add(nObjIndex + 1);				//1ページ目のインデックスを渡す
						WritePages(bw, ref nObjIndex, listPage);
					}


					//1ページ出力
					{
						WritePageContentsIndex(bw, ref nObjIndex, nPagesReferenceIndex, nResourceIndex, nObjIndex + 1, 595, 842);

						//ページテキスト出力
						{
							List<PDFText> listTexts = new List<PDFText>();

							listTexts.Add(new PDFText("F0", 40, 50, 540, @"abc123"));


							//コンテンツの書き出し
							using (MemoryStream ms = new MemoryStream())
							using (BinaryWriter bwms = new BinaryWriter(ms))
							{
								//文字データをPDF出力用に準備
								PrepareTextContents(ms, listTexts);

								ms.Flush();

								byte[] data = ms.ToArray();

								//ページコンテンツの出力
								WriteFlateData(bw, ref nObjIndex, data);
							}
						}
					}
				}

				//クロスリファレンス/トレーラー出力
				WriteXrefTrailer(bw, nRoot);
			}

			return true;
		}



		/// <summary>
		/// カタログの書き込み
		/// 
		/// nPagesObjIndex は、WritePages()のnObjIndexを指定
		/// </summary>
		void WriteCatalog(PDFRawWriter bw, ref int nObjIndex, int nPagesObjIndex)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Catalog");
				bw.WriteLine("/Pages " + nPagesObjIndex + " 0 R");
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;
		}


		/// <summary>
		/// ページ情報の書き込み
		/// 
		/// listnKidsObjIndex は、WritePageContentsIndex()へのインデックス。すべてのページ分を用意する
		/// </summary>
		void WritePages(PDFRawWriter bw, ref int nObjIndex, List<int> listnKidsObjIndex)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Pages");

				string strKidLine = "/Kids [";
				foreach (int nKidObj in listnKidsObjIndex)
				{
					strKidLine += "" + nKidObj + " 0 R ";
				}
				strKidLine += "]";
				bw.WriteLine(strKidLine);

				bw.WriteLine("/Count " + listnKidsObjIndex.Count);
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;
		}



		/// <summary>
		/// 欧文フォントの指定
		/// 
		/// デフォルトで用意されているフォントを利用する場合はこれで指定、
		/// 使えるフォント名(strFont)は↓
		/// Times-Roman
		/// Helvetica
		/// Courier
		/// Symbol
		/// Times-Bold
		/// Helvetica-Bold
		/// Courier-Bold
		/// ZapfDingbats
		/// Times-Italic
		/// Helvetica-Oblique
		/// Courier-Oblique
		/// Times-BoldItalic
		/// Helvetica-BoldOblique
		/// Courier-BoldOblique
		/// </summary>
		void WriteFont_Ascii(PDFRawWriter bw, ref int nObjIndex, string strFont, string strFontObjName)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Font");
				bw.WriteLine("<</" + strFontObjName);
					bw.WriteLine("<<");
						bw.WriteLine("/Type /Font");
						bw.WriteLine("/BaseFont /" + strFont);
						bw.WriteLine("/Subtype /Type1");
					bw.WriteLine(">>");
				bw.WriteLine(">>");
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;

			//フォント情報の保存
			_mapFontType.Add(strFontObjName, FONT_TYPE.ASCII);
		}



		void WritePageContentsIndex(PDFRawWriter bw, ref int nObjIndex, int nParentObjIndex, int nResourcesObjIndex, int nContentsObjIndex, float fWidth, float fHeight)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Type /Page");
				bw.WriteLine("/Parent " + nParentObjIndex + " 0 R");
				bw.WriteLine("/Resources " + nResourcesObjIndex + " 0 R");
				bw.WriteLine("/MediaBox [0 0 " + fWidth + " " + fHeight + "]");
				bw.WriteLine("/Contents " + nContentsObjIndex + " 0 R");
				bw.WriteLine(">>");
				bw.WriteLine("endobj");
			}
			nObjIndex++;
		}







		/// <summary>
		/// 与えられたテキストデータをストリームに以下の形式で書き込む
		/// "BT /F0 10 Tf 150 200 Td (hello) Tj ET\r";
		/// </summary>
		void PrepareTextContents(Stream strm, List<PDFText> listTexts)
		{
			using (MemoryStream ms = new MemoryStream())
			using (BinaryWriter bwms = new BinaryWriter(ms))
			{
				foreach (PDFText text in listTexts)
				{
					bool ret;
					FONT_TYPE type;

					ret = _mapFontType.TryGetValue(text.strFont, out type);
					if (ret == false)
					{
						//フォントの種類特定失敗
						Debug.Assert(false);
						continue;
					}


					string strText = text.strText;

					byte[] raw2 = null;

					if (type == FONT_TYPE.ASCII)
					{
						//カッコと¥をエスケープ
						strText = strText.Replace(@"\", @"\\");
						strText = strText.Replace(@"(", @"\(");
						strText = strText.Replace(@")", @"\)");

						raw2 = Encoding.ASCII.GetBytes(strText);
					}
					else
					{
						Debug.Assert(false);
					}

					string strData = "BT /" + text.strFont + " " + text.fPoint + " Tf " + text.fX + " " + text.fY + " Td (";
					byte[] raw1 = Encoding.ASCII.GetBytes(strData);
					byte[] raw3 = Encoding.ASCII.GetBytes(") Tj ET");

					bwms.Write(raw1);
					bwms.Write(raw2);
					bwms.Write(raw3);
					bwms.Write('\r');
				}
				ms.Flush();

				byte[] data = ms.ToArray();
				strm.Write(data, 0, data.Length);
			}
		}


		/// <summary>
		/// pcbRawData をCompressDeflate()にかけてstreamとして書き込む
		/// (pcbRawDataは圧縮せずに生データを渡すこと!)
		/// </summary>
		void WriteFlateData(PDFRawWriter bw, ref int nObjIndex, byte[] pcbRawData)
		{
			_listnXref.Add(bw.BaseStream.Position);
			{
				int nLength;

				byte[] data = CompressDeflate(pcbRawData);
				nLength = data.Length + 2;

				bw.WriteLine("" + nObjIndex + " 0 obj");
				bw.WriteLine("<</Filter /FlateDecode /Length " + nLength + ">>");
				bw.WriteLine("stream");
				{
					byte[] header = new byte[2];
					header[0] = 0x78;
					header[1] = 0x9c;
					bw.Write(header);
				}
				bw.Write(data);
				bw.Write0x0a();
				bw.WriteLine("endstream");
				bw.WriteLine("endobj");
			}
			nObjIndex++;
		}



		/// <summary>
		/// クロスリファレンス/トレーラー/PDFフッターの書き出し
		/// </summary>
		void WriteXrefTrailer(PDFRawWriter bw, int nRootObjIndex)
		{
			//Trailerは1行のバイト数が重要

			long nXrefPos = bw.BaseStream.Position;

			bw.WriteLine("xref");
			bw.WriteLine("0 " + (_listnXref.Count + 1));
			bw.WriteLine("0000000000 65535 f ");

			foreach (long n in _listnXref)
			{
				bw.WriteLine(string.Format("{0:0000000000}", n) + " 00000 n ");
			}

			bw.WriteLine("trailer");
			bw.WriteLine("<<");
			bw.WriteLine("/Root " + nRootObjIndex + " 0 R");
			bw.WriteLine("/Size " + (_listnXref.Count + 1));
			bw.WriteLine(">>");

			bw.WriteLine("startxref");
			bw.WriteLine("" + nXrefPos);
	
			bw.WriteLine("%%EOF");
		}


		/// <summary>
		/// Deflateを圧縮する
		/// </summary>
		byte[] CompressDeflate(byte[] data)
		{
			byte[] ret = new byte[0];

			using (MemoryStream ms = new MemoryStream())
			{
				DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress);

				ds.Write(data, 0, data.Length);
				ds.Flush();
				ds.Close();

				ret = ms.ToArray();
				ds.Dispose();
			}

			return ret;
		}
	}
}
■Form1.cs
		public Form1()
		{
			InitializeComponent();

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

			//以下を追加
			PDFTextWriter pw = new PDFTextWriter();
			pw.CreatePDFFile("test.pdf");

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

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

前の10件 1  2  3  4  5  6  7  8  9  10  11