我试图用Delphi 2010打印文本文件。我找到了一些代码,但是当我运行时,它要求保存一个xps文件,它不显示打印对话框。该代码位于http://www.delphipages.com/forum/showthread.php?t=72986
procedure TForm1.print_btnClick(Sender: TObject);
var
filename: string;
begin
filename := 'printfile.txt';
ShellExecute(handle, 'print', pchar(Filename), nil, nil, SW_NORMAL);
end;
另一个位于http://www.delphibasics.co.uk/Article.asp?Name=Printing
这一次又一次循环“确定”对话框,它无法打印任何内容。
问候
最佳答案
选项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;
警告:如果文本文件中的任何一行太宽以致于不能放在一张纸上(包装后),上述代码将不起作用。我太累了,无法立即解决该问题。
选项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;
我建议不要这样做,因为它太讨厌了。
关于delphi - 使用delphi打印文本文件所需的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6809478/