<?php
// SV-33917: valid 1-page PDF padded to the customer's file size (10,024,157
// bytes by default, from the HAR "total"). Served inline (no
// Content-Disposition) because the page fetch()es it and wraps it in a Blob.
set_time_limit(0);

$target = isset($_GET['size']) ? max(1024, intval($_GET['size'])) : 10024157;

function build_pdf($pad_len) {
   $content = "BT /F1 24 Tf 72 720 Td (SV-33917 kagoshima_blob_pdf.php) Tj ET";
   $objs = array(
      "<< /Type /Catalog /Pages 2 0 R >>",
      "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
      "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " .
         "/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
      "<< /Length " . strlen($content) . " >>\nstream\n" . $content . "\nendstream",
      "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
   );
   $head = "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n";
   $offsets = array();
   foreach ($objs as $i => $o) {
      $offsets[] = strlen($head);
      $head .= ($i + 1) . " 0 obj\n" . $o . "\nendobj\n";
   }
   $offsets[] = strlen($head);
   $head .= "6 0 obj\n<< /Length " . $pad_len . " >>\nstream\n";
   $tail = "\nendstream\nendobj\n";
   $xref_pos = strlen($head) + $pad_len + strlen($tail);
   $tail .= "xref\n0 7\n0000000000 65535 f \n";
   foreach ($offsets as $o) {
      $tail .= sprintf("%010d 00000 n \n", $o);
   }
   $tail .= "trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n" . $xref_pos . "\n%%EOF\n";
   return array($head, $pad_len, $tail);
}

// Digit counts in /Length and startxref shift the size, so converge on target.
$pad = $target;
for ($i = 0; $i < 10; $i++) {
   list($head, $pad_len, $tail) = build_pdf($pad);
   $total = strlen($head) + $pad_len + strlen($tail);
   if ($total == $target) {
      break;
   }
   $pad = max(0, $pad + $target - $total);
}

header("HTTP/1.1 200 OK");
header("Content-Type: application/pdf");
header("Content-Length: " . $total);
header("Cache-Control: no-store");

echo $head;
// Stream the padding in 256 KB chunks so the page sees fetch() progress.
$chunk = str_repeat(" ", 256 * 1024);
for ($left = $pad_len; $left > 0; $left -= strlen($chunk)) {
   echo ($left >= strlen($chunk)) ? $chunk : substr($chunk, 0, $left);
   flush();
}
echo $tail;
?>
