Datatable customize the export to PDF

Admin 2020.06.28 12:36 조회 수 : 42

데이타테이블에서 PDF로 출력할때 이미지와 스타일 수정하는 방법이다.

 

테이블 1번 컬럼에는 이미지 URL을 출력하고, 2번 컬럼에 내용을 추가한다.

<table>
<thead>
<tr>
<th>No</th>
<th>IMAGE</th>
<th>NOTE</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{$NO}}</td>
<td>{{$imgSRC}}</td>
<td>
  {{$NAME}}<br />
  {{$GRADE}}<br />
  {{$PROFILE}}<br />
  {{$CODE}}<br />
</td>
</tr>
</tbody>
</table>

 

 

$.extend( true, $.fn.dataTable.defaults, {
  buttons: [
    {
      text: '<i class="bx bx-download font-medium-1"></i><span class="align-middle ml-25">Download PDF</span>',
      className: 'btn btn-light-secondary mb-1 mx-1 dnPDF',
      extend: 'pdfHtml5',
      pageSize: 'A4',
      styles: {
       fullWidth: { fontSize: 16, bold: true, alignment: 'left', margin: [0,0,0,0] }
      },
      action: function ( e, dt, node, config ) {
        var that = this;
        setTimeout( function () {
          $.fn.dataTable.ext.buttons.pdfHtml5.action.call(that, e, dt, node, config);
          $( ".donePDF" ).remove();
          $( ".dnPDF" ).prop("disabled", false);
        }, 50);
      },
      customize: function(doc) {
        doc.defaultStyle.fontSize = 11;
        doc.defaultStyle.alignment = 'left';
        doc.content[1].table.dontBreakRows = true;
        if (doc) {
          for (var i = 1; i < doc.content[1].table.body.length; i++) {
            // 1st Column - display IMAGE
            var imgtext = doc.content[1].table.body[i][0].text;
            delete doc.content[1].table.body[i][0].text;
            jQuery.ajax({
              type: "GET",
              dataType: "json",
              url: "{{route('base64')}}",
              data: { src: imgtext },
              async: false,
              success: function(resp) {
                //console.log(resp.data);
                doc.content[1].table.body[i][0] = {
                    margin: [0, 0, 0, 3],
                    alignment: 'center',
                    image: resp.data,
                    width: 80,
                    height: 136
                };
              }
            });
            // 2nd Column - display NOTE(4 line)
            var bodyhtml = doc.content[1].table.body[i][1].text;
            var bodytext = bodyhtml.split("\n");
            var bodystyle = []
            for (var j = 0; j < bodytext.length; j++) {
              switch(j) {
                case 0:
                  var _text = { margin:[0, 0, 0, 12], color:"#000000", fillColor:'#ffffff', bold:true, fontSize:20, alignment:'center', text:bodytext[j] };
                  break;
                case 1:
                  var _text = { margin:[0, 0, 0, 12], color:"blue", fillColor:'#ffffff', bold:false, fontSize:12, alignment:'left', text:bodytext[j] };
                  break;
                case 3:
                  var _text = { margin:[0, 0, 0, 12], color:"#000000", fillColor:'#ffffff', bold:true, fontSize:12, alignment:'left', text:bodytext[j] };
                  break;
                default:
                  var _text = { margin:[0, 0, 0, 12], color:"#000000", fillColor:'#ffffff', bold:false, fontSize:12, alignment:'left', text:bodytext[j] };
                  break;
              }
              bodystyle[j] = _text;
            };
            doc.content[1].table.body[i][1] = bodystyle;
          }
        }
      },
      exportOptions: {
        columns: [ 1, 2 ],
        stripNewlines: false,
        stripHtml: true,
        modifier: {
          page: 'all' // 'all', 'current'
        },
      }
    },
  ],
  columns: [
    { className: 'iNo', orderable: true, visible: true},
    { className: 'iIMG', orderable: false, visible: false },
    { className: 'iPDF', orderable: false, visible: false, responsivePriority: 10001 }
  ]
});


$('.dnPDF').on('click', function(){
  $(this).append('<span class="spinner-border spinner-border-sm donePDF" role="status" aria-hidden="true"></span>').closest('button').attr('disabled','disabled');
});

 

public function base64(Request $request)
{
  $request->validate([
    'src' => 'required|string',
  ]);
  $fTYPE = pathinfo($request->src, PATHINFO_EXTENSION);
  $fDATA = @file_get_contents($request->src);
  $imgDATA = base64_encode($fDATA);
  $imgSRC = 'data:image/' . $fTYPE . ';base64,'.$imgDATA;
  $error = ($imgDATA!='') ? 0 : 1;
  $msg = ($error) ? 'Error' : 'Success';
  return response()->json([ 'msg' => $msg, 'error'=> $error, 'data' => $imgSRC]);
}