Export pdf with javascript in laravel - javascript

my code in index.blade.php to display the data to be exported to pdf.
<div class="card-body">
<div class="table-responsive table-bordered" id="pdf">
<table class="table mb-0">
<thead>
<tr>
<th>NAMA</th>
<th>PERUSAHAAN</th>
<th>LOKASI ABSEN</th>
<th>MASUK</th>
<th>PULANG</th>
<TH>KETERANGAN</TH>
</tr>
</thead>
<tbody>
#foreach ($absen as $data)
#php
$work_hour_start = $data->work_hour_start;
$attendance_time = \Carbon\Carbon::parse($data->in_time)->format('H:i:s');
$tolerance = \Carbon\Carbon::parse($attendance_time)->subMinutes($data->late_tolerance);
$hour = $tolerance->format('H:i:s');
$attendance_grp = \App\Models\AttendanceGroup::where('id', $data->attendance_group_id)
->select('ignore_work_hour')
->first();
if (isset($attendande_grp)) {
if ($data->ignore_work_hour == 0 || $attendance_grp->ignore_work_hour == 0) {
if ($hour > $work_hour_start) {
$is_late = 'Terlambat';
} else {
$is_late = 'Tepat Waktu';
}
}
}
#endphp
<tr>
<td>{{ $data->name ?? '' }}</td>
<td>{{ $data->alias ?? '' }}</td>
<td>{{ $data->location_name ?? '' }}</td>
<td>
<span class="badge badge-success">
{{ Carbon\Carbon::parse($data->in_time)->format('H:i:s') }}
</span>
</td>
<td>
<span class=" #if ($data->out_time != null) badge badge-info #else #endif">
#if ($data->out_time != null)
{{ Carbon\Carbon::parse($data->out_time)->format('H:i:s') }}
#else
{{ '-' }}
#endif
</span>
</td>
<td>{{ $is_late }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
result view
my javascript code to export pdf data from index.blade.php
<script>
var doc = new jsPDF();
function printDiv(divId,title)
{
let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150');
mywindow.document.write(`<html><head><title>${title}</title>`);
mywindow.document.write('</head><body >');
mywindow.document.write(document.getElementById(divId).innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}
</script>
results after exporting pdf
in my view i create data in tableform, i will export this data in tableform too, but the problem is the view after i export is not in table form, to export pdf i use javascript, is there any way to change my javascript code to export pdf so it can take the form of a table?

it is simple . because when you are creating the html to print with javascript . you simply DO NOT include the files related to styles . if there is a css file for styling you should include that in the html you are creating with js . or else if there is a bootstrap link to style elements include the link to cdn in the tag
your javascript would be something like that :
mywindow.document.write(`<html><head><title>${title}</title>`);
mywindow.document.write('<link rel="stylesheet" type="text/css" href="your css path">');
mywindow.document.write('</head><body >');
the rest of code...

Related

Button that adds a new row when clicked in Vue 3

First I must say that I'm a complete newbie in coding and Vue it's the first framework I'm learning and I'm terrible working with arrays at the moment. In the practice I am doing I am displaying the first five elements of the array in a table (I've filtered them in a new variable to do the v-for).
Now I need to add a button that when clicked will show me a new row of the original array, but I'm a bit stuck on how to do it. As u may see in the code below, contactList is the variable that has all the data, but I have no clue how to link it to the filtered one to show more data when clicked.
<template>
<h1 class="display-1 text-primary">Contacts</h1>
<button type="button" class="btn btn-outline-primary btn-lg" #click="addRandom">Add random</button>
<div class="container container__pos">
<table class="table table-hover">
<thead>
<tr>
<th class="col col__style">Picture</th>
<th class="col col__style">Name</th>
<th class="col col__style">Popularity</th>
<th class="col col__style">Won an Oscar</th>
<th class="col col__style">Won an Emmy</th>
</tr>
</thead>
<tbody>
<tr v-for="(element, index) of contactListed" :key="index">
<td scope="row">
<img
:src="element.pictureUrl"
:alt="element.name + ` image`"
class="image"
/>
</td>
<td> {{ element.name }}</td>
<td>{{ element.popularity }}</td>
<td>{{ wonAward(element.wonOscar) }}</td>
<td>{{ wonAward(element.wonEmmy) }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import contacts from "./contacts.json";
export default {
data() {
return {
contactList: contacts,
contactListed: contacts.slice(0, 5),
};
},
methods: {
wonAward(element) {
if (element === true || element === true){
return "winner";
} else {
return "";
}
},
},
};
</script>
You can use a computed variable that holds the first N elements of the array, and have your button increment the value of N, like this:
<script>
import contacts from "./contacts.json";
export default {
data() {
return {
contactList: contacts,
nItems: 5
};
},
computed: {
contactListed() {
return this.contacts.slice(0, this.nItems)
}
},
methods: {
addRow() {
this.nItems++;
},
wonAward(element) {
if (element === true || element === true){
return "winner";
} else {
return "";
}
},
},
};
</script>
<template>
...
<button #click="addRow()" />
</template>

Laravel 8 Delete Data Using Bootstrap Model

I have a table made with Bootstrap and I want to delete the data with bootstrap model confirm. Deleting works fine without model, but with model, delete button always send last row data to the model no matter which row delete button clicked.
model button
<i class="fe fe-trash text-danger fe-24"></i>
Modal delete button
<form action="{{ route('admin.users.delete', $user) }}" method="post">
#csrf
<button type="submit" class="btn mb-2 btn-danger">Delete</button>
</form>
js used
$('#deleteModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var recipient = button.data('user')
});
table foreach
<tbody>
#if ($users->count())
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>(478) 446-9234</td>
<td>159 address</td>
<td>
#if ($user->user_role == 0)
User
#elseif ($user->user_role == 1)
Editor
#else Admin
#endif
</td>
<td>{{ $user->created_at->format('M d, Y') }}</td>
<td>{{ $plans->find($user->plan_id)->name }}</td>
<td>
#if ($user->expiration_date != null)
{{ Carbon\Carbon::parse($user->expiration_date)->format('M d, Y') }}
#else
N/A
#endif
</td>
<td>
#if ($user->is_active == 1)
<span class="text-success font-weight-bold">Active</span>
#else
<span class="text-danger font-weight-bold">Disabled</span>
#endif
</td>
<td>
<i class="fe fe-edit text-secondary fe-24"></i>
<i class="fe fe-trash text-danger fe-24"></i>
</td>
</tr>
#endforeach
#endif
</tbody>
I am assuming that you have a foreach to creat the delete button s for every user
The $user that is passed will always be the last $user id
You need to pass the $user that was clicked
and pass this the the action of the form
try
var deleteModal = $('#deleteModal');
$('a').on('click', function (e) { // this is the "a" tag
var userId = $(this).data('user'),
var submitUrl = {!! url("/admin/users/delete/") !!}+userId;
var form = $('#form');
form.attr('action', submitUrl);
});
});
when the is clicked ,store the data-user and create the submit and change the form action
Hope this would be of any help to you.

Javascript working only after I open a modal

So I have a problem where my script for a filter/search list used to work, added a few lines of code to open a modal when a certain event occurs and now strangely when I go on my page, I can't use the search/filter list, but when I open the modal and close it, then I can use it..? It looks like it has to process the modal script first to be able to use the search/filter script.
I am working with Django and MySQL, here are the relevant lines of code:
.html ( first lines are about the search function, the second part is the modal and third block is the table used in the search/filter function and the conditions for opening the modal )
<div class="search-right">
<input type="text" id="mySearchInput" placeholder= " Search a stock.." title="Stock Search" style="float:left">
</div>
{% if warning %}
<div id="myModalAddaStock" class="modalAddaStock">
<div class="modal-content">
<span class="closeAddaStock">×</span>
<p>{{warning}} {% if stock_to_add %}{{stock_to_add}} {% endif %}{% if stock_to_replace %}{{stock_to_replace}} or {{flex}}{% endif %}</p>
</div>
</div>{% endif %}
<div class="grid-itam-2bottom">
<table id="myTable1" class="myTable"cellspacing="0" cellpadding="1" border="1" width="100%">
<tr class="stockheader">
<th width="8%" style="text-align:center;">Symbol</th>
<th width="35%"style="text-align:center">Company Name</th>
<th width="8%" style="text-align:center">Sector</th>
<th width="7%" style="text-align:center">Streak</th>
<th width="12%"style="text-align:center">Market Cap</th>
<th width="8%" style="text-align:center">Return</th>
<th width="6%" style="text-align:center">WL</th>
<th width="6%" style="text-align:center">Add</th>
</tr>
{% for stock in stock_list %}
<tbody id="searchAstock">
<tr>
<td id="searchsymmol" style="border-bottom:1px;padding-left: 5px;">{{stock.symbol}}</td>
<td style="border:0px;"class="Ellipsis Company">{{stock.company_name}}</td>
<td data-type="{{stock.sector}}">{{stock.sector}}</td>
<td>{{stock.streak}}</td>
<td>{{stock.market_cap_rounded}}</td>
<td>{% if 1w %}{{stock.five_day_avg}}{% elif 2w %}{{stock.ten_day_avg}}{% elif 3w %}{{stock.fifteen_day_avg}}{% else %}{{stock.change_percent}}{% endif %}</td>
<td style="text-align:center"><img onclick="myFunctionWL" id="WLtest"src="{% static "Myimages/images/flag.png" %}" alt="" title="Add to Watchlist" height=20 width=20 style="border-radius:50%;"></img></td>
<td style="text-align:center"><img src="{% static "Myimages/images/icon.png" %}" title="Add to my Team" height=20 width=20 style="border-radius:50%;"></img></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
And here are the scripts:
function myFunctionsearchbar() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById("mySearchInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myTable1");
li = ul.getElementsByTagName("tr");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
var modal = document.getElementById("myModalAddaStock");
var span = document.getElementsByClassName("closeAddaStock")[0];
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
I feel like there is a core concept I have missed about Javascript? My script was working just fine before I implement the modal ( those loops at the beginning of the HTML files ) and now it only works AFTER those loops are done...

pagination for table rows with fixed tablehead

On my website I created a "dynamic" table. I want to include a pagination, to only show 10 rows at a time. The table head shall be displayed above the rows on every page.
But with my pagination function, all the content within is put under "Ref.". If I uncomment the commented part, the pagination does not work at all.
What needs to changed in my code to display the table correct on each page? (all ref{{i}} under "Ref." / "score{{i}} under "Score" /...)
Table:
{% if empty == False %}
<table style="float: left; width: 100%" class="table table-hover">
<thead id="header">
<tr >
<th>Ref.</th>
<th>Score</th>
<th>Title</th>
</tr>
</thead>
<tbody>
{% for i in range (0,numofresults) %}
<tr id="cardmb3n{{i}}">
<td id="ref{{i}}"> </td>
<td id="score{{i}}" "> </td>
<td>
<div>
<a id="header{{i}}" href=""></a><br>
<a id="hyperlink{{i}}" href="" ></a>
</div>
</td>
</tr>
</tbody>
{% endfor %}
</table>
Pagination:
{% if empty == False %}
function paginate(page){
var val = parseInt(document.getElementById("currentpage").innerHTML);
if(page=='Next'){
page = val + 1;
} else if(page=='Previous'){
page = val - 1;
} else{
page = parseInt(page);
}
if(val!=page){
for(var j = 0; j<ergebnisliste.length; j++){
if(j>=(page-1)*10 && j<10*page){
// document.geElementById("header").style = "display:table";
document.getElementById("cardmb3n" + j).style = "display:block";
}else{
// document.geElementById("header").style = "display:none";
document.getElementById("cardmb3n" + j).style = "display:none";
}
}
........some code.........
}
}
{% endif %}
found a solution: document.getElementById("cardmb3n" + j).style = "display:table-row";

Using v-bind to put data into a tag a in the property href (VUE.JS 2 + Laravel 5.3)

Here is my javascript/vue.js code:
import _ from 'lodash'
export default{
props:['campanha'],
data (){
return{
list:[],
filter: '',
href: '/campanha/9/edit'
}
},
methods:{
url: function (href){
return '/campanha/'+this.href+'/edit'
}
},
mounted: function (){
this.list = JSON.parse(this.campanha)
},
computed: {
filteredCampanhas(){
var self = this
return this.list.filter(function(campanhas) {
return campanhas.nome.indexOf(self.filter) > -1
})
}
}
}
And here it`s my html:
<template>
<div>
<div class="well">
Novo Cadastro <span class="glyphicon glyphicon-plus" aria-hidden="true"/><br></br>
<input type="text" class="form-control" placeholder="Filtrar Campanhas" v-model="filter">
</div>
<div class="table-responsive">
<table class="table table-borderless">
<thead>
<tr>
<th>Id</th>
<th>Nome</th>
<th>Data Início</th>
<th>Data Término</th>
<th>Hora Inícío</th>
<th>Hora Término</th>
</tr>
</thead>
<tbody>
<!--{{ url('/campanha/' . $item->id_campanha . '/edit') }}
href: '/campanha/9/edit'
<td><a v-bind:href="href">{{ c.nome }}</a></td>
!-->
<tr v-for="c in filteredCampanhas">
<td>{{ c.id_campanha }}</td>
<td><a :href="url(c.id_campanha)">{{ c.nome }}</a></td>
<td>{{ c.data_inicio }}</td>
<td>{{ c.data_termino }}</td>
<td>{{ c.hora_inicio }}</td>
<td>{{ c.hora_termino }}</td>
</tr>
</tbody>
</table>
</div>
<div>
</template>
I have tried to put some data into href section of my tag a, to link to another page, but it`s not working.
Try following:
methods:{
url: function (href){
return '/campanha/'+ href+'/edit'
}
},
When you are using this.href it will start to pick href from data of vue instance,

Categories

Resources