Search code examples
phphtmlpdf-to-html

Saving html page in local storage using php


I am using PDFTOHTML (a php library) to convert pdf files to html and it's working fine but it's showing converted file in a browser and not storing in local folder, i want to store converted html in local folder using php with the same name as pdf was i-e mydata.pdf to mydata.html Code that is converting pdf to html is:-

 <?php
// if you are using composer, just use this
include 'vendor/autoload.php';

 $pdf = new \TonchikTm\PdfToHtml\Pdf('cv.pdf', [
     'pdftohtml_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdftohtml.exe',
    'pdfinfo_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdfinfo.exe'
]);

// get content from all pages and loop for they
foreach ($pdf->getHtml()->getAllPages() as $page) {
    echo $page . '<br/>';
}
?>

Solution

  • Just change your foreach to

    $filePdf = 'cv'; // your pdf filename without extension
    $pdf = new \TonchikTm\PdfToHtml\Pdf($filePdf.'.pdf', [
        'pdftohtml_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdftohtml.exe',
        'pdfinfo_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdfinfo.exe'
    ]);
    
    $counterPage = 1;
    foreach ($pdf->getHtml()->getAllPages() as $page) {
        $filename = $filePdf . "_" . $counterPage.'.html'; // set as string directory and filename where you want to save it
    
        if (file_exists($filename)) {
            // if file exist do something
        } else {
            // else 
            $fileOpen = fopen($filename, 'w+');
            fputs($fileOpen, $page);
            fclose($fileOpen);
        }
        $counterPage++;
        echo $page . '<br/>';
    }
    

    This will create you file for example: example_1.html, example_2.html and so on. if this not help you then probably you need to use file_put_contents with ob_start() and ob_get_contents() read more here