Skip to content

Instantly share code, notes, and snippets.

@digital-old-school-journey
Created January 6, 2019 14:38
Show Gist options
  • Save digital-old-school-journey/1a0dc725fa18ca4c57948476d254ae0f to your computer and use it in GitHub Desktop.
Save digital-old-school-journey/1a0dc725fa18ca4c57948476d254ae0f to your computer and use it in GitHub Desktop.
<?php
require_once("vendor/autoload.php");
$op = $_REQUEST['op'];
if ($op == "create") {
png();
} else if($op == "download") {
word();
}
function png()
{
$data = $_POST['image_data'];
if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
if (!in_array($type, ['jpg', 'jpeg', 'gif', 'png'])) {
die('invalid image type');
}
$data = base64_decode($data);
if ($data === false) {
die('base64_decode failed');
}
} else {
die('did not match data URI with image data');
}
file_put_contents("pic.{$type}", $data);
echo "OK";
}
function word()
{
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$image_path = realpath("pic.png");
$section->addImage($image_path, array(
'height' => 100,
'positioning' => 'absolute',
'posHorizontal' => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_CENTER,
'posHorizontalRel' => 'margin',
'posVerticalRel' => 'line',
));
$filename = "test.docx";
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
try {
header("Content-Disposition: attachment; filename='" . $filename . "'");
$objWriter->save("php://output");
} catch (Exception $e) {
die($e->getMessage());
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment