How To…AutoSize Font to One Page

Question

“How can I shrink the font to force the report to produce a single page?”

Solution

This example contains a pre-processing step that generates the report pages to a dummy output device. If more than one page is produced, then the font size is adjusted. Following the pre-processing step, Report.Print is called to generate the report to preview.

Download:  ForceFontToOnePageReport.zip

Sample Delphi code:

procedure TForm1.Button1Click(Sender: TObject);
var
  lDevice: TppDevice;
  lbReduceFont: Boolean;
begin

  if FPrinting then Exit;

  FPrinting := True;

  lDevice := TppDevice.Create(nil);

  lbReduceFont := True;

  while lbReduceFont do
    begin

      ppReport1.PrintToDevices;

      if (ppReport1.AbsolutePageCount > 1) then
        lbReduceFont := ReduceFont(ppReport1)
      else
        lbReduceFont := False;

    end;

  lDevice.Free;

  ppReport1.Print;

  FPrinting := False;

end;

function TForm1.ReduceFont(aReport: TppReport): Boolean;
var
  liBand: Integer;
  liObject: Integer;
  lObject: TppComponent;
begin

  Result := True;

  for liBand := 0 to aReport.BandCount-1 do
    begin

      for liObject := 0 to aReport.Bands[liBand].ObjectCount-1 do
        begin
          lObject := aReport.Bands[liBand].Objects[liObject];

          if lObject.HasFont then
            begin
              lObject.Font.Size := lObject.Font.Size - 1;

              if (lObject.Font.Size <= 2) then
                Result := False;

            end;

        end;

    end;

end;