Tuesday, October 1, 2024

Count PDF Pages in Folders and Subfolders with PHP

 Below php code provide list of all pdf files and page count under a folder or subfolder into a csv file.

Here you will required PdfParser library. We will installed this using composer.

so go to composer folder and type below command to installed PdfParser library-

C:\composer>composer require smalot/pdfparser


<?php

require 'C:\composer\vendor\autoload.php'; // Load Composer's autoloader

use Smalot\PdfParser\Parser;

function countPdfPages($pdfPath) {

    try {

        $parser = new Parser();

        $pdf = $parser->parseFile($pdfPath);

        return count($pdf->getPages());

    } catch (Exception $e) {

        echo "Error reading $pdfPath: " . $e->getMessage() . PHP_EOL;

        return 0;

    }

}


function getPdfFilesAndCounts($rootFolder) {

    $pdfInfo = [];    

    // Use RecursiveDirectoryIterator to loop through all directories and files

    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootFolder));    

    foreach ($iterator as $fileInfo) {

        if ($fileInfo->isFile() && strtolower($fileInfo->getExtension()) === 'pdf') {

            $pdfPath = $fileInfo->getPathname();

            $pageCount = countPdfPages($pdfPath);

            $pdfInfo[] = [$pdfPath, $pageCount];

        }

    }   

    return $pdfInfo;

}


function writeToCsv($pdfInfo, $outputCsv) {

    $file = fopen($outputCsv, 'w');    

    // Write the CSV header

    fputcsv($file, ['File Path', 'Page Count']);    

    // Write data

    foreach ($pdfInfo as $row) {

        fputcsv($file, $row);

    }    

    fclose($file);

}


// Set the root folder containing your PDF files

$rootFolder = 'Path of Folder'; // Change this to your folder path

$outputCsv = 'pdf_page_counts.csv'; // Output CSV file name

$pdfInfo = getPdfFilesAndCounts($rootFolder);

writeToCsv($pdfInfo, $outputCsv);

echo "Page counts for PDF files have been written to $outputCsv" . PHP_EOL;

?>


Get List All Files in a Folder with PHP Code in CSV

Below code generate a csv file that provide you name of all files exists in the folder.

<?php

function getAllFolders($path) {

    // Check if the path is a directory

    if (!is_dir($path)) {

        return "The specified path is not a directory.";

    }


    // Scan the directory

    $folders = [];

    $items = scandir($path);


    // Filter out the folders

    foreach ($items as $item) {

        if ($item != '.' && $item != '..') { // Skip the current and parent directory

            if (is_dir($path . DIRECTORY_SEPARATOR . $item)) {

                $folders[] = $item; // Add folder name to the array

            }

        }

    }

    return $folders;

}


function saveFoldersToCSV($folders, $csvFilePath) {

    // Open the CSV file for writing

    $file = fopen($csvFilePath, 'w');


    // Write the folder names to the CSV file

    foreach ($folders as $folder) {

        fputcsv($file, [$folder]);

    }


    // Close the file

    fclose($file);

}


// Specify the path to the directory and the CSV file

$path = 'Paste file path here'; // Change this to your desired path

$csvFilePath = 'folders_list.csv'; // Name of the CSV file


$folders = getAllFolders($path);


if (is_array($folders) && !empty($folders)) {

    saveFoldersToCSV($folders, $csvFilePath);

    echo "Folders have been saved to '$csvFilePath'.\n";

} else {

    echo $folders ?: "No folders found in the specified directory.\n";

}

?>


Friday, August 31, 2018

Export and save multiple worksheet as new workbook in excel


If you have multiple excel sheet in a workbook and want to export and save all sheet to individual workbook then just follow below instructions-

Open Visual basic editor by pressing alt+F11
On project window at left side => right click on project => insert=>Module.
now paste below code. read comments and set your parameter.

Sub exportcsv()
Dim ws As Worksheet
Dim path As String

path = ActiveWorkbook.path & "\" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".") - 1)
For Each ws In Worksheets
    ws.Activate
    ActiveWorkbook.SaveAs Filename:=path & "_" & ws.Name & ".csv", FileFormat:=xlCSV, CreateBackup:=False
Next
End Sub

Thursday, December 7, 2017

How to export and save each worksheet as new workbook in Excel

excel - VBA - Saving all worksheets as separate files

if you want to save your multiple excel worksheet as a separate workbook at specific folder then you are right place..

Open Visual basic editor by pressing alt+F11
On project window at left side => right click on project => insert=>Module.
now paste below code. read comments and set your parameter.

Sub Splitbook()
'Updateby20140612
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
    xWs.Copy
    Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xlsx"
    Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub


=========================
now its time to run your code by pressing F5.
Done!

Excel VBA- split data into multiple worksheets based on column

 Here VBA Code to split data into multiple worksheets based on selected column

If you have an excel sheet and want to split the data into individual multiple sheet based on column valued then the below code is best for you.


Open Visual basic editor by pressing alt+F11
On project window at left side => right click on project => insert=>Module.
now paste below code. read comments and set your parameter.

Sub parse_data()
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
vcol = 7  ''number of column on which basis you want to create saprate sheet
Set ws = Sheets("finalsheet")  ''name of your master sheet which need to compile
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1:V1"  ''range of column which need to transfer into each individual sheet
titlerow = ws.Range(title).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
For i = 2 To lr
On Error Resume Next
If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
End If
Next
myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
Sheets(myarr(i) & "").Columns.AutoFit
Next
ws.AutoFilterMode = False
ws.Activate
End Sub



=========================
now its time to run your code by pressing F5.
Done!



Wednesday, July 26, 2017

httpd-xampp.conf: How to allow access to an external IP or another computer IP to mysql



Access Xampp mysql from another computer:-

Open your xampp folder go to =&gt;apache=&gt;conf=&gt;extra=&gt;httpd-xampp.conf
 copy below cod and past it into httpd-xampp.conf file

// How to allow a particular IP to access
 
 
    Require local
    Require ip 10.0.0.1
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
 
=====================
Note: Write the remote IP at the place of 10.0.0.1
======================================= 
// How to allow anyone to access which is not safe.
 
    # Require local
    Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
 
 


Send data from Java to PHP via Post




 Here an interface between a Java and a PHP application, through we can  transfer data between the two applications. Using below java code we can generate a POST request to transfer data from JAVA to PHP.


         try {
                // open a connection to the site where script written
                URL url = new URL("http://www.domainname.com/yourphppage.php");
                URLConnection con = url.openConnection();
                // activate the output
                con.setDoOutput(true);
                PrintStream ps = new PrintStream(con.getOutputStream());
                // send your parameters to your site
                ps.print("firstKey=firstValue");
                ps.print("&amp;secondKey=secondValue");
           
                // we have to get the input stream in order to actually send the request
                con.getInputStream();
           
                // close the print stream
                ps.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

    We can use more complex data like array to send multiple parameters and values and In your PHP script, you can get the values like this:

      foreach ($_POST as $key =&gt; $value) {
        switch ($key) {
            case 'firstKey':
                $firstKey = $value;
                break;
            case 'secondKey':
                $secondKey = $value;
                break;
            default:
                break;
        }
    }