Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel blade file to word document

I am passing data from my controller to my blade file, and then want to export the blade file to word document, so far things are controlled, I can export blade to word document, the issue is the document is not opening in Microsoft word it says "word found unreadable content in 1.docx". Below is the code that I am using

$view = View::make('advertisement.advt_template.template_dr')->with('advtData', $advtData->first())->render();
$file_name = strtotime(date('Y-m-d H:i:s')) . '_advertisement_template.docx';
$headers = array(
            "Content-type"=>"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "Content-Disposition"=>"attachment;Filename=$file_name"
        );
return response()->make($view, 200, $headers);
  • I am passing data to blade and then storing all information in a variable
  • creating a file name for reference
  • creating headers to be used when downloading file
  • making the response with blade content variable and header information

Any help will be appreciated

like image 321
kkarayat Avatar asked Aug 03 '19 05:08

kkarayat


3 Answers

This is part of my old project that loads the result of some view as a msword document. Of course you can change the style section as you want

header('Content-Type: application/vnd.msword');
header('Content-Disposition: attachment; filename="test.doc"');
header('Cache-Control: private, max-age=0, must-revalidate');
?>
<head>
<style>
@page {
    size: A4 landscape;
    margin: 1.25cm 2cm 1.5cm 2cm;
}
p { font-size:16px; margin-top:0; padding-top:0 }
table { font-size:14.3px }
h1 { font-size:18.5px; text-align:center;  }
h2 { font-size:16px; text-align:left; margin-bottom:0; padding-bottom:0 }
</style>
</head>
<body>
<!-- Your html -->
</body>
</html>
like image 94
splash58 Avatar answered Oct 25 '22 05:10

splash58


You could render your blade to HTML first, then use something like phpdocx to convert that HTML to a Word document.

like image 34
Mahdi Bashirpour Avatar answered Oct 25 '22 05:10

Mahdi Bashirpour


I would try something like this:

<?php
header("Content-type: application/vnd.ms-word");
  header("Content-Disposition: attachment;Filename=document_name.doc");    
  echo "<html>";
  echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
  echo "<body>";
  echo "<b>My first document</b>";
  echo "</body>";
  echo "</html>";
?>
like image 2
Logan Craft Avatar answered Oct 25 '22 06:10

Logan Craft