ExportController.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. switch ($request->descr) {
  16. case 1:
  17. $descr = $product->characteristics . "\r\n" . $product->tech_description_short;
  18. break;
  19. case 2:
  20. $descr = $product->characteristics . "\r\n" . $product->tech_description;
  21. break;
  22. case 3:
  23. $descr = $product->tech_description_short;
  24. break;
  25. case 4:
  26. $descr = $product->tech_description;
  27. break;
  28. case 5:
  29. default:
  30. $descr = $product->characteristics;
  31. break;
  32. }
  33. $vars_for_template = array_merge($vars_for_template, [
  34. 'series#' . $i => $product->series,
  35. 'product_group#' .$i => $product->product_group,
  36. 'num#' . $i => $i,
  37. 'name#' . $i => $product->name,
  38. 'name_for_form#' . $i => $product->name_for_form,
  39. 'price#' . $i => number_format($product->price, 0, '', ' '),
  40. 'image#' . $i => $product->image_path,
  41. 'description#' . $i => str_replace("\n", '</w:t><w:br/><w:t xml:space="preserve">', $descr),
  42. ]);
  43. $i++;
  44. }
  45. // dd($vars_for_template);
  46. $my_template->cloneBlock('product_block', count($products), true, true, $vars_for_template);
  47. foreach ($vars_for_template as $k => $v){
  48. $file = public_path() . '/' . env('IMAGES_PATH') . '/' . $v;
  49. if(str_starts_with($k, 'image') && file_exists($file) && $v !== ''){
  50. $my_template->setImageValue($k, ['path' => $file, 'width' => 270, 'height' => 180]);
  51. } else {
  52. $my_template->setValue($k, $v);
  53. }
  54. }
  55. // dd($vars_for_template);
  56. $file = 'Наш_Двор_' . date('YmdHis') . '.docx';
  57. header("Content-Description: File Transfer");
  58. header('Content-Disposition: attachment; filename="' . $file . '"');
  59. header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
  60. header('Content-Transfer-Encoding: binary');
  61. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  62. header('Expires: 0');
  63. ob_clean();
  64. $my_template->saveAs("php://output");
  65. Log::notice('Execution time: ' . microtime(true) - LARAVEL_START);
  66. exit();
  67. }
  68. }