Add text in header for jspdf if (autoTable Html) - pdf-generation

How can we add a text to the top of the pdf? I use autoTable.
const handleDownloadPdf = async (orientation) => {
const report = new jsPDF({
orientation: orientation,
unit: "pt",
format: "a4",
});
report.autoTable({
html: refExportExcel,
margin: 15,
})
report.save('Report.pdf');
};
refExportExcel: It is a ref(NextJS) of the table.

You can use the text method before calling the autotable to add text to the top
import "./styles.css";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
const handleDownloadPdf = () => {
const report = new jsPDF({
unit: "pt",
format: "a4"
});
const refExportExcel = document.getElementById("myTable");
report.text(20, 20, "This is some text at the top of the PDF.");
report.autoTable({
html: refExportExcel,
margin: 35
});
report.save("Report.pdf");
};
export default function App() {
return (
<div className="App">
<table id="myTable">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
<button onClick={handleDownloadPdf}>Create</button>
</div>
);
}

Related

Sort table using jquery.ui and store the new position to database

I have a table named categories where I store the categories for an E-Commerce. This table has the following aspect:
And this is the user interface to admin the categories.
I want to make a system to sort this table using JQuery.UI.
This is what I tried, but it returns me 500 (Internal Server Error)
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
foreach($categories as $category)
<tr data-index="{{$category->id}}" data-position="{{$category->position}}">
<td class="table-text">{{$category->name}}</td>
<td class="table-text table-justified hide-mobile">
if ($category->visibility)
<i class="far fa-eye"></i>
else
<i class="far fa-eye-slash"></i>
endif
</td>
<td class="table-text table-opts">{{$category->position}}</td>
<td class="table-opts">
<div class="operations">
<a href="{{url('/admin/categories/'.$category->id.'/edit')}}" class="btn-edit pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Editar">
<i class="fas fa-edit"></i>
</a>
<a href="{{url('/admin/categories/'.$category->id.'/delete')}}" class="btn-delete btn-confirm pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Eliminar">
<i class="fas fa-trash-alt"></i>
</a>
</div>
</td>
</tr>
endforeach
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$('#table_content').sortable({
cancel: 'thead',
stop: () => {
var items = $('#table_content').sortable('toArray', {attribute: 'data-index'});
var ids = $.grep(items, (item) => item !== "");
$.post('{{ url('/admin/categories_list/reorder') }}', {
": $("meta[name='csrf-token']").attr("content"),
ids
})
.fail(function (response) {
alert('Error occured while sending reorder request');
location.reload();
});
}
});
});
</script>
And this is the controller function:
public function postCategoriesReorder(Request $request){
$request->validate([
'ids' => 'required|array',
'ids.*' => 'integer',
]);
foreach ($request->ids as $index => $id){
DB::table('categories')->where('id', $id)->update(['position' => $index+1]);
}
return response(null, Response::HTTP_NO_CONTENT);
}
Consider the following example.
var tableData = [{
id: 1,
name: "Cat 1",
visibility: true,
position: 1
}, {
id: 2,
name: "Cat 2",
visibility: false,
position: 2
}, {
id: 3,
name: "Cat 3",
visibility: true,
position: 3
}, {
id: 4,
name: "Cat 4",
visibility: true,
position: 4
}, {
id: 5,
name: "Cat 5",
visibility: true,
position: 5
}];
$(function() {
function updateTable(data) {
$.each(data, function(i, r) {
var row = $("<tr>", {
"data-index": r.id
}).data("row", r).appendTo("#table_content");
$("<td>", {
class: "table-text"
}).html(r.name).appendTo(row);
$("<td>", {
class: "table-text table-justified hide-mobile"
}).html("<i class='fas fa-eye'></i>").appendTo(row);
if (!r.visibility) {
$(".fa-eye", row).toggleClass("fa-eye fa-eye-slash");
}
$("<td>", {
class: "table-text table-opts"
}).html(r.position).appendTo(row);
$("<td>", {
class: "table-opts"
}).appendTo(row);
$("<div>", {
class: "operations"
}).appendTo($("td:last", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/edit",
class: "btn-edit pV-8 pH-12",
title: "Editor",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-edit'></i>").appendTo($("td:last > div", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/delete",
class: "btn-delete btn-confirm pV-8 pH-12",
title: "Eliminar",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-trash-alt'></i>").appendTo($("td:last > div", row));
});
}
function gatherData(table) {
var rows = $("tbody > tr", table);
var item;
var results = [];
rows.each(function(i, el) {
item = $(el).data("row");
item.position = i + 1;
results.push(item);
});
return results;
}
updateTable(tableData);
$('#table_content').sortable({
cancel: 'thead',
start: (e, ui) => {
start = $('#table_content').sortable('toArray', {
attribute: 'data-index'
});
},
stop: () => {
ids = gatherData("table");
console.log(start, ids);
/*
$.post('/admin/categories_list/reorder', {
"csrf-token": $("meta[name = 'csrf-token']").attr("content"),
ids
})
.fail(function(response) {
alert('Error occured while sending reorder request');
location.reload();
});
*/
}
});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#fortawesome/fontawesome-free#5.15.4/css/fontawesome.min.css" integrity="sha384-jLKHWM3JRmfMU0A5x5AkjWkw/EYfGUAGagvnfryNV3F9VqM98XiIH7VBGVoxVSc7" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
</tbody>
</table>
This should allow you to pass the new position for each ID to the script so the Database is updated.

Is there a way to update my component dynamically without refreshing the page?

I have a vue component which builds the card up, and within that component is another component that I pass data to with a prop I currently use Swal to as a popup to add a new project to the database however when it finishes adding I have to refresh the page for the data to be visible. The entire reason I wanted to use vue was to not have to refresh the page to view updated data and I haven't been able to figure it out.
This is my Projects.vue
import ProjectItem from './Projects/ProjectItem.vue';
export default {
name: "Projects",
components: {
ProjectItem
},
data() {
return {
projects: []
}
},
methods: {
getProjects () {
axios.get('/api/projects').then((res) => {this.projects = res.data});
},
addProject() {
Swal.queue([{
title: 'Add a New Project?',
html:
'<label for="name" style="color: #000;font-weight: 700">Project Name<input id="name" class="swal2-input"></label>' +
'<label for="description" style="color: #000;font-weight: 700">Project Description<textarea id="description" rows="5" cols="15" class="swal2-input"></textarea></label>',
showCancelButton: true,
confirmButtonText: 'Create Project',
showLoaderOnConfirm: true,
preConfirm: (result) => {
return new Promise(function(resolve, reject) {
if (result) {
let name = $('#name').val();
let desc = $('#description').val();
axios.post('/api/projects', {title:name,description:desc})
.then(function(response){
Swal.insertQueueStep({
type: 'success',
title: 'Your project has been created!'
})
resolve();
})
.catch(function(error){
Swal.insertQueueStep({
type: 'error',
title: 'Something went wrong.'
})
console.log(error);
reject();
})
}
});
}
}])
}
},
mounted () {
this.getProjects();
}
I bind it to ProjectItem in my Project.vue template:
<div class="table-responsive border-top">
<table class="table card-table table-striped table-vcenter text-nowrap">
<thead>
<tr>
<th>Id</th>
<th>Project Name</th>
<th>Team</th>
<th>Date</th>
<th>Preview</th>
</tr>
</thead>
<project-item v-bind:projects="projects" />
</table>
and this is my ProjectItem.vue:
<template>
<tbody>
<tr v-for="project in projects" :key="project.id">
<td>{{ project.id }}</td>
<td>{{ project.title }}</td>
<td><div class="avatar-list avatar-list-stacked">
{{ project.description }}
</div>
</td>
<td class="text-nowrap">{{ project.updated_at }}</td>
<td class="w-1"><i class="fa fa-eye"></i></td>
</tr>
</tbody>
</template>
<script>
export default {
name: "ProjectItem",
props: ["projects"],
}
</script>
You must insert the recently added project to the products array.
If you are able to change the backend code, you could change the response to include the project.
this.projects.push(response.project);

How to solve the pure render/function binding pr0blem in vanilla React?

Let's start with some code:
export default class BookingDriverContainer extends React.PureComponent {
static propTypes = {
bookingId: PropTypes.number.isRequired,
};
constructor(props) {
super(props);
this.state = {
loading: true,
saving: false,
};
}
componentDidMount() {
ajax(Router.route('api.bookingDrivers', {
id: this.props.bookingId,
})).then(res => {
if(res.ok) {
this.setState({
loading: false,
segments: res.data.segments,
drivers: res.data.drivers,
});
}
});
}
driverChanged = segmentId => ev => {
console.log(`Driver for segment ${segmentId} changed to ${ev.target.value}`);
};
render() {
if(this.state.loading) {
return <img src={loadingGif} width="220" height="20" alt="Loading..."/>;
}
return (
<table className="index-table">
<thead>
<tr>
<th style={{width: '50px'}}>Seg.</th>
<th style={{width: '70px'}}>Unit</th>
<th style={{width: '140px'}}>Driver</th>
<th style={{width: '100px'}}>Driver #</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{this.state.segments.map(seg => (
<tr key={seg.id}>
<td>*snip*</td>
<td>*snip*</td>
<td>
<SelectBox onChange={this.driverChanged(seg.id)}>
<option value="" className="not-set">TBD</option>
{this.state.drivers.map(([id, name]) => (
<option key={id} value={id}>{name}</option>
))}
</SelectBox>
</td>
<td>*snip*</td>
<td>*snip*</td>
</tr>
))}
</tbody>
</table>
)
}
}
In this example, my component is not pure because of this: onChange={this.driverChanged(seg.id)}. i.e., every time my component renders, that creates a new function, which will cause <SelectBox> to be re-rendered even though nothing has changed.
How can this be fixed without introducing a large framework like Redux?
Best way I've found so far is just to memoize the function.
driverChanged = memoize(segmentId => ev => {
// ...
});
This way, given the same segmentId it will return the same function instance, which will allow the PureRenderMixin et al. to work their magic.
Here's my memoize function:
export default function memoize(fn, options={
serialize: fn.length === 1 ? x => x : (...args) => JSON.stringify(args),
}) {
let cache = new Map();
return (...args) => {
let key = options.serialize(...args);
if(cache.has(key)) {
return cache.get(key);
}
let value = fn(...args);
cache.set(key, value);
return value;
}
}
It only supports JSON-serializable variables, but you can find a more advanced memoizer on npm if you wish.
If all you want is to prevent creating new functions every time the component renders, you could simply create another component to contain SelectBox component:
class MySelectBox extends React.Component {
static propTypes = {
drivers: PropTypes.arrayOf(PropTypes.object).isRequired,
segId: PropTypes.string.isRequired,
driverChanged: PropTypes.function.isRequired,
}
render() {
const {
drivers,
segId,
driverChanged,
} = this.props;
return (
<SelectBox onChange={ev => driverChanged(ev, segId)}>
<option value="" className="not-set">TBD</option>
{drivers.map(([id, name]) => (
<option key={id} value={id}>{name}</option>
))}
</SelectBox>
);
}
}
Then use this new component inside BookingDriverContainer with the proper properties:
export default class BookingDriverContainer extends React.Component {
// ...
driverChanged = (ev, segId) => {
console.log(`Driver for segment ${segId} changed to ${ev.target.value}`);
}
render() {
// ...
return (
<table className="index-table">
<thead>
{/* ... */}
</thead>
<tbody>
{this.state.segments.map(seg => (
<tr key={seg.id}>
<td>*snip*</td>
<td>*snip*</td>
<td>
<MySelectBox
driverChanged={this.driverChanged}
segId={seg.id}
drivers={this.state.drivers}
/>
</td>
<td>*snip*</td>
<td>*snip*</td>
</tr>
))}
</tbody>
</table>
)
}
}
This way you do not create new functions at every render times.

make jquery plugin not share private variable in same plugin

<script>
(function () {
jQuery.fn.szThreeStateColor = function (settings) {
var cfg = {
"overBgColor": "green",
"overFgColor": "white",
"clickBgColor": "blue",
"clickFgColor": "white"
};
if(settings) {
$.extend(cfg, settings);
}
var clickIdx = -1;
$thisObj = $(this);
var iniBgColor = $thisObj.find("tbody td").css("background-color");
var iniFgColor = $thisObj.find("tbody td").css("color");
var iniHeight = $thisObj.find("tr").css("height");
$thisObj.find("tbody tr").bind("mouseover", function (e) {
if($(this).index() != clickIdx) {
$(this).css({
"background-color": cfg.overBgColor,
"color": cfg.overFgColor
});
}
});
$thisObj.find("tbody tr").bind("mouseout", function (e) {
if($(this).index() != clickIdx) {
$(this).css({
"background-color": iniBgColor,
"color": iniFgColor
});
}
});
$thisObj.find("tbody tr").bind("click", function (e) {
//console.log($(this).index() + ":" + clickIdx);
if($(this).index() != clickIdx) {
if(clickIdx >= 0) {
$thisObj.find("tbody tr:eq(" + clickIdx + ")").css({
"background-color": iniBgColor,
"color": iniFgColor
});
}
$(this).css({
"background-color": cfg.clickBgColor,
"color": cfg.clickFgColor
});
clickIdx = $(this).index();
}
});
return this;
}
})($);
$(document).ready(function () {
$("#table1")
.szThreeStateColor({
"overBgColor": "#34ef2a",
"overFgColor": "#000000",
"clickBgColor": "#333333"
});
$("#table2").szThreeStateColor();
});
</script>
</HEAD>
<BODY>
<table id="table1" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
<table id="table2" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
This plugin sets different cell colors when the events mouseover, mouseout, click are fired. The plugin works fine with a single table but works abnormally when multiple tables are used. Maybe the variable clickIdx is shared by each table. How can I prevent sharing of that variable?
You can do so by wrapping your plugin in return this.each(function() {...}).
jQuery.fn.szThreeStateColor = function (settings) {
// ...
return this.each(function() {
// variables that need to be private go in here
});
}

Edit button in a view details popup in MVC 3 using jQuery

I am currently in the process of setting up an MVC entities page with the ability to list all entities of a certain type, using jQuery popups to create new entities, edit or delete existing entities.
As not all entities' details are shown in the list, I would like to provide a details view (read only) which has an edit button in case changes need to be made.
However, at the moment I have not been able to implement this and would welcome any suggestions on how to proceed. Please find the view definitions included below:
Entity Country:
/Views/Country/Index:
#model IEnumerable<MVCjQuerySample2.Entities.Country>
#{
ViewBag.Title = "Countries";
}
<h2>Countries</h2>
<span class="AddLink IconLink"><img src="/Content/Images/Create.png" alt="Add new country" /></span>
<div id="ListBlock"></div>
<div id="EditDialog" title="" class="Hidden"></div>
<div id="DeleteDialog" title="" class="Hidden"></div>
<script type="text/javascript">
$(function () {
$("#EditDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Save": function () {
if ($("#EditForm").validate().form()) {
$.post("/Country/Save", $("#EditForm").serialize(), function (data) {
$("#EditDialog").dialog("close");
$("#ListBlock").html(data);
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$("#DeleteDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Delete": function () {
$.post("/Country/Delete", $("#DeleteForm").serialize(), function (data) {
$("#DeleteDialog").dialog("close");
$("#ListBlock").html(data);
});
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".AddLink").click(function () {
$("#EditDialog").html("")
.dialog("option", "title", "Add new Country")
.load("/Country/Create", function () { $("#EditDialog").dialog("open"); });
});
$(".EditLink").live("click", function () {
var id = $(this).attr("itemid");
$("#EditDialog").html("")
.dialog("option", "title", "Edit Country")
.load("/Country/Edit/" + id, function () { $("#EditDialog").dialog("open"); });
});
$(".DeleteLink").live("click", function () {
var id = $(this).attr("itemid");
$("#DeleteDialog").html("")
.dialog("option", "title", "Delete Country")
.load("/Country/DeleteConfirm/" + id, function () { $("#DeleteDialog").dialog("open"); });
});
LoadList();
});
function LoadList() {
$("#ListBlock").load("/Country/List");
}
/Views/Country/List:#using MVCjQuerySample2.Helpers
#model IEnumerable<MVCjQuerySample2.Entities.Country>
<table class="CountryList">
<tr>
<th>Iso</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Iso)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<span class="EditLink IconLink" itemid="#item.Id"><img src="/Content/Images/Pencil.png" alt="Edit" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Pencil.png", "Edit", "Edit", new { id = item.Id })-->
</td>
<td>
<span class="DeleteLink IconLink" itemid="#item.Id"><img src="/Content/Images/Delete.png" alt="Delete" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Delete.png", "Delete", "Delete", new { id = item.Id })-->
</td>
</tr>
}
</table>
/Views/Country/EditForm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Save", "Country", FormMethod.Post, new { id = "EditForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("CreatedBy")
#Html.Hidden("CreatedOn")
#Html.Hidden("UpdatedBy")
#Html.Hidden("UpdatedOn")
<table>
<tr>
<td>Iso</td>
<td>#Html.TextBox("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBox("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}
<script type="text/javascript">
$(function () {
$("#EditForm").validate({
rules: {
Iso: { required: true },
Name: { required: true }
}
});
});
/Views/Country/DeleteConfirm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Delete", "Country", FormMethod.Post, new { id = "DeleteForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("Iso")
#Html.Hidden("Name")
#Html.Hidden("CreatedOn")
#Html.Hidden("CreatedBy")
#Html.Hidden("UpdatedOn")
#Html.Hidden("UpdatedBy")
<table>
<tr>
<td>Iso</td>
<td>#Html.DisplayText("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.DisplayText("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}

Resources