ExportController.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\Product;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Log;
  6. class ExportController extends Controller
  7. {
  8. public function export_docx(Request $request){
  9. $ids = json_decode($request->ids,true);
  10. $products = Product::query()->whereIn('id', $ids)->orderBy('series', 'asc')->get();
  11. $my_template = new \PhpOffice\PhpWord\TemplateProcessor(storage_path('templates/template_maf.docx'));
  12. $vars_for_template = [];
  13. $i = 1;
  14. foreach ($products as $product){
  15. $vars_for_template = array_merge($vars_for_template, [
  16. 'series#' . $i => $product->series,
  17. 'product_group#' .$i => $product->product_group,
  18. 'num#' . $i => $i,
  19. 'name#' . $i => $product->name,
  20. 'name_for_form#' . $i => $product->name_for_form,
  21. 'price#' . $i => number_format($product->price, 0, '', ' '),
  22. 'image#' . $i => $product->image_path,
  23. 'description#' . $i => str_replace("\n", '</w:t><w:br/><w:t xml:space="preserve">', $product->characteristics . "\r\n" . $product->tech_description),
  24. ]);
  25. $i++;
  26. }
  27. // dd($vars_for_template);
  28. $my_template->cloneBlock('product_block', count($products), true, true, $vars_for_template);
  29. foreach ($vars_for_template as $k => $v){
  30. $file = public_path() . '/' . env('IMAGES_PATH') . '/' . $v;
  31. if(str_starts_with($k, 'image') && file_exists($file) && $v !== ''){
  32. $my_template->setImageValue($k, ['path' => $file, 'width' => 270, 'height' => 180]);
  33. } else {
  34. $my_template->setValue($k, $v);
  35. }
  36. }
  37. // dd($vars_for_template);
  38. $file = 'Наш_Двор_' . date('YmdHis') . '.docx';
  39. header("Content-Description: File Transfer");
  40. header('Content-Disposition: attachment; filename="' . $file . '"');
  41. header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
  42. header('Content-Transfer-Encoding: binary');
  43. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  44. header('Expires: 0');
  45. ob_clean();
  46. $my_template->saveAs("php://output");
  47. Log::notice('Execution time: ' . microtime(true) - LARAVEL_START);
  48. exit();
  49. }
  50. }