Unit MainForm;

{$I ..\..\..\Lib\PDFlibDefines.inc}

Interface

Uses
{$IFDEF XE2+}
  Winapi.Windows,
  System.Classes,
  System.SysUtils,
  System.StrUtils,
  Vcl.Controls,
  Vcl.StdCtrls,
  Winapi.ShellAPI,
  Vcl.Forms,
  Vcl.Dialogs,
{$ELSE}
  Windows,
  Classes,
  StrUtils,
  SysUtils,
  Controls,
  StdCtrls,
  ShellAPI,
  Forms,
  Dialogs,
{$ENDIF}
  BrowseFolder,
  PDFlibrary;

Type
  TForm1 = Class(TForm)
    btnMerge: TButton;
    btnConvertImages: TButton;
    linkLabel1: TLabel;
    listBoxImages: TListBox;
    btnLoadImage: TButton;
    btnRemoveImage: TButton;
    btnOutputFolder: TButton;
    textBoxSaveFiles: TEdit;
    Procedure linkLabel1Click(Sender: TObject);
    Procedure FormCreate(Sender: TObject);
    Procedure btnLoadImageClick(Sender: TObject);
    Procedure btnRemoveImageClick(Sender: TObject);
    Procedure btnMergeClick(Sender: TObject);
    Procedure btnConvertImagesClick(Sender: TObject);
    Procedure btnOutputFolderClick(Sender: TObject);
    Procedure FormShow(Sender: TObject);
  Private
    { Private declarations }
  Public
    { Public declarations }
  End;

Var
  Form1: TForm1;

Implementation

{$R *.dfm}

Procedure updateButtons;
Begin
  With Form1 Do
  Begin
    If listBoxImages.Count = 0 Then
    Begin
      btnMerge.Enabled := False;
      btnConvertImages.Enabled := False;
    End
    Else
    Begin
      btnMerge.Enabled := True;
      btnConvertImages.Enabled := True;
    End;
  End;
End;

Procedure TForm1.btnConvertImagesClick(Sender: TObject);
Var
  i, imageID, lWidth, lHeight: Integer;
  bFail: Boolean;
  sPDFFileName: String;
Begin

  // Check to see that user actually has any items in the list
  If (listBoxImages.Items.Count < 1) Then
  Begin
    MessageBox(Handle, 'Please add images to the list and try again.', 'Error:', MB_OK or MB_ICONSTOP);
    Abort;
  End;

  // Instantiate a PDFlibrary Object
  With TPDFlib.Create Do // A document is created automatically upon creation
    Try
      // Iterate through each image filename in the list box
      bFail := False;
      For i := 0 To listBoxImages.Items.Count - 1 Do
      Begin
        // Create a blank document
        NewDocument();

        // Load the image into memory
        if (lowercase(RightStr(listBoxImages.Items.Strings[i], 3)) = 'png') then
          imageID := AddImageFromFile(listBoxImages.Items.Strings[i], 6)
        else
          imageID := AddImageFromFile(listBoxImages.Items.Strings[i], 1);

        If imageID = 0 Then
        Begin
          MessageBox(Handle, PChar('PDF library was unable to load "' + listBoxImages.Items.Strings[i] + '".'), 'Error:', MB_OK or MB_ICONSTOP);
          bFail := True;
          Abort;
        End;

        // Get width, height of image
        lWidth := ImageWidth;
        lHeight := ImageHeight;
        If (SetPageDimensions(lWidth, lHeight) = 0) Then
        Begin
          MessageBox(Handle, PChar('PDF library was unable to process the page dimensions for "' + listBoxImages.Items.Strings[i] + '".'), 'Error:',
            MB_OK or MB_ICONSTOP);
          bFail := True;
          Abort;
        End;

        // Draw the image onto the document using the specified width/height
        If (DrawImage(0, lHeight, lWidth, lHeight) = 0) Then
        Begin
          MessageBox(Handle, PChar('PDF library was unable to redraw the image "' + listBoxImages.Items.Strings[i] + '" as a PDF file.'), 'Error:',
            MB_OK or MB_ICONSTOP);
          bFail := True;
          Abort;
        End;

        // Then do so using a .PDF extension instead of the image filename
        // in the output folder...
        sPDFFileName := IncludeTrailingPathDelimiter(textBoxSaveFiles.Text) + ExtractFileName(listBoxImages.Items.Strings[i]);
        If Length(ExtractFileExt(listBoxImages.Items.Strings[i])) > 0 Then
          sPDFFileName := StringReplace(sPDFFileName, ExtractFileExt(listBoxImages.Items.Strings[i]), '.pdf', [rfIgnoreCase])
        Else
          sPDFFileName := sPDFFileName + '.pdf';

        If (SaveToFile(sPDFFileName) = 0) Then
        Begin
          MessageBox(Handle, PChar('PDF library could not save the image "' + listBoxImages.Items.Strings[i] + '" as a PDF file.'), 'Error:',
            MB_OK or MB_ICONSTOP);
          bFail := True;
          Abort;
        End;
      End;

    Finally
      Free;
    End;

  If (not bFail) Then
    MessageBox(Handle, PChar('The image(s) have been successfully converted to PDF.'), 'Information:', MB_OK or MB_ICONINFORMATION)
  Else
    MessageBox(Handle, PChar('There was an error converting some images.'), 'Error:', MB_OK or MB_ICONSTOP);

End;

Procedure TForm1.btnLoadImageClick(Sender: TObject);
Var
  openDialog: TOpenDialog; // Open dialog variable
  i: Integer;
Begin
  openDialog := TOpenDialog.Create(self);
  openDialog.InitialDir := ExtractFilePath(ParamStr(0));
  openDialog.Options := [ofAllowMultiSelect];
  openDialog.Filter := 'Image Files (JPEG,GIF,BMP,PNG,WMF,EMF,TIFF)|*.jpg;*.jpeg;*.gif;*.bmp;*.png;*.tiff;*.wmf;*.emf';
  openDialog.FilterIndex := 8;
  If openDialog.Execute() Then
  Begin
    For i := 0 To openDialog.Files.Count - 1 Do
      listBoxImages.Items.Add(openDialog.Files[i]);
    updateButtons;
  End;
  openDialog.Free;
End;

Procedure TForm1.btnMergeClick(Sender: TObject);
Var
  i, iDocID, iNewDocID: Integer;
  imageID, lWidth, lHeight: Integer;
  bFail: Boolean;
Begin

  If (listBoxImages.Items.Count < 2) Then
  Begin
    MessageBox(Handle, 'You need at least 2 images in order to convert and merge.', 'Error:', MB_OK or MB_ICONSTOP);
    Abort;
  End;

  // Instantiate a PDFlibrary Object
  With TPDFlib.Create Do // A document is created automatically upon creation
    Try
      iDocID := SelectedDocument; // Get the ID of the first document

      // Iterate through each image filename in the listbox
      bFail := False;
      For i := 0 To listBoxImages.Items.Count - 1 Do
      Begin
        // Create a blank document
        iNewDocID := NewDocument;

        // Load the image into memory
        if (lowercase(RightStr(listBoxImages.Items.Strings[i], 3)) = 'png') then
          imageID := AddImageFromFile(listBoxImages.Items.Strings[i], 6)
        else
          imageID := AddImageFromFile(listBoxImages.Items.Strings[i], 1);

        If imageID = 0 Then
        Begin
          MessageBox(Handle, PChar('PDF library was unable to load "' + listBoxImages.Items.Strings[i] + '".'), 'Error:', MB_OK or MB_ICONSTOP);
          bFail := True;
          Abort;
        End;

        // Get width, height of image
        lWidth := ImageWidth;
        lHeight := ImageHeight;
        If (SetPageDimensions(lWidth, lHeight) = 0) Then
        Begin
          MessageBox(Handle, PChar('PDF library was unable to process the page dimensions for "' + listBoxImages.Items.Strings[i] + '".'), 'Error:',
            MB_OK or MB_ICONSTOP);
          bFail := True;
          Abort;
        End;

        // Draw the image onto the document using the specified width/height
        If (DrawImage(0, lHeight, lWidth, lHeight) = 0) Then
        Begin
          MessageBox(Handle, PChar('PDF library was unable to redraw the image "' + listBoxImages.Items.Strings[i] + '" as a PDF file.'), 'Error:',
            MB_OK or MB_ICONSTOP);
          bFail := True;
          Abort;
        End;

        // Append the new document to the primary
        SelectDocument(iDocID);
        MergeDocument(iNewDocID);
        // Note: the merge function also deletes the new document
      End;
      // Delete the first page (blank) of the merged document as this was created by the first
      DeletePages(1, 1); // instance of PDFlibrary
      // Now all documents have been merged
      // with the primary document
      // So time to save it...
      If (SaveToFile(IncludeTrailingPathDelimiter(textBoxSaveFiles.Text) + 'merged.pdf') = 0) Then
      // Use the same folder, and a hard-coded filename
      Begin
        MessageBox(Handle, PChar('PDFlibrary could not save the combined image as a PDF file.'), 'Error:', MB_OK or MB_ICONSTOP);

        bFail := True;
        Abort;
      End;
    Finally
      Free;
    End;

  If (not bFail) Then
    MessageBox(Handle, PChar('Images have been successfully merged.'), 'Information:', MB_OK or MB_ICONINFORMATION)
  Else
    MessageBox(Handle, PChar('There was an error during merge the images.'), 'Error:', MB_OK or MB_ICONSTOP);

End;

Procedure TForm1.btnOutputFolderClick(Sender: TObject);
Var
  sFolder: String;
Begin
  sFolder := BrowseForFolder('', '', True);
  If (DirectoryExists(sFolder)) and (Length(Trim(sFolder)) > 0) Then
    textBoxSaveFiles.Text := sFolder;
End;

Procedure TForm1.btnRemoveImageClick(Sender: TObject);
Begin
  (*
    listBoxImages.Items.Remove(listBoxImages.SelectedItem);
  *)
  With listBoxImages Do
  Begin
    If ItemIndex > -1 Then
      Items.Delete(ItemIndex);
    updateButtons;
  End;

End;

Procedure TForm1.FormCreate(Sender: TObject);
Var
  crHand: HCURSOR;
Begin
  crHand := LoadCursor(0, IDC_HAND);
  If crHand <> 0 Then
    Screen.Cursors[crHandPoint] := crHand
  Else
    Screen.Cursors[crHandPoint] := crDefault;

  textBoxSaveFiles.Text := ExtractFilePath(ParamStr(0));
End;

Procedure TForm1.FormShow(Sender: TObject);
Begin
  updateButtons;
End;

Procedure TForm1.linkLabel1Click(Sender: TObject);
Begin
  ShellExecuteA(0, 'open', 'https://www.loslab.com/purchase/pdf-library', Nil, Nil, SW_SHOWNORMAL);
End;

End.
