☆簡単な印刷サンプル
.NET Framework SDKを見ながら、簡単な印刷サンプルを作ってみました。
このサンプルは、テキストファイルを読み込んでPrintDialogで設定された内容で印刷し
ます。(実際には印刷せずにFuji Xerox Docuworksに印刷して確認しました。)
1.Windowsフォームアプリケーションを新規作成します。
2.Button1, PrintDocument1, PrintDialog1を配置します。
3.usesに System.IO を追加します。
4.フォームのPrivate宣言に
StreamToPrint: StreamReader;
PrintFont: System.Drawing.Font;
と記述します。
5.Button1のClickイベントとPrintDocument1のPrintPageイベントに
下記のプログラムを設定します。
procedure TWinForm1.Button1_Click(sender: System.Object;
e: System.EventArgs);
begin
PrintDialog1.Document := PrintDocument1;
if PrintDialog1.ShowDialog <>
System.Windows.Forms.DialogResult.OK then Exit;
PrintDocument1.PrinterSettings := PrintDialog1.PrinterSettings;
StreamToPrint := StreamReader.Create('c:\PrintMe.txt');
↑↑テキストファイル名は適当に設定して。
try
PrintFont := System.Drawing.Font.Create('Arial', 10);
PrintDocument1.Print;
finally
StreamToPrint.Close;
end;
end;
procedure TWinForm1.PrintDocument1_PrintPage(sender: System.Object;
e: System.Drawing.Printing.PrintPageEventArgs);
var
lpp: Single;
yPos: Single;
Count: Integer;
LeftMargin: Single;
TopMargin: Single;
Line: String;
begin
Count := 0;
LeftMargin := e.MarginBounds.Left;
TopMargin := e.MarginBounds.Top;
lpp := e.MarginBounds.Height / PrintFont.GetHeight(e.Graphics);
Line := StreamToPrint.ReadLine;
while (Count < lpp) do
begin
yPos := TopMargin + (Count * PrintFont.GetHeight(e.Graphics));
e.Graphics.DrawString (Line, PrintFont, Brushes.Black,
LeftMargin, yPos, StringFormat.Create);
Inc(Count);
if (Count < lpp) then
Line := StreamToPrint.ReadLine;
end;
//これではLineが偶然空白行だった場合、
//次ページが印刷されないのだがサンプルということでお許しを(^^;
e.HasMorePages := (Line <> '');
end;
| 固定リンク
