Option 1
您可以编写自己的打印代码。一个简单的例子(uses Printers
):
procedure PrintTextFile(const FileName: string; const Numbering: boolean = true);
const
FONT_NAME = 'Times New Roman';
FONT_SIZE = 10;
var
MARGIN: integer;
sl: TStringList;
i, h: Integer;
r, rFooter: TRect;
s: string;
DocEnd: integer;
begin
with TPrintDialog.Create(nil) do
try
if not Execute then
Exit;
finally
Free;
end;
sl := TStringList.Create;
try
sl.LoadFromFile(FileName);
Printer.BeginDoc;
Printer.Title := FileName; // or application name or sth else
Printer.Canvas.Font.Name := FONT_NAME;
Printer.Canvas.Font.Size := FONT_SIZE;
MARGIN := 5*Printer.Canvas.TextWidth('M');
DocEnd := Printer.PageHeight - MARGIN;
if Numbering then
begin
dec(DocEnd, 2*Printer.Canvas.TextHeight('8'));
rFooter := Rect(0, DocEnd, Printer.PageWidth, Printer.PageHeight - MARGIN);
DrawText(Printer.Canvas.Handle,
PChar(IntToStr(Printer.PageNumber)),
length(IntToStr(Printer.PageNumber)),
rFooter,
DT_SINGLELINE or DT_CENTER or DT_BOTTOM);
end;
r.Left := MARGIN;
r.Top := MARGIN;
for i := 0 to sl.Count - 1 do
begin
r.Right := Printer.PageWidth - MARGIN;
r.Bottom := DocEnd;
s := sl.Strings[i];
if s = '' then s := ' ';
h := DrawText(Printer.Canvas.Handle, // Height of paragraph on paper
PChar(s),
length(s),
r,
DT_LEFT or DT_TOP or DT_WORDBREAK or DT_CALCRECT);
if r.Top + h >= DocEnd then
begin
Printer.NewPage;
if Numbering then
DrawText(Printer.Canvas.Handle,
PChar(IntToStr(Printer.PageNumber)),
length(IntToStr(Printer.PageNumber)),
rFooter,
DT_SINGLELINE or DT_CENTER or DT_BOTTOM);
r.Top := MARGIN;
r.Bottom := DocEnd;
end;
if h > Printer.PageHeight - 2*MARGIN then
raise Exception.Create('Line too long to fit on single page.');
DrawText(Printer.Canvas.Handle,
PChar(s),
length(s),
r,
DT_LEFT or DT_TOP or DT_WORDBREAK);
inc(r.Top, h);
end;
Printer.EndDoc;
finally
sl.Free;
end;
end;
Warning:上面的代码做了not如果文本文件中的任何单行太宽以至于无法容纳在单张纸上(换行后),则可以使用。我现在太累了,无法解决这个问题。
Option 2
一个令人讨厌的伎俩是使用一个看不见的东西TRichEdit
打印。
procedure PrintTextFile(AOwner: TWinControl; const FileName: string);
begin
with TRichEdit.Create(nil) do
try
Visible := false;
Parent := AOwner;
Lines.LoadFromFile(FileName);
with TPrintDialog.Create(nil) do
try
if Execute then
Print(FileName);
finally
Free;
end;
finally
Free;
end;
end;
我建议不要这样做,因为它有点太令人讨厌了。