在Delphi中实现分栏打印
软件世界
笔者在给公司开发软件的过程中,涉及到一个打印模块,感觉很有趣,就拿其中的一个小功能模块与大家共享。下面就以在纸张的矩形框内打印为例简单介绍:
要求:
单点“打印”按钮,把Memo的内容最多分成3行打出来,每行最多能容22个3号字,限定汉字的上限是50个汉字。
编程思路:
用LineTo及MoveTo函数画一个矩形框,根据Memo组件中的内容长度,用Copy函数将它分割成1至3个子串。在矩形框内美观地输出文字时的技术处理是:当输出一行时最多能打18个汉字,当输出多行时第一、第二行分别打16和18个汉字。
具体步骤:
1.首先建一新工程,在窗体上加上一个Memo组件和Button组件。
2.Memo组件中的Lines值设为空,MaxLength值设为“100”(即是50个汉字),字体是“三号字”;Button中的Caption值是“打印”。
3.添加“打印”按钮的事件处理代码Button1.Click,先在Interface中的Uses部分增加Printers,它的完整代码为:
procedure TForm1.Button1Click(Sender: TObject);
var Str_Len, Left, Top, Word_Height,word_Width: Integer;
Content_Str:String[100];
Str1, Str2, Str3 : String[36];
begin
with Printer do
begin
Canvas.Font.Size:=16;
Word_Height:=Canvas.TextHeight
('字');
word_Width:=Canvas.TextWidth
('字');
Left:=(Printer.PageWidth-word_Width*22) div 2;
Top:=(Printer.PageHeight-Word_Height*7) div 2;
BeginDOC;
With Canvas do
begin
Pen.Width:=3;
{画一个7个字高,22个字宽的矩形框}
MoveTo(Left,Top);
LineTo(Left+word_Width*22,Top);
LineTo(Left+word_Width*22,Top+Word_Height*7);
LineTo(Left,Top+Word_Height*7);
LineTo(Left,Top);
Content_Str:=Memo1.Lines.Text;
Str_Len:=Length(Content_Str);
if Str_Len< 37 then
{分1行打印}
begin
TextOut(Left+word_Width*2, Top+Word_Height*3, Content_Str)
end
else if Str_Len< 66 then
{在垂直方向中间分成两行打印}
begin
Str1:=Copy(Content_Str, 0, 32);
Str2:=Copy(Content_Str, 33, Str_Len-32),;
TextOut(Left+word_Width*4, Top+Word_Height*(7-2)div 2,Str1);
TextOut(Left+word_Width*2, Top+Word_Height*(7-2)div 2+Word_Height,Str2);
end
else
{分3行打印}
begin
Str1:=Copy(Content_Str,0,32);
Str2:=Copy(Content_Str,33,36);
Str3:=Copy(Content_Str, 69, Str_Len-68);
TextOut(Left+word_Width*4, Top+Word_Height*2, Str1);
{左缩两个汉字}
TextOut(Left+word_Width*2, Top+Word_Height*3, Str2);
TextOut(Left+word_Width*2, Top+Word_Height*4, Str3);
end
end;
EndDoc;
end;
end;
注:以上程序在Delphi 6中调试通过,希望能对初次编写打印程序的读者有点帮助。