<?php
// am_a4.php
// A4 webpage

 $contis="<html><head><style>
 @media print {
    body{
        width: 21cm;
        height: 29.7cm;
        margin: 30mm 45mm 30mm 45mm; 
        /* change the margins as you want them to be. */
   } 
}
</style></head><body";
 $lcontis="<html><head><style>
 @media print {
    body{
        height: 21cm;
        width: 29.7cm;
        margin: 45mm 30mm 45mm 30mm; 
        /* change the margins as you want them to be. */
   } 
}
</style></head><body";

 if (isset($_GET['clear'])) {
   if (file_exists("a4_content.txt")) {
   if (abs(filesize("a4_content.txt") - $_GET['clear']) < 9) {
   unlink("a4_content.txt");
   }
   }
 } else if (file_exists("a4_content.txt")) {
   $fis=file_get_contents("a4_content.txt");
   if (strpos($fis, ":IMAGE/") !== false) { $contis=$lcontis; }
   $contis.=" style='background-image:URL(" . str_replace(":IMAGE/", ":image/", trim($fis)) . "); background-repeat:no-repeat; background-size:contain;'></body></html>";
   if ($fis != trim($fis)) {
     unlink("a4_content.txt");
   } else {
     file_put_contents("a4_content.txt", ($fis . " "));
   }
 } else if (isset($_POST['a4_content'])) {
   file_put_contents("a4_content.txt", str_replace(" ","+",urldecode($_POST['a4_content'])));
   $gps="window.open(\"https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fwww.rjmprogramming.com.au%2FPHP%2Fam_a4.php&tab=desktop\",\"_blank\",\"top=50,left=50,height=900,width=1300\");";
   $contis.=" onload='" . $gps . "'></body></html>";
 } else {
   $contis.="></body></html>";
 }
 
 echo $contis;
 exit;
?>