unit frm_ImprimirTextoLibre;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
  Vcl.Buttons, Vcl.Samples.Spin, FireDAC.Comp.Client, FireDAC.Stan.Param,
  frxClass, uAppTheme, System.Math, Vcl.Printers, System.UITypes, Data.DB;

type
  TFormatoTextoItem = class
  public
    Id: Integer;
    Nombre: string;
    Tipo: string; // 'HOJA' o 'ETIQUETA'
    AnchoMM: Double;
    AltoMM: Double;
    Orientacion: string; // 'VERTICAL' o 'HORIZONTAL'
    MargenIzqMM: Double;
    MargenDerMM: Double;
    MargenSupMM: Double;
    MargenInfMM: Double;
    EsSistema: Boolean;
    ArchivoPlantilla: string;
  end;

  TfrmImprimirTextoLibre = class(TForm)
    pnlTop: TPanel;
    lblTitulo: TLabel;
    lblSubtitulo: TLabel;
    pnlControls: TPanel;
    sbControls: TScrollBox;
    grpFormato: TGroupBox;
    lblSelFormato: TLabel;
    cboFormato: TComboBox;
    btnNuevoFormato: TSpeedButton;
    btnEditarFormato: TSpeedButton;
    pnlInfoFormato: TPanel;
    grpEditorTexto: TGroupBox;
    mmoTexto: TMemo;
    grpEstiloFuente: TGroupBox;
    lblFuente: TLabel;
    cboFuentes: TComboBox;
    lblTamanoFuente: TLabel;
    seTamanoFuente: TSpinEdit;
    lblTamanoCalculado: TLabel;
    chkAutoAjuste: TCheckBox;
    lblEstilos: TLabel;
    btnNegrita: TSpeedButton;
    btnSubrayado: TSpeedButton;
    btnCursiva: TSpeedButton;
    lblAlineacion: TLabel;
    btnAlinearIzq: TSpeedButton;
    btnAlinearCentro: TSpeedButton;
    btnAlinearDer: TSpeedButton;
    btnAlinearJustificado: TSpeedButton;
    grpMargenes: TGroupBox;
    lblMargenIzq: TLabel;
    lblMargenDer: TLabel;
    lblMargenSup: TLabel;
    lblMargenInf: TLabel;
    seMargenIzq: TSpinEdit;
    seMargenDer: TSpinEdit;
    seMargenSup: TSpinEdit;
    seMargenInf: TSpinEdit;
    btnGuardarMargenes: TButton;
    grpImpresion: TGroupBox;
    lblCopias: TLabel;
    seCopias: TSpinEdit;
    btnPrevisualizar: TBitBtn;
    btnImprimir: TBitBtn;
    splSplitter: TSplitter;
    pnlPreviewArea: TPanel;
    pnlPreviewHeader: TPanel;
    lblPreviewTitle: TLabel;
    lblPreviewZoomInfo: TLabel;
    pbPreview: TPaintBox;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure FormResize(Sender: TObject);
    procedure cboFormatoChange(Sender: TObject);
    procedure btnNuevoFormatoClick(Sender: TObject);
    procedure btnEditarFormatoClick(Sender: TObject);
    procedure mmoTextoChange(Sender: TObject);
    procedure cboFuentesChange(Sender: TObject);
    procedure chkAutoAjusteClick(Sender: TObject);
    procedure seTamanoFuenteChange(Sender: TObject);
    procedure StyleButtonClick(Sender: TObject);
    procedure AlignButtonClick(Sender: TObject);
    procedure MargenSpinChange(Sender: TObject);
    procedure btnGuardarMargenesClick(Sender: TObject);
    procedure btnPrevisualizarClick(Sender: TObject);
    procedure btnImprimirClick(Sender: TObject);
    procedure pbPreviewPaint(Sender: TObject);
  private
    FMeasureBitmap: TBitmap;
    FUpdatingControls: Boolean;
    FLastCalculatedPt: Integer;
    procedure CargarFuentes;
    procedure CargarFormatos(ASelectId: Integer = 0);
    procedure LimpiarFormatos;
    function GetSelectedFormato: TFormatoTextoItem;
    function ObtenerEstilosFuente: TFontStyles;
    function CalcularTamanoOptimoFuente(out AFontSizePt: Integer): Boolean;
    function ResolverArchivoPlantilla(AF: TFormatoTextoItem): string;
    procedure ActualizarInfoFormato;
    procedure PrepararReporteFastReport(AReport: TfrxReport);
    procedure RenderPreview(ACanvas: TCanvas; AWidth, AHeight: Integer);
    procedure ReportPrintReport(Sender: TObject);
    procedure ReportPrintPage(Page: TfrxReportPage; CopyNo: Integer);
    procedure SincronizarImpresoraFastReport(AReport: TfrxReport; AOrientation: TPrinterOrientation; APaperWidth, APaperHeight: Double; APaperSize: Integer; ACopies: Integer);
  public
  end;

var
  frmImprimirTextoLibre: TfrmImprimirTextoLibre;

implementation

uses
  dmg_Main, frm_FormatoTextoLibreEditor, uFormatosImpresionService, frxPrinter,
  Winapi.WinSpool, frxPreviewPages;

{$R *.dfm}

procedure TfrmImprimirTextoLibre.FormCreate(Sender: TObject);
begin
  FMeasureBitmap := TBitmap.Create;
  FMeasureBitmap.SetSize(10, 10);
  FLastCalculatedPt := 18;
  FUpdatingControls := False;
end;

procedure TfrmImprimirTextoLibre.FormDestroy(Sender: TObject);
begin
  LimpiarFormatos;
  FMeasureBitmap.Free;
end;

procedure TfrmImprimirTextoLibre.FormShow(Sender: TObject);
begin
  TAppTheme.ApplyToForm(Self);
  CargarFuentes;
  CargarFormatos;
  ActualizarInfoFormato;
  pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.FormResize(Sender: TObject);
begin
  pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.LimpiarFormatos;
var
  i: Integer;
begin
  for i := 0 to cboFormato.Items.Count - 1 do
  begin
    if Assigned(cboFormato.Items.Objects[i]) then
      cboFormato.Items.Objects[i].Free;
  end;
  cboFormato.Items.Clear;
end;

procedure TfrmImprimirTextoLibre.CargarFuentes;
var
  i: Integer;
  LTargetIndex: Integer;
begin
  cboFuentes.Items.BeginUpdate;
  try
    cboFuentes.Items.Clear;
    for i := 0 to Screen.Fonts.Count - 1 do
      cboFuentes.Items.Add(Screen.Fonts[i]);

    LTargetIndex := cboFuentes.Items.IndexOf('Segoe UI');
    if LTargetIndex < 0 then
      LTargetIndex := cboFuentes.Items.IndexOf('Arial');
    if LTargetIndex < 0 then
      LTargetIndex := 0;

    cboFuentes.ItemIndex := LTargetIndex;
  finally
    cboFuentes.Items.EndUpdate;
  end;
end;

procedure TfrmImprimirTextoLibre.CargarFormatos(ASelectId: Integer = 0);
var
  Qry: TFDQuery;
  LItem: TFormatoTextoItem;
  LIndex, LTargetIndex: Integer;
begin
  if not Assigned(dmgMain) or not Assigned(dmgMain.dbConn) then
    Exit;

  LimpiarFormatos;
  LTargetIndex := 0;

  Qry := TFDQuery.Create(nil);
  try
    Qry.Connection := dmgMain.dbConn;
    Qry.SQL.Text :=
      'SELECT * FROM ge_formatos_texto_libre ' +
      'WHERE activo = 1 ' +
      'ORDER BY tipo ASC, nombre ASC';
    Qry.Open;

    cboFormato.Items.BeginUpdate;
    try
      while not Qry.Eof do
      begin
        LItem := TFormatoTextoItem.Create;
        LItem.Id := Qry.FieldByName('id').AsInteger;
        LItem.Nombre := Qry.FieldByName('nombre').AsString;
        LItem.Tipo := UpperCase(Qry.FieldByName('tipo').AsString);
        LItem.AnchoMM := Qry.FieldByName('ancho_mm').AsFloat;
        LItem.AltoMM := Qry.FieldByName('alto_mm').AsFloat;
        LItem.Orientacion := UpperCase(Qry.FieldByName('orientacion').AsString);
        LItem.MargenIzqMM := Qry.FieldByName('margen_izq_mm').AsFloat;
        LItem.MargenDerMM := Qry.FieldByName('margen_der_mm').AsFloat;
        LItem.MargenSupMM := Qry.FieldByName('margen_sup_mm').AsFloat;
        LItem.MargenInfMM := Qry.FieldByName('margen_inf_mm').AsFloat;
        if Qry.FieldByName('es_sistema') is TBooleanField then
          LItem.EsSistema := Qry.FieldByName('es_sistema').AsBoolean
        else
          LItem.EsSistema := Qry.FieldByName('es_sistema').AsInteger <> 0;
        if Qry.FindField('archivo_plantilla') <> nil then
          LItem.ArchivoPlantilla := Trim(Qry.FieldByName('archivo_plantilla').AsString)
        else
          LItem.ArchivoPlantilla := '';

        LIndex := cboFormato.Items.AddObject(LItem.Nombre, LItem);

        if (ASelectId > 0) and (LItem.Id = ASelectId) then
          LTargetIndex := LIndex;

        Qry.Next;
      end;
    finally
      cboFormato.Items.EndUpdate;
    end;

    if cboFormato.Items.Count > 0 then
    begin
      cboFormato.ItemIndex := LTargetIndex;
      cboFormatoChange(nil);
    end;
  finally
    Qry.Free;
  end;
end;

function TfrmImprimirTextoLibre.GetSelectedFormato: TFormatoTextoItem;
begin
  Result := nil;
  if (cboFormato.ItemIndex >= 0) and (cboFormato.ItemIndex < cboFormato.Items.Count) then
    Result := TFormatoTextoItem(cboFormato.Items.Objects[cboFormato.ItemIndex]);
end;

procedure TfrmImprimirTextoLibre.ActualizarInfoFormato;
var
  LF: TFormatoTextoItem;
  LTipoDesc, LOriDesc: string;
begin
  LF := GetSelectedFormato;
  if not Assigned(LF) then
  begin
    pnlInfoFormato.Caption := '  Sin formato seleccionado';
    Exit;
  end;

  if LF.Tipo = 'ETIQUETA' then
    LTipoDesc := 'Etiqueta'
  else
    LTipoDesc := 'Hoja suelta';

  if SameText(LF.Orientacion, 'HORIZONTAL') then
  begin
    LOriDesc := 'Horizontal (Landscape)';
    pnlInfoFormato.Caption := Format('  Tipo: %s | Medidas: %.0f x %.0f mm | Orientación: %s',
      [LTipoDesc, Max(LF.AnchoMM, LF.AltoMM), Min(LF.AnchoMM, LF.AltoMM), LOriDesc]);
  end
  else
  begin
    LOriDesc := 'Vertical (Portrait)';
    pnlInfoFormato.Caption := Format('  Tipo: %s | Medidas: %.0f x %.0f mm | Orientación: %s',
      [LTipoDesc, Min(LF.AnchoMM, LF.AltoMM), Max(LF.AnchoMM, LF.AltoMM), LOriDesc]);
  end;

  FUpdatingControls := True;
  try
    seMargenIzq.Value := Round(LF.MargenIzqMM);
    seMargenDer.Value := Round(LF.MargenDerMM);
    seMargenSup.Value := Round(LF.MargenSupMM);
    seMargenInf.Value := Round(LF.MargenInfMM);
  finally
    FUpdatingControls := False;
  end;
end;

procedure TfrmImprimirTextoLibre.cboFormatoChange(Sender: TObject);
begin
  ActualizarInfoFormato;
  pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.btnNuevoFormatoClick(Sender: TObject);
var
  LFrm: TfrmFormatoTextoLibreEditor;
begin
  LFrm := TfrmFormatoTextoLibreEditor.Create(Self);
  try
    LFrm.FormatoId := 0;
    if LFrm.ShowModal = mrOk then
    begin
      CargarFormatos(LFrm.FormatoId);
      pbPreview.Invalidate;
    end;
  finally
    LFrm.Free;
  end;
end;

procedure TfrmImprimirTextoLibre.btnEditarFormatoClick(Sender: TObject);
var
  LF: TFormatoTextoItem;
  LFrm: TfrmFormatoTextoLibreEditor;
begin
  LF := GetSelectedFormato;
  if not Assigned(LF) then
  begin
    ShowMessage('Por favor seleccione un formato para editar.');
    Exit;
  end;

  LFrm := TfrmFormatoTextoLibreEditor.Create(Self);
  try
    LFrm.FormatoId := LF.Id;
    if LFrm.ShowModal = mrOk then
    begin
      CargarFormatos(LF.Id);
      pbPreview.Invalidate;
    end;
  finally
    LFrm.Free;
  end;
end;

function TfrmImprimirTextoLibre.ObtenerEstilosFuente: TFontStyles;
begin
  Result := [];
  if btnNegrita.Down then Include(Result, fsBold);
  if btnSubrayado.Down then Include(Result, fsUnderline);
  if btnCursiva.Down then Include(Result, fsItalic);
end;

procedure TfrmImprimirTextoLibre.mmoTextoChange(Sender: TObject);
begin
  pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.cboFuentesChange(Sender: TObject);
begin
  pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.chkAutoAjusteClick(Sender: TObject);
begin
  seTamanoFuente.Enabled := not chkAutoAjuste.Checked;
  lblTamanoCalculado.Visible := chkAutoAjuste.Checked;
  pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.seTamanoFuenteChange(Sender: TObject);
begin
  if not chkAutoAjuste.Checked then
    pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.StyleButtonClick(Sender: TObject);
begin
  mmoTexto.Font.Style := ObtenerEstilosFuente;
  pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.AlignButtonClick(Sender: TObject);
begin
  pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.MargenSpinChange(Sender: TObject);
var
  LF: TFormatoTextoItem;
begin
  if FUpdatingControls then Exit;
  LF := GetSelectedFormato;
  if Assigned(LF) then
  begin
    LF.MargenIzqMM := seMargenIzq.Value;
    LF.MargenDerMM := seMargenDer.Value;
    LF.MargenSupMM := seMargenSup.Value;
    LF.MargenInfMM := seMargenInf.Value;
  end;
  pbPreview.Invalidate;
end;

procedure TfrmImprimirTextoLibre.btnGuardarMargenesClick(Sender: TObject);
var
  LF: TFormatoTextoItem;
  Qry: TFDQuery;
begin
  LF := GetSelectedFormato;
  if not Assigned(LF) then Exit;

  if not Assigned(dmgMain) or not Assigned(dmgMain.dbConn) then Exit;

  Qry := TFDQuery.Create(nil);
  try
    Qry.Connection := dmgMain.dbConn;
    Qry.SQL.Text :=
      'UPDATE ge_formatos_texto_libre SET ' +
      '  margen_izq_mm = :miz, margen_der_mm = :mde, margen_sup_mm = :msu, margen_inf_mm = :minf, ' +
      '  updated_at = NOW() ' +
      'WHERE id = :id';
    Qry.ParamByName('id').AsInteger := LF.Id;
    Qry.ParamByName('miz').AsInteger := seMargenIzq.Value;
    Qry.ParamByName('mde').AsInteger := seMargenDer.Value;
    Qry.ParamByName('msu').AsInteger := seMargenSup.Value;
    Qry.ParamByName('minf').AsInteger := seMargenInf.Value;
    Qry.ExecSQL;

    LF.MargenIzqMM := seMargenIzq.Value;
    LF.MargenDerMM := seMargenDer.Value;
    LF.MargenSupMM := seMargenSup.Value;
    LF.MargenInfMM := seMargenInf.Value;

    ShowMessage('Márgenes guardados correctamente en el formato "' + LF.Nombre + '".');
  finally
    Qry.Free;
  end;
end;

function TfrmImprimirTextoLibre.CalcularTamanoOptimoFuente(out AFontSizePt: Integer): Boolean;
var
  LF: TFormatoTextoItem;
  LText, LFontName: string;
  LStyles: TFontStyles;
  UsableW_MM, UsableH_MM: Double;
  VirtW, VirtH: Integer;
  LowPt, HighPt, MidPt, BestPt: Integer;

  function TextFits(APt: Integer): Boolean;
  var
    R: TRect;
    LFlags: UINT;
  begin
    if APt < 5 then Exit(True);
    FMeasureBitmap.Canvas.Font.Name := LFontName;
    FMeasureBitmap.Canvas.Font.Height := -Round(APt * 300 / 72);
    FMeasureBitmap.Canvas.Font.Style := LStyles;
    R := Rect(0, 0, VirtW, 0);
    LFlags := DT_CALCRECT or DT_WORDBREAK or DT_NOPREFIX;
    DrawText(FMeasureBitmap.Canvas.Handle, PChar(LText), Length(LText), R, LFlags);
    Result := (R.Bottom - R.Top <= VirtH) and (R.Right - R.Left <= VirtW + 5);
  end;

begin
  Result := False;
  AFontSizePt := 14;
  LF := GetSelectedFormato;
  if not Assigned(LF) then Exit;

  LText := Trim(mmoTexto.Text);
  if LText = '' then
  begin
    AFontSizePt := 18;
    Exit(True);
  end;

  LFontName := cboFuentes.Text;
  if LFontName = '' then LFontName := 'Segoe UI';
  LStyles := ObtenerEstilosFuente;

  // Dimensiones utilizables en milímetros
  if SameText(LF.Orientacion, 'HORIZONTAL') then
  begin
    UsableW_MM := Max(LF.AnchoMM, LF.AltoMM) - seMargenIzq.Value - seMargenDer.Value;
    UsableH_MM := Min(LF.AnchoMM, LF.AltoMM) - seMargenSup.Value - seMargenInf.Value;
  end
  else
  begin
    UsableW_MM := Min(LF.AnchoMM, LF.AltoMM) - seMargenIzq.Value - seMargenDer.Value;
    UsableH_MM := Max(LF.AnchoMM, LF.AltoMM) - seMargenSup.Value - seMargenInf.Value;
  end;

  if UsableW_MM < 10 then UsableW_MM := 10;
  if UsableH_MM < 10 then UsableH_MM := 10;

  // Resolución virtual de cálculo a 300 DPI
  VirtW := Round(UsableW_MM * 300 / 25.4);
  VirtH := Round(UsableH_MM * 300 / 25.4);

  // Búsqueda binaria rápida del tamaño en puntos (pt)
  LowPt := 6;
  HighPt := 250;
  BestPt := 6;

  while LowPt <= HighPt do
  begin
    MidPt := (LowPt + HighPt) div 2;
    if TextFits(MidPt) then
    begin
      BestPt := MidPt;
      LowPt := MidPt + 1; // Probar si cabe uno mayor
    end
    else
    begin
      HighPt := MidPt - 1; // Reducir tamaño
    end;
  end;

  AFontSizePt := BestPt;
  FLastCalculatedPt := BestPt;
  Result := True;
end;

procedure TfrmImprimirTextoLibre.RenderPreview(ACanvas: TCanvas; AWidth, AHeight: Integer);
var
  LF: TFormatoTextoItem;
  Scale, PaperW_MM, PaperH_MM: Double;
  PaperPxW, PaperPxH, PaperLeft, PaperTop: Integer;
  PaperRect, UsableRect, ShadowRect: TRect;
  LText, LFontName: string;
  LStyles: TFontStyles;
  FontSizePt, ScreenFontHeight: Integer;
  LFlags: UINT;
  TextRect: TRect;
  TextHeightPx, OffsetY: Integer;
  LParagraphs, LLines: TStringList;
  p, l: Integer;
  LPara, LLine: string;
  LineRect: TRect;
  ExtraSpace, SpaceCount, s: Integer;
  LDrawY: Integer;
begin
  // 1. Limpiar fondo del panel de visualización
  ACanvas.Brush.Color := $00EFEFEF;
  ACanvas.FillRect(Rect(0, 0, AWidth, AHeight));

  LF := GetSelectedFormato;
  if not Assigned(LF) then
  begin
    ACanvas.Font.Name := 'Segoe UI';
    ACanvas.Font.Size := 12;
    ACanvas.Font.Color := clGray;
    ACanvas.TextOut(30, 30, 'Seleccione un formato de impresión para visualizar');
    Exit;
  end;

  if SameText(LF.Orientacion, 'HORIZONTAL') then
  begin
    PaperW_MM := Max(LF.AnchoMM, LF.AltoMM);
    PaperH_MM := Min(LF.AnchoMM, LF.AltoMM);
  end
  else
  begin
    PaperW_MM := Min(LF.AnchoMM, LF.AltoMM);
    PaperH_MM := Max(LF.AnchoMM, LF.AltoMM);
  end;
  if PaperW_MM <= 0 then PaperW_MM := 100;
  if PaperH_MM <= 0 then PaperH_MM := 100;

  // 2. Factor de escala para encajar la hoja/etiqueta dejando margen de 30 px
  Scale := Min((AWidth - 60) / PaperW_MM, (AHeight - 60) / PaperH_MM);
  if Scale <= 0.05 then Scale := 0.05;

  PaperPxW := Round(PaperW_MM * Scale);
  PaperPxH := Round(PaperH_MM * Scale);
  PaperLeft := (AWidth - PaperPxW) div 2;
  PaperTop := (AHeight - PaperPxH) div 2;

  PaperRect := Rect(PaperLeft, PaperTop, PaperLeft + PaperPxW, PaperTop + PaperPxH);

  // 3. Dibujar sombra suave de papel
  ShadowRect := Rect(PaperLeft + 6, PaperTop + 6, PaperLeft + PaperPxW + 6, PaperTop + PaperPxH + 6);
  ACanvas.Brush.Color := $00D0D0D0;
  ACanvas.Pen.Color := $00D0D0D0;
  ACanvas.Rectangle(ShadowRect);

  // 4. Dibujar hoja de papel / etiqueta blanca
  ACanvas.Brush.Color := clWhite;
  ACanvas.Pen.Color := $00B0B0B0;
  ACanvas.Pen.Width := 1;
  ACanvas.Rectangle(PaperRect);

  // 5. Dibujar márgenes con línea discontinua suave
  UsableRect.Left := PaperLeft + Round(seMargenIzq.Value * Scale);
  UsableRect.Top := PaperTop + Round(seMargenSup.Value * Scale);
  UsableRect.Right := PaperLeft + PaperPxW - Round(seMargenDer.Value * Scale);
  UsableRect.Bottom := PaperTop + PaperPxH - Round(seMargenInf.Value * Scale);

  ACanvas.Pen.Color := $00D8D8D8;
  ACanvas.Pen.Style := psDot;
  ACanvas.Brush.Style := bsClear;
  ACanvas.Rectangle(UsableRect);
  ACanvas.Pen.Style := psSolid;

  // 6. Determinar tamaño de fuente
  if chkAutoAjuste.Checked then
  begin
    CalcularTamanoOptimoFuente(FontSizePt);
    lblTamanoCalculado.Caption := Format('Tamaño auto: %d pt', [FontSizePt]);
  end
  else
  begin
    FontSizePt := seTamanoFuente.Value;
  end;

  LText := mmoTexto.Text;
  if Trim(LText) = '' then Exit;

  LFontName := cboFuentes.Text;
  if LFontName = '' then LFontName := 'Segoe UI';
  LStyles := ObtenerEstilosFuente;

  // Altura de fuente en píxeles de pantalla según escala real
  ScreenFontHeight := Round(FontSizePt * (25.4 / 72.0) * Scale);
  if ScreenFontHeight < 4 then ScreenFontHeight := 4;

  ACanvas.Font.Name := LFontName;
  ACanvas.Font.Height := -ScreenFontHeight;
  ACanvas.Font.Style := LStyles;
  ACanvas.Font.Color := clBlack;
  ACanvas.Brush.Style := bsClear;

  // 7. Medir altura total del texto para centrado vertical
  TextRect := Rect(UsableRect.Left, UsableRect.Top, UsableRect.Right, UsableRect.Top);
  LFlags := DT_CALCRECT or DT_WORDBREAK or DT_NOPREFIX;
  DrawText(ACanvas.Handle, PChar(LText), Length(LText), TextRect, LFlags);
  TextHeightPx := TextRect.Bottom - TextRect.Top;

  OffsetY := 0;
  if (TextHeightPx > 0) and (TextHeightPx < (UsableRect.Bottom - UsableRect.Top)) then
    OffsetY := ((UsableRect.Bottom - UsableRect.Top) - TextHeightPx) div 2;

  // 8. Renderizar texto según alineación
  if btnAlinearJustificado.Down then
  begin
    // Renderizado Justificado párrafo a párrafo
    LParagraphs := TStringList.Create;
    LLines := TStringList.Create;
    try
      LParagraphs.Text := LText;
      LDrawY := UsableRect.Top + OffsetY;

      for p := 0 to LParagraphs.Count - 1 do
      begin
        LPara := LParagraphs[p];
        if Trim(LPara) = '' then
        begin
          LDrawY := LDrawY + ScreenFontHeight;
          Continue;
        end;

        // Partir el párrafo en líneas que quepan en UsableRect
        LLines.Clear;
        var Words := LPara.Split([' ']);
        var CurLine := '';
        for var w := 0 to High(Words) do
        begin
          var TestLine: string;
          if CurLine = '' then
            TestLine := Words[w]
          else
            TestLine := CurLine + ' ' + Words[w];

          var Wd := ACanvas.TextWidth(TestLine);
          if (Wd <= (UsableRect.Right - UsableRect.Left)) or (CurLine = '') then
            CurLine := TestLine
          else
          begin
            LLines.Add(CurLine);
            CurLine := Words[w];
          end;
        end;
        if CurLine <> '' then
          LLines.Add(CurLine);

        // Dibujar cada línea justificada
        for l := 0 to LLines.Count - 1 do
        begin
          LLine := LLines[l];
          if LDrawY + ScreenFontHeight > UsableRect.Bottom + 5 then Break;

          if (l = LLines.Count - 1) or (Pos(' ', LLine) = 0) then
          begin
            // Última línea del párrafo: alineada a la izquierda
            ACanvas.TextOut(UsableRect.Left, LDrawY, LLine);
          end
          else
          begin
            // Distribuir el espacio sobrante entre las palabras
            SpaceCount := 0;
            for s := 1 to Length(LLine) do
              if LLine[s] = ' ' then Inc(SpaceCount);

            if SpaceCount > 0 then
            begin
              ExtraSpace := (UsableRect.Right - UsableRect.Left) - ACanvas.TextWidth(LLine);
              if ExtraSpace > 0 then
                SetTextJustification(ACanvas.Handle, ExtraSpace, SpaceCount);
            end;

            ACanvas.TextOut(UsableRect.Left, LDrawY, LLine);
            SetTextJustification(ACanvas.Handle, 0, 0);
          end;

          LDrawY := LDrawY + ScreenFontHeight + Round(ScreenFontHeight * 0.15);
        end;
      end;
    finally
      LLines.Free;
      LParagraphs.Free;
    end;
  end
  else
  begin
    // Alineación Izquierda, Centro o Derecha estándar
    LFlags := DT_WORDBREAK or DT_NOPREFIX;
    if btnAlinearCentro.Down then
      LFlags := LFlags or DT_CENTER
    else if btnAlinearDer.Down then
      LFlags := LFlags or DT_RIGHT
    else
      LFlags := LFlags or DT_LEFT;

    TextRect := Rect(UsableRect.Left, UsableRect.Top + OffsetY, UsableRect.Right, UsableRect.Bottom);
    DrawText(ACanvas.Handle, PChar(LText), Length(LText), TextRect, LFlags);
  end;
end;

procedure TfrmImprimirTextoLibre.pbPreviewPaint(Sender: TObject);
begin
  RenderPreview(pbPreview.Canvas, pbPreview.Width, pbPreview.Height);
end;

function TfrmImprimirTextoLibre.ResolverArchivoPlantilla(AF: TFormatoTextoItem): string;
var
  LIsLandscape: Boolean;
  LMinDim, LMaxDim: Integer;
begin
  Result := '';
  if not Assigned(AF) then Exit;

  // 1. Si el registro ya especifica un archivo .fr3 específico y existe
  if AF.ArchivoPlantilla <> '' then
  begin
    Result := TFormatosImpresionService.ResolverRutaArchivo(AF.ArchivoPlantilla);
    if (Result <> '') and FileExists(Result) then Exit;
  end;

  LIsLandscape := SameText(AF.Orientacion, 'HORIZONTAL');
  LMinDim := Round(Min(AF.AnchoMM, AF.AltoMM));
  LMaxDim := Round(Max(AF.AnchoMM, AF.AltoMM));

  // 2. Mapeo específico por dimensiones físicas y orientación a su correspondiente .fr3
  // A7 / Etiqueta 105x74 mm
  if (LMinDim = 74) and (LMaxDim = 105) then
  begin
    if LIsLandscape then
      Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_A7_105x74_H.fr3')
    else
      Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_A7_74x105_V.fr3');
  end
  // Etiqueta 100x50 mm
  else if (LMinDim = 50) and (LMaxDim = 100) then
  begin
    Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_100x50_H.fr3');
  end
  // Etiqueta 100x76 mm
  else if (LMinDim = 76) and (LMaxDim = 100) then
  begin
    Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_100x76_H.fr3');
  end
  // Etiqueta Palet 100x150 mm
  else if (LMinDim = 100) and (LMaxDim = 150) then
  begin
    Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_100x150_V.fr3');
  end
  // Etiqueta 70x36 mm
  else if (LMinDim = 36) and (LMaxDim = 70) then
  begin
    Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_70x36_H.fr3');
  end
  // Hoja A4 estándar (210x297 mm)
  else if (LMinDim = 210) and (LMaxDim = 297) then
  begin
    if LIsLandscape then
      Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_A4_H.fr3')
    else
      Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_A4_V.fr3');
  end
  // Hoja A5 estándar (148x210 mm)
  else if (LMinDim = 148) and (LMaxDim = 210) then
  begin
    if LIsLandscape then
      Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_A5_H.fr3')
    else
      Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_A5_V.fr3');
  end
  else
  begin
    Result := TFormatosImpresionService.ResolverRutaArchivo('TextoLibre_Generico.fr3');
  end;
end;

procedure TfrmImprimirTextoLibre.PrepararReporteFastReport(AReport: TfrxReport);
var
  LF: TFormatoTextoItem;
  LPage: TfrxReportPage;
  LMemo: TfrxMemoView;
  LTitleBand: TfrxReportTitle;
  LFontSizePt: Integer;
  LAnchoMM, LAltoMM: Double;
  LMinDim, LMaxDim: Integer;
  LReportFile: string;
  i: Integer;
  LUsableW_Px, LUsableH_Px: Extended;
begin
  LF := GetSelectedFormato;
  if not Assigned(LF) then
    raise Exception.Create('Debe seleccionar un formato de impresión.');

  AReport.Clear;

  // 1. Cargar plantilla .fr3 correspondiente al formato
  LPage := nil;
  LReportFile := ResolverArchivoPlantilla(LF);
  if (LReportFile <> '') and FileExists(LReportFile) then
  begin
    AReport.LoadFromFile(LReportFile);
    for i := 0 to AReport.PagesCount - 1 do
    begin
      if AReport.Pages[i] is TfrxReportPage then
      begin
        LPage := TfrxReportPage(AReport.Pages[i]);
        Break;
      end;
    end;
  end;

  // Si por alguna razón no cargó la página del .fr3, crearla dinámicamente
  if not Assigned(LPage) then
  begin
    LPage := TfrxReportPage.Create(AReport);
    LPage.CreateUniqueName;
  end;

  // 2. Ajustar dimensiones físicas del papel y orientación exacta
  LMinDim := Round(Min(LF.AnchoMM, LF.AltoMM));
  LMaxDim := Round(Max(LF.AnchoMM, LF.AltoMM));

  if SameText(LF.Orientacion, 'HORIZONTAL') then
  begin
    LAnchoMM := Max(LF.AnchoMM, LF.AltoMM);
    LAltoMM := Min(LF.AnchoMM, LF.AltoMM);
    LPage.Orientation := poLandscape;
  end
  else
  begin
    LAnchoMM := Min(LF.AnchoMM, LF.AltoMM);
    LAltoMM := Max(LF.AnchoMM, LF.AltoMM);
    LPage.Orientation := poPortrait;
  end;

  // Asignar PaperSize según dimensiones estándar o DMPAPER_USER (256)
  if SameText(LF.Tipo, 'HOJA') and (LMinDim = 210) and (LMaxDim = 297) then
    LPage.PaperSize := DMPAPER_A4
  else if SameText(LF.Tipo, 'HOJA') and (LMinDim = 148) and (LMaxDim = 210) then
    LPage.PaperSize := DMPAPER_A5
  else
    LPage.PaperSize := 256; // DMPAPER_USER para etiquetas y tamaños personalizados

  // Para formatos estándar (A4/A5), FastReport ya calcula automáticamente PaperWidth y PaperHeight
  // según Orientation. NO reasignar PaperWidth ni PaperHeight si PaperSize es DMPAPER_A4 o DMPAPER_A5,
  // porque reasignarlos hace que FastReport mute internamente PaperSize a 256 (DMPAPER_USER),
  // provocando que las impresoras físicas PCL6 / Sharp ignoren la orientación Landscape y corten la hoja.
  if LPage.PaperSize = 256 then
  begin
    LPage.PaperWidth := LAnchoMM;
    LPage.PaperHeight := LAltoMM;
  end;

  // 3. Aplicar márgenes configurados por el usuario
  LPage.LeftMargin := seMargenIzq.Value;
  LPage.RightMargin := seMargenDer.Value;
  LPage.TopMargin := seMargenSup.Value;
  LPage.BottomMargin := seMargenInf.Value;

  // Área útil en píxeles de FastReport (1 mm = fr01cm), restando 2 px de margen técnico para evitar saltos de página espurios
  LUsableW_Px := (LPage.PaperWidth - LPage.LeftMargin - LPage.RightMargin) * fr01cm;
  LUsableH_Px := (LPage.PaperHeight - LPage.TopMargin - LPage.BottomMargin) * fr01cm - 2;
  if LUsableH_Px < 10 then LUsableH_Px := 10;

  // 4. Buscar o ajustar la banda ReportTitle
  LTitleBand := nil;
  for i := 0 to LPage.AllObjects.Count - 1 do
  begin
    if TObject(LPage.AllObjects[i]) is TfrxReportTitle then
    begin
      LTitleBand := TfrxReportTitle(TObject(LPage.AllObjects[i]));
      Break;
    end;
  end;

  if Assigned(LTitleBand) then
  begin
    LTitleBand.Left := 0;
    LTitleBand.Top := 0;
    LTitleBand.Width := LUsableW_Px;
    LTitleBand.Height := LUsableH_Px;
  end;

  // 5. Localizar el MemoView de la plantilla (dentro de la banda o página) o crearlo si no estuviera
  LMemo := nil;
  if AReport.FindObject('MemoTextoLibre') is TfrxMemoView then
    LMemo := TfrxMemoView(AReport.FindObject('MemoTextoLibre'));

  if not Assigned(LMemo) then
  begin
    for i := 0 to LPage.AllObjects.Count - 1 do
    begin
      if TObject(LPage.AllObjects[i]) is TfrxMemoView then
      begin
        LMemo := TfrxMemoView(TObject(LPage.AllObjects[i]));
        Break;
      end;
    end;
  end;

  if not Assigned(LMemo) then
  begin
    if Assigned(LTitleBand) then
      LMemo := TfrxMemoView.Create(LTitleBand)
    else
      LMemo := TfrxMemoView.Create(LPage);
    LMemo.CreateUniqueName;
  end;

  // Ajustar posición y tamaño del MemoView para que cubra exactamente el área útil
  LMemo.Left := 0;
  LMemo.Top := 0;
  LMemo.Width := LUsableW_Px;
  LMemo.Height := LUsableH_Px;
  LMemo.WordWrap := True;
  LMemo.AutoWidth := False;
  LMemo.VAlign := vaCenter;
  LMemo.AllowExpressions := False;

  // Alineación horizontal
  if btnAlinearCentro.Down then
    LMemo.HAlign := haCenter
  else if btnAlinearDer.Down then
    LMemo.HAlign := haRight
  else if btnAlinearJustificado.Down then
    LMemo.HAlign := haBlock
  else
    LMemo.HAlign := haLeft;

  // Tipografía y estilos
  LMemo.Font.Name := cboFuentes.Text;
  if LMemo.Font.Name = '' then LMemo.Font.Name := 'Segoe UI';
  LMemo.Font.Style := ObtenerEstilosFuente;

  if chkAutoAjuste.Checked then
  begin
    CalcularTamanoOptimoFuente(LFontSizePt);
    LMemo.Font.Size := LFontSizePt;
  end
  else
  begin
    LMemo.Font.Size := seTamanoFuente.Value;
  end;

  AReport.Variables['TextoImprimir'] := QuotedStr(mmoTexto.Text);
  LMemo.Text := mmoTexto.Text;
end;

procedure TfrmImprimirTextoLibre.btnPrevisualizarClick(Sender: TObject);
var
  LReport: TfrxReport;
  LF: TFormatoTextoItem;
  LOrientation: TPrinterOrientation;
  LAnchoDef, LAltoDef: Double;
  LPaperSize: Integer;
begin
  LF := GetSelectedFormato;
  if Assigned(LF) and SameText(LF.Orientacion, 'HORIZONTAL') then
  begin
    LOrientation := TPrinterOrientation.poLandscape;
    LAnchoDef := Max(LF.AnchoMM, LF.AltoMM);
    LAltoDef := Min(LF.AnchoMM, LF.AltoMM);
  end
  else
  begin
    LOrientation := TPrinterOrientation.poPortrait;
    if Assigned(LF) then
    begin
      LAnchoDef := Min(LF.AnchoMM, LF.AltoMM);
      LAltoDef := Max(LF.AnchoMM, LF.AltoMM);
    end
    else
    begin
      LAnchoDef := 210;
      LAltoDef := 297;
    end;
  end;

  if Assigned(LF) and SameText(LF.Tipo, 'HOJA') and (Round(Min(LF.AnchoMM, LF.AltoMM)) = 210) and (Round(Max(LF.AnchoMM, LF.AltoMM)) = 297) then
    LPaperSize := DMPAPER_A4
  else if Assigned(LF) and SameText(LF.Tipo, 'HOJA') and (Round(Min(LF.AnchoMM, LF.AltoMM)) = 148) and (Round(Max(LF.AnchoMM, LF.AltoMM)) = 210) then
    LPaperSize := DMPAPER_A5
  else
    LPaperSize := 256;

  LReport := TfrxReport.Create(nil);
  try
    PrepararReporteFastReport(LReport);

    // Enlazar eventos para cuando el usuario imprima desde el botón de la previsualización
    LReport.OnPrintReport := ReportPrintReport;
    LReport.OnPrintPage := ReportPrintPage;
    SincronizarImpresoraFastReport(LReport, LOrientation, LAnchoDef, LAltoDef, LPaperSize, seCopias.Value);

    LReport.PreviewOptions.Modal := True;
    LReport.ShowReport(True);
  finally
    LReport.Free;
  end;
end;

procedure TfrmImprimirTextoLibre.SincronizarImpresoraFastReport(AReport: TfrxReport;
  AOrientation: TPrinterOrientation; APaperWidth, APaperHeight: Double;
  APaperSize: Integer; ACopies: Integer);
var
  LFrPrn: TfrxPrinters;
  LPrn: TfrxCustomPrinter;
  LFrxPrn: TfrxPrinter;
  LHPrn: THandle;
  LDmOrient: WORD;
  LDevModeSize: Integer;
  pDevModeTemp: PDeviceModeW;
  Device, Driver, Port: array[0..255] of Char;
  hVclDevMode: THandle;
  pVclDevMode: PDeviceMode;
begin
  if AOrientation = poLandscape then
    LDmOrient := DMORIENT_LANDSCAPE
  else
    LDmOrient := DMORIENT_PORTRAIT;

  // 1. Sincronizar el subsistema VCL Printers global
  try
    if Printer.Printers.Count > 0 then
    begin
      Printer.GetPrinter(Device, Driver, Port, hVclDevMode);
      if hVclDevMode <> 0 then
      begin
        pVclDevMode := GlobalLock(hVclDevMode);
        if pVclDevMode <> nil then
        try
          pVclDevMode^.dmOrientation := LDmOrient;
          pVclDevMode^.dmFields := pVclDevMode^.dmFields or DM_ORIENTATION;
          if APaperSize in [DMPAPER_A4, DMPAPER_A5] then
          begin
            pVclDevMode^.dmPaperSize := APaperSize;
            pVclDevMode^.dmFields := pVclDevMode^.dmFields or DM_PAPERSIZE;
          end;
        finally
          GlobalUnlock(hVclDevMode);
        end;
        Printer.SetPrinter(Device, Driver, Port, hVclDevMode);
      end;
      Printer.Orientation := AOrientation;
    end;
  except
  end;

  // 2. Si se proporciona AReport, seleccionar su impresora
  if Assigned(AReport) then
  begin
    try
      AReport.SelectPrinter;
    except
    end;
  end;

  // 3. Sincronizar frxPrinters
  try
    LFrPrn := frxPrinters;
    if Assigned(LFrPrn) and Assigned(LFrPrn.Printer) then
    begin
      LPrn := LFrPrn.Printer;

      // Actualizar parámetros lógicos en FastReport
      try
        LPrn.SetPrintParams(APaperSize, APaperWidth, APaperHeight, AOrientation, 0, 0, ACopies);
      except
      end;

      // 4. Sincronizar a nivel de driver físico (DEVMODE de Windows y extensiones privadas de PCL6/Sharp)
      if (LPrn is TfrxPrinter) and Assigned(TfrxPrinter(LPrn).DeviceMode) then
      begin
        LFrxPrn := TfrxPrinter(LPrn);

        // Abrir la impresora física en Windows Spooler
        if OpenPrinter(PChar(LPrn.Name), LHPrn, nil) then
        begin
          try
            // Consultar el tamaño total de la estructura DEVMODE que requiere este driver (incluye dmDriverExtra)
            LDevModeSize := DocumentProperties(0, LHPrn, PChar(LPrn.Name), PDeviceMode(nil)^, PDeviceMode(nil)^, 0);
            if LDevModeSize > 0 then
            begin
              GetMem(pDevModeTemp, LDevModeSize);
              try
                // Obtener configuración actual del driver
                DocumentProperties(0, LHPrn, PChar(LPrn.Name), pDevModeTemp^, PDeviceMode(nil)^, DM_OUT_BUFFER);

                // Modificar orientación y tamaño
                pDevModeTemp^.dmOrientation := LDmOrient;
                pDevModeTemp^.dmFields := pDevModeTemp^.dmFields or DM_ORIENTATION;

                if APaperSize in [DMPAPER_A4, DMPAPER_A5] then
                begin
                  pDevModeTemp^.dmPaperSize := APaperSize;
                  pDevModeTemp^.dmPaperWidth := 0;
                  pDevModeTemp^.dmPaperLength := 0;
                  pDevModeTemp^.dmFields := (pDevModeTemp^.dmFields or DM_PAPERSIZE)
                    and not (DM_PAPERWIDTH or DM_PAPERLENGTH);
                end
                else if APaperSize > 0 then
                begin
                  pDevModeTemp^.dmPaperSize := APaperSize;
                  pDevModeTemp^.dmPaperWidth := Round(APaperWidth * 10);
                  pDevModeTemp^.dmPaperLength := Round(APaperHeight * 10);
                  pDevModeTemp^.dmFields := pDevModeTemp^.dmFields or DM_PAPERSIZE or DM_PAPERWIDTH or DM_PAPERLENGTH;
                end;

                if ACopies > 0 then
                begin
                  pDevModeTemp^.dmCopies := ACopies;
                  pDevModeTemp^.dmFields := pDevModeTemp^.dmFields or DM_COPIES;
                end;

                // FUSIONAR con el driver: DocumentProperties actualiza toda la sección privada del driver (dmDriverExtra)
                DocumentProperties(0, LHPrn, PChar(LPrn.Name), pDevModeTemp^, pDevModeTemp^, DM_IN_BUFFER or DM_OUT_BUFFER);

                // Copiar la estructura completa y validada al DeviceMode de FastReport
                Move(pDevModeTemp^, LFrxPrn.DeviceMode^, LDevModeSize);
              finally
                FreeMem(pDevModeTemp);
              end;
            end
            else
            begin
              // Fallback directo sobre campos públicos
              LFrxPrn.DeviceMode^.dmOrientation := LDmOrient;
              LFrxPrn.DeviceMode^.dmFields := LFrxPrn.DeviceMode^.dmFields or DM_ORIENTATION;
              if APaperSize in [DMPAPER_A4, DMPAPER_A5] then
              begin
                LFrxPrn.DeviceMode^.dmPaperSize := APaperSize;
                LFrxPrn.DeviceMode^.dmFields := (LFrxPrn.DeviceMode^.dmFields or DM_PAPERSIZE) and not (DM_PAPERWIDTH or DM_PAPERLENGTH);
              end;
              DocumentProperties(0, LHPrn, PChar(LPrn.Name), LFrxPrn.DeviceMode^, LFrxPrn.DeviceMode^, DM_IN_BUFFER or DM_OUT_BUFFER);
            end;
          finally
            ClosePrinter(LHPrn);
          end;
        end;

        // Asegurar campos públicos en FastReport
        LFrxPrn.DeviceMode^.dmOrientation := LDmOrient;
        LFrxPrn.DeviceMode^.dmFields := LFrxPrn.DeviceMode^.dmFields or DM_ORIENTATION;
        if APaperSize in [DMPAPER_A4, DMPAPER_A5] then
        begin
          LFrxPrn.DeviceMode^.dmPaperSize := APaperSize;
          LFrxPrn.DeviceMode^.dmFields := (LFrxPrn.DeviceMode^.dmFields or DM_PAPERSIZE) and not (DM_PAPERWIDTH or DM_PAPERLENGTH);
        end;

        // Recrear el DC de la impresora en FastReport con el nuevo DEVMODE
        try
          LFrxPrn.RecreateDC;
        except
        end;

        // Reconfirmar parámetros en FastReport
        try
          LFrxPrn.SetPrintParams(APaperSize, APaperWidth, APaperHeight, AOrientation, 0, 0, ACopies);
        except
        end;
      end;
    end;
  except
  end;
end;

procedure TfrmImprimirTextoLibre.ReportPrintReport(Sender: TObject);
var
  LF: TFormatoTextoItem;
  LOrientation: TPrinterOrientation;
  LAncho, LAlto: Double;
  LPaperSize: Integer;
  i: Integer;
  LRep: TfrxReport;
begin
  LF := GetSelectedFormato;
  if Assigned(LF) and SameText(LF.Orientacion, 'HORIZONTAL') then
  begin
    LOrientation := poLandscape;
    LAncho := Max(LF.AnchoMM, LF.AltoMM);
    LAlto := Min(LF.AnchoMM, LF.AltoMM);
  end
  else
  begin
    LOrientation := poPortrait;
    if Assigned(LF) then
    begin
      LAncho := Min(LF.AnchoMM, LF.AltoMM);
      LAlto := Max(LF.AnchoMM, LF.AltoMM);
    end
    else
    begin
      LAncho := 210;
      LAlto := 297;
    end;
  end;

  if Assigned(LF) and SameText(LF.Tipo, 'HOJA') and (Round(Min(LF.AnchoMM, LF.AltoMM)) = 210) and (Round(Max(LF.AnchoMM, LF.AltoMM)) = 297) then
    LPaperSize := DMPAPER_A4
  else if Assigned(LF) and SameText(LF.Tipo, 'HOJA') and (Round(Min(LF.AnchoMM, LF.AltoMM)) = 148) and (Round(Max(LF.AnchoMM, LF.AltoMM)) = 210) then
    LPaperSize := DMPAPER_A5
  else
    LPaperSize := 256;

  if Sender is TfrxReport then
  begin
    LRep := TfrxReport(Sender);
    if Assigned(LRep.PreviewPages) and (LRep.PreviewPages is TfrxPreviewPages) then
    begin
      for i := 0 to LRep.PreviewPages.Count - 1 do
        TfrxPreviewPages(LRep.PreviewPages).UpdatePageDimension(i, LAncho, LAlto, LOrientation);
    end;
    SincronizarImpresoraFastReport(LRep, LOrientation, LAncho, LAlto, LPaperSize, seCopias.Value);
  end
  else
    SincronizarImpresoraFastReport(nil, LOrientation, LAncho, LAlto, LPaperSize, seCopias.Value);
end;

procedure TfrmImprimirTextoLibre.ReportPrintPage(Page: TfrxReportPage; CopyNo: Integer);
var
  LF: TFormatoTextoItem;
  LOrientation: TPrinterOrientation;
  LAncho, LAlto: Double;
  LPaperSize: Integer;
begin
  LF := GetSelectedFormato;
  if Assigned(LF) and SameText(LF.Orientacion, 'HORIZONTAL') then
  begin
    LOrientation := poLandscape;
    LAncho := Max(LF.AnchoMM, LF.AltoMM);
    LAlto := Min(LF.AnchoMM, LF.AltoMM);
  end
  else
  begin
    LOrientation := poPortrait;
    if Assigned(LF) then
    begin
      LAncho := Min(LF.AnchoMM, LF.AltoMM);
      LAlto := Max(LF.AnchoMM, LF.AltoMM);
    end
    else
    begin
      LAncho := 210;
      LAlto := 297;
    end;
  end;

  if Assigned(LF) and SameText(LF.Tipo, 'HOJA') and (Round(Min(LF.AnchoMM, LF.AltoMM)) = 210) and (Round(Max(LF.AnchoMM, LF.AltoMM)) = 297) then
    LPaperSize := DMPAPER_A4
  else if Assigned(LF) and SameText(LF.Tipo, 'HOJA') and (Round(Min(LF.AnchoMM, LF.AltoMM)) = 148) and (Round(Max(LF.AnchoMM, LF.AltoMM)) = 210) then
    LPaperSize := DMPAPER_A5
  else
    LPaperSize := 256;

  if Assigned(Page) then
  begin
    Page.Orientation := LOrientation;
    Page.PaperSize := LPaperSize;
    if LPaperSize = 256 then
    begin
      Page.PaperWidth := LAncho;
      Page.PaperHeight := LAlto;
    end;
  end;

  SincronizarImpresoraFastReport(nil, LOrientation, LAncho, LAlto, LPaperSize, seCopias.Value);
end;

procedure TfrmImprimirTextoLibre.btnImprimirClick(Sender: TObject);
var
  LReport: TfrxReport;
  NumCopias: Integer;
  LF: TFormatoTextoItem;
  LOrientation: TPrinterOrientation;
  i: Integer;
  LPrepPage: TfrxReportPage;
  LAnchoDef, LAltoDef: Double;
  LPaperSize: Integer;
begin
  LF := GetSelectedFormato;
  NumCopias := seCopias.Value;
  if NumCopias < 1 then NumCopias := 1;

  if Assigned(LF) and SameText(LF.Orientacion, 'HORIZONTAL') then
  begin
    LOrientation := TPrinterOrientation.poLandscape;
    LAnchoDef := Max(LF.AnchoMM, LF.AltoMM);
    LAltoDef := Min(LF.AnchoMM, LF.AltoMM);
  end
  else
  begin
    LOrientation := TPrinterOrientation.poPortrait;
    if Assigned(LF) then
    begin
      LAnchoDef := Min(LF.AnchoMM, LF.AltoMM);
      LAltoDef := Max(LF.AnchoMM, LF.AltoMM);
    end
    else
    begin
      LAnchoDef := 210;
      LAltoDef := 297;
    end;
  end;

  if Assigned(LF) and SameText(LF.Tipo, 'HOJA') and (Round(Min(LF.AnchoMM, LF.AltoMM)) = 210) and (Round(Max(LF.AnchoMM, LF.AltoMM)) = 297) then
    LPaperSize := DMPAPER_A4
  else if Assigned(LF) and SameText(LF.Tipo, 'HOJA') and (Round(Min(LF.AnchoMM, LF.AltoMM)) = 148) and (Round(Max(LF.AnchoMM, LF.AltoMM)) = 210) then
    LPaperSize := DMPAPER_A5
  else
    LPaperSize := 256;

  LReport := TfrxReport.Create(nil);
  try
    PrepararReporteFastReport(LReport);

    // Enlazar eventos para interceptar la orden de imprimir antes de que WinSpool inicie StartDoc
    LReport.OnPrintReport := ReportPrintReport;
    LReport.OnPrintPage := ReportPrintPage;

    // 1. Sincronizar impresora FastReport ANTES de abrir el diálogo de impresión
    SincronizarImpresoraFastReport(LReport, LOrientation, LAnchoDef, LAltoDef, LPaperSize, NumCopias);

    LReport.PrintOptions.Copies := NumCopias;
    LReport.PrintOptions.ShowDialog := True;

    // 2. Compilar páginas
    LReport.PrepareReport(True);

    // 3. Garantizar orientación en todas las páginas generadas en el búfer
    if Assigned(LReport.PreviewPages) then
    begin
      for i := 0 to LReport.PreviewPages.Count - 1 do
      begin
        LPrepPage := LReport.PreviewPages.Page[i];
        if Assigned(LPrepPage) then
        begin
          LPrepPage.Orientation := LOrientation;
          LPrepPage.PaperSize := LPaperSize;
          if LPaperSize = 256 then
          begin
            LPrepPage.PaperWidth := LAnchoDef;
            LPrepPage.PaperHeight := LAltoDef;
          end;
        end;
        if LReport.PreviewPages is TfrxPreviewPages then
          TfrxPreviewPages(LReport.PreviewPages).UpdatePageDimension(i, LAnchoDef, LAltoDef, LOrientation);
      end;
    end;

    // 4. Sincronizar de nuevo antes de llamar a Print por si PrepareReport reseteó algo
    SincronizarImpresoraFastReport(LReport, LOrientation, LAnchoDef, LAltoDef, LPaperSize, NumCopias);

    // 5. Enviar trabajo de impresión
    LReport.Print;
  finally
    LReport.Free;
  end;
end;

end.
