ExportController.php 2.3 KB

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