PDF Fundamentals

Exporting a report to a PDF file using the built-in PDF device is very simple using ReportBuilder.

  1. Setting the TppReport.AllowPrintToFile property to True will enable the Print To File section of the Print Dialog.  From there the PDF file type can be selected as well as a custom file name before the report is exported.
  2. Exporting directly to PDF can be done by setting the TppReport.DeviceType to “PDF”, assigning the TppReport.TextFileName property, and calling Report.Print.  Set the ShowPrintDialog property to False to export directly.

Exporting directly to a stream is also possible and can be useful if the output is needed in memory rather than on the hard disk.  This can be done by manually assigning the TppPDFDevice.OutputStream property to a newly created TStream descendent (TMemoryStream).  See the example below on how this can be done.

Use the TppReport.PDFSettings properties to manage and control the PDF file created.  Some useful features include:

  • CompressionLevel: Higher compression will save space however the PDF may take longer to generate.
  • OpenPDFFile: Automatically open the PDF file using your default viewer (Acrobat) after it has been generated.
  • ScaleImages: Smaller images are scaled to reduce size.
  • EmbedFonts: Fonts used are embedded into the PDF file preventing the need to have them installed on another computer to be seen correctly.

Download: PDFDevice.zip

Sample Delphi code:

Export PDF to file in code:

procedure TForm1.btnPrintClick(Sender: TObject);
begin

  ppReport1.AllowPrintToFile := True;
  ppReport1.ShowPrintDialog := False;
  ppReport1.DeviceType := dtPDF;

  ppReport1.PDFSettings.Author := 'ReportBuilder';
  ppReport1.PDFSettings.Title := 'Export to PDF Demo';
  ppReport1.PDFSettings.OpenPDFFile := True;

  ppReport1.TextFileName := 'C:\MyPDFFile.pdf';

  ppReport1.Print;

end;

Export PDF to stream in code:

procedure TPDFFrm.btnGenerateClick(Sender: TObject);
var
  lPDFDevice: TppPDFDevice;
begin

  // delete existing file
  if FileExists(ppReport1.TextFileName) then
    DeleteFile(ppReport1.TextFileName);


  // creat and configure the PDFDevice
  lPDFDevice := TppPDFDevice.Create(nil);

  if (FOutputStream = nil) then
    FOutputStream := TMemoryStream.Create
  else
    FOutputStream.Clear;

  try
    lPDFDevice.PDFSettings := ppReport1.PDFSettings;
    lPDFDevice.OutputStream := FOutputStream;        // assign output stream
    lPDFDevice.Publisher := ppReport1.Publisher;

    // generate the report
    ppReport1.PrintToDevices;

    btnSaveToFile.Enabled := True;

  finally
    lPDFDevice.Free;
  end;

end;