Nous avons été contactés à plusieurs reprises par des développeurs PHP qui souhaitent utiliser un script PHP pour convertir automatiquement tous les documents d'un répertoire spécifique en fichiers PDF.

Pour illustrer cela, nous avons créé un petit script PHP qui fait exactement cela. Plusieurs documents Word, Excel, image, texte et Powerpoint contenus dans un dossier d' entrée sont directement convertis en PDF à l'aide de l'API PDF de notre imprimante PDF à l'aide de PHP 7.

Lorsque vous exécutez le script PHP, le script recherche les fichiers dans le ..\input et les convertit en documents PDF dans le ..\output . En cas de problème, le document d'entrée est copié dans le dossier d'erreur. Si la conversion réussit, le document d'entrée est copié dans le dossier de sortie.

    <?php
    
    /*
    
    ++++++++++++++++++++++++++++++++++++++++++++++++++++
    Auto Convert Files in a folder using PHP 7 and a PDF Printer
    
    Date: 2018-11-28
    Author: T. Niebergall-Hodes, 7-PDF Germany
    
    (c) All rights reserved 2018
    ++++++++++++++++++++++++++++++++++++++++++++++++++++
    
    IMPORTANT:
    
    1. Be sure to use this PHP7 example on Windows. We use the .NET COM Assembly, so we need Windows!
    
    2. Be sure to have 7-PDF Printer installed first.
    
    3. Be sure that you have associated a Default Application for the following file types (BMP, DOCX, PPTX, XSLX, TXT) on your Windows System
       The default application will be used to print out the documents to the pdf printer...
       
    4. Be sure to have installed PHP 7 (recommended) and extracted it to C:\PHP7. 
    
    5. If necessary: You can use that public manual for some more informations installing PHP 7 on Windows: http://kizu514.com/blog/install-php7-and-composer-on-windows-10/
    
    6. Be sure to activate the following extension in PHP.ini extension=php_com_dotnet.dll !!!
    
    7. Put C:\PHP7 to your Path ENV_VAR if you like it a bit easier to run PHP from console 
    
    8. Run it on the windows shell (console) like:
    
    C:\PHP7\php.exe [PATH_ON_YOUR_SYSTEM]\Converter.php
    
    This example was tested with:
    
    PHP 7.2.12 (cli) (built: Nov  8 2018 05:47:24) ( NTS MSVC15 (Visual C++ 2017) x64 )
    Copyright (c) 1997-2018 The PHP Group
    Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    
    under Windows 10
    
    */
    
    $applicationFolder = realpath(dirname(__FILE__));
    
    $inputFolder = $applicationFolder . '\input';
    $outputFolder = $applicationFolder . '\output';
    $doneFolder = $applicationFolder . '\done';
    $errorFolder = $applicationFolder . '\errors';
    
    $printerUtil = new COM("Pdf7.PdfUtil") or die("Couldn't init Printer's Util COM Interface.");
    
    //Check that folders exist
    if (!is_dir($inputFolder)) mkdir($inputFolder);
    if (!is_dir($outputFolder)) mkdir($outputFolder);
    if (!is_dir($doneFolder)) mkdir($doneFolder);
    if (!is_dir($errorFolder)) mkdir($errorFolder);
    
    // Get the printer name
    $printerName = $printerUtil->DefaultPrinterName;
    
    // Get file names from input folder
    $inputFileNames = glob($inputFolder.'\*.*');
    
    foreach ($inputFileNames as $inputFileName) {
    $isError = false;
    $errorMessage = '';
    
    if (file_exists($inputFileName)) {
    echo "Printing {$inputFileName}...";
    $outputFileName = $outputFolder . '\\' . basename($inputFileName) . '.pdf';
    
    //Init COM API of 7-PDF Printer
    $printerSettings = new COM("Pdf7.PdfSettings") or die("Couldn't init Printer's Settings COM Interface.");
    $printerSettings->PrinterName = $printerName;
    
    // Set the output file name
    $printerSettings->SetValue('Output', $outputFileName);
    
    // Disable all dialogs
    $printerSettings->SetValue('ShowSettings', 'never');
    $printerSettings->SetValue('ShowSaveAS', 'never');
    $printerSettings->SetValue('ShowProgress', 'no');
    $printerSettings->SetValue('ShowProgressFinished', 'no');
    $printerSettings->SetValue('ShowPDF', 'no');
    $printerSettings->SetValue('ConfirmOverwrite', 'no');
    
    // Get the name of a status file and delete it if it already exist
    //First, get Users Temp Folder
    exec('echo %Temp%' , $outputENV);
    $statusFileName = $outputENV[0];
    $statusFileName =  $statusFileName . '\converter_status.ini';
    //echo $statusFileName . "\n";
    if (file_exists($statusFileName)) unlink ($statusFileName);
    
    // Make the printer write a status file
    $printerSettings->SetValue('StatusFile', $statusFileName);
    
    // Write the settings to the printer
    $isRunOnce = true;
    $printerSettings->WriteSettings($isRunOnce) . "\n";
    
    try {
    
    // Print the file using the associated program for the specific file type
    $printerUtil->PrintFile($inputFileName, $printerName);
    
    // Wait for the status file to appear. This means that the print has finished
    $printerUtil->WaitForFile($statusFileName, 60000);
    
    // Check if output file exists
    $isError = !file_exists($outputFileName);
    
    } catch (Exception $ex) {
    $isError = true;
                $errorMessage = $ex->getMessage() . "\n";
    }
    
    // Move the input file
            if ($isError){
    rename($inputFileName, $errorFolder . '\\' . basename($inputFileName));
            }
    else{
    rename($inputFileName, $doneFolder . '\\' . basename($inputFileName));
    }
    
    // Write a status
    if ($isError){
    echo $errorMessage;
            }
            else{
    echo "Done\n";
    }
    }
    }
    
    //Close Printer 
    $printerSettings = null;
    $printerUtil = null;
    
    ?>
    

Des exemples de fichiers source sont inclus dans le fichier ZIP ci-dessous, qui peut être téléchargé ici.

Téléchargements

appendice taille
Téléchargez l'exemple 73.6 KB

Top