How to set filename when printing to “Microsoft print to PDF” in delphi

前端 未结 2 1131
礼貌的吻别
礼貌的吻别 2021-01-06 02:49

I am trying to set the filename when printing to PDF. Setting (Printers.pas) Printer.Title works to default the PDF filename for most PDF printing engines (Adobe, CutePDF),

相关标签:
2条回答
  • 2021-01-06 02:57

    You can set the output path if you do printing without vcl. That means you have to use the DOCINFO structure, named TDocInfo from the WinApi.Windows unit. I've sligtly adapted the official example from Embarcadero:

    procedure TForm1.Button1Click(Sender: TObject);
    var
      Pd : TPrintDlg;
      DocInfo: TDocInfo;
    const
      DOC_NAME = 'Stack Overflow';
      FILE_NAME = 'C:\temp\print\SO.pdf';
      MAX_PATH = 260;
    begin
      Pd := default(TPrintDlg);
      Pd.lStructSize := sizeof(Pd);
      Pd.hWndOwner := Form1.Handle;
      Pd.Flags := PD_RETURNDC;
      if PrintDlg(pd) then begin
        DocInfo := Default(TDocInfo);
        DocInfo.cbSize := SizeOf(DocInfo);
        DocInfo.lpszDocName := StrAllocW(32);
        DocInfo.lpszOutput := StrAllocW(MAX_PATH);
        lStrCpynW(DocInfo.lpszDocName, DOC_NAME, Length(DOC_NAME) * sizeof(char));
        lStrCpynW(DocInfo.lpszOutput, FILE_NAME, Length(FILE_NAME) * sizeof(char));
        StartDoc(Pd.hDc, DocInfo);
        StartPage(Pd.hDc);
        TextOut(Pd.hDc, 100, 100, 'Page 1', 6);
        EndPage(Pd.hDc);
        StartPage(Pd.hDc);
        TextOut(Pd.hDc, 100, 100, 'Page 2', 6);
        EndPage(Pd.hDc);
        EndDoc(Pd.hDc);
        StrDisposeW(DocInfo.lpszDocName);
        StrDisposeW(DocInfo.lpszOutput);
      end;
    end;
    

    Setting lpszOutput enables you to set the output file name if you select "Microsoft Print To Pdf" as printer.

    0 讨论(0)
  • 2021-01-06 03:02

    You can try.

    var
      DeviceMode: THandle;
      Device, Driver, Port: array[0..80] of Char;
    begin
      Printer.PrinterIndex := Printer.Printers.IndexOf('Microsoft Print to PDF');
      Printer.GetPrinter(Device, Driver, Port, DeviceMode);
      Printer.SetPrinter(Device, Driver, 'C:\Temp\Test.pdf', 0);
    
      Printer.BeginDoc;
      Printer.Canvas.TextOut(100, 100, 'Test');
      Printer.EndDoc;
    end;
    
    0 讨论(0)
提交回复
热议问题