data is shown on chartjs-vue only after resizing browser or opening developer tools - vue.js

im having hard time fixing this problem.
i get my data with a get request, after opening developer tools or resizing browser the data is shown.
i have tried some delay or timeout solutions but sadly could not make it work. i need the fastest solution, even if it is a "dirty hack" sort of solution.
im using vue 2.9.1 and chartjs-vue 2.7.1.
thank you!
this is my code:
import {Line} from 'vue-chartjs'
export default {
name: 'Events',
extends: Line,
created: function () {
this.getEvents();
},
data () {
return {
gradient: null,
gradient2: null,
datesList : [],
avgList: []
}
},
methods:{
graphClickEvent(event, array){
var points = this.getElementAtEvent(event)
},
getEvents () {
this.$http.get('http://localhost:8081/users/getAllEvents'
,{headers: {'Content-Type': 'application/json',
'Authorization': localStorage.getItem('token'),}
}).then((res) => {
// res.body = array of event object
var eventsArr = res.body;
var arrayLength = eventsArr.length;
for (var i = 0; i < arrayLength; i++) {
var date = new Date(parseInt(eventsArr[i].startTime))
var day = date.getDate()
var month = date.getMonth()
var year = date.getFullYear()
var hours = date.getHours()
hours = ("0" + hours).slice(-2);
var minutes = date.getMinutes()
minutes = ("0" + minutes).slice(-2);
var str = day;
var str = day + "." + (month + 1) + "." + year +" - " + hours + ":" + minutes
this.datesList.push(str);
}
for (var i = 0; i < arrayLength; i++) {
var evnt = eventsArr[i];
this.avgList.push({label: evnt.name,y: evnt.pulseAverage ,tag: evnt.tag, id: evnt.id });
}
})
}
},
mounted () {
this.gradient = this.$refs.canvas.getContext('2d').createLinearGradient(0, 0, 0, 450)
this.gradient2 = this.$refs.canvas.getContext('2d').createLinearGradient(0, 0, 0, 450)
this.gradient.addColorStop(0, 'rgba(255, 0,0, 0.5)')
this.gradient.addColorStop(0.5, 'rgba(255, 0, 0, 0.25)');
this.gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
this.gradient2.addColorStop(0, 'rgba(0, 231, 255, 0.9)')
this.gradient2.addColorStop(0.5, 'rgba(0, 231, 255, 0.35)');
this.gradient2.addColorStop(1, 'rgba(0, 231, 255, 0)');
this.renderChart({
labels: this.datesList,
datasets: [
{
label: 'Events',
borderColor: '#05CBE1',
pointBackgroundColor: 'white',
pointBorderColor: 'white',
borderWidth: 2,
backgroundColor: this.gradient2,
data: this.avgList
},
]
,
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
}
//
,{ onClick: function(event){
var activePoints = this.getElementAtEvent(event)
var firstPoint = activePoints[0];
if(firstPoint !== undefined){
var label = this.data.labels[firstPoint._index];
var value = this.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
var location = "eventGraph?id=" + value.id;
window.location.href = location;
}
}
, responsive: true, maintainAspectRatio: false,fontColor: '#66226',
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
title: function(tooltipItems, data) {
var evnt = data.datasets[0].data[tooltipItems[0].index].label;
return evnt
},
label: function(tooltipItems, data) {
var avg = 'Average heart: ' + [tooltipItems.yLabel];
var evnt = 'Type: ' + data.datasets[0].data[tooltipItems.index].tag;
return [avg,evnt];
}
}
}
})
}
}

It sounds like an initialization issue where the chart is initially rendered in an element that is not visible or it can't determine the size of the parent.
I see similar issues doing a Google:
ChartJS won't draw graph inside bootstrap tab until window resize #17
Charts rendered in hidden DIVs will not display until browser resize #29
Chart.js not rendering properly until window resize or toggling line in legend
One suggested doing a chart refresh when everything is visible:
setTimeout(function() { myChart.update(); },1000);
In think in vue this could be done in the mount function.
I'm sure there is a more elegant way to handle this with a watch function or something similar for instance.
Updated:
As mentioned in the comments, I've seen references to people firing a window resize event manually using:
window.dispatchEvent(new Event('resize'));
I think it would probably work in the mounted function of the vue component:
export default {
name: 'graphs-component',
mounted: function(){
window.dispatchEvent(new Event('resize'));
}
}
You might even wrap it in a setTimeout to ensure everything is loaded.

Related

Instagram API / Flickity Carousel

Trying to integrate this on a site: https://github.com/mangcoding/instagram-feeder
I don't know enough about APIs to get it working for a username instead of a tag. I'm thinking it might have something to do with this line: let instaData = data.edge_hashtag_to_media.edges;
Anyone know how I could accomplish, thanks!
<script charset="utf-8">
(function ($) {
$(window).on('load', function () {
var limit = 20;
$.instagramFeed({
'tag': 'data', // want this to be 'username': 'data',
'get_data': true,
'callback': function (data) {
let instaData = data.edge_hashtag_to_media.edges;
instaData.slice(0, limit).filter(x => x.node.edge_media_to_caption.edges.length > 0)
.forEach(item => {
let node = item.node;
let source = $("#instagram-template").html();
let template = Handlebars.compile(source);
let taken = new Date(node.taken_at_timestamp * 1000)
.toDateString().substr(4);
//change format to month date,year
let created = taken.slice(0, 6) + ',' + taken.slice(6);
let context = {
link: "https://www.instagram.com/p/" + node
.shortcode + "/",
image_url: node.display_url,
countLikes: node.edge_liked_by.count,
caption: node.edge_media_to_caption.edges[0].node
.text,
created: created
};
let html = template(context);
$("#instagramFeed").append(html);
});
$('#instagramFeed').flickity({
cellAlign: 'left',
wrapAround: true,
pageDots: false,
setGallerySize: false,
prevNextButtons: true,
arrowShape: { "x0": 20, "x1": 60, "y1": 40, "x2": 60, "y2": 35, "x3": 25 }
});
}
});
});
})(jQuery);
</script>
Figured it out:
let instaData = data.edge_owner_to_timeline_media.edges;
vs
let instaData = data.edge_hashtag_to_media.edges;
<script charset="utf-8">
(function ($) {
$(window).on('load', function () {
var limit = 20;
$.instagramFeed({
'username': 'myusername',
'get_data': true,
'callback': function (data) {
let instaData = data.edge_owner_to_timeline_media.edges;
instaData.slice(0, limit).filter(x => x.node.edge_media_to_caption.edges.length > 0)
.forEach(item => {
let node = item.node;
let source = $("#instagram-template").html();
let template = Handlebars.compile(source);
let taken = new Date(node.taken_at_timestamp * 1000)
.toDateString().substr(4);
//change format to month date,year
let created = taken.slice(0, 6) + ',' + taken.slice(6);
let context = {
link: "https://www.instagram.com/p/" + node
.shortcode + "/",
image_url: node.display_url,
countLikes: node.edge_liked_by.count,
caption: node.edge_media_to_caption.edges[0].node
.text,
created: created
};
let html = template(context);
$("#instagramFeed").append(html);
});
$('#instagramFeed').flickity({
cellAlign: 'left',
wrapAround: true,
pageDots: false,
setGallerySize: false,
prevNextButtons: true,
arrowShape: { "x0": 20, "x1": 60, "y1": 40, "x2": 60, "y2": 35, "x3": 25 }
});
}
});
});
})(jQuery);
</script>

Adding markerclustergroup to leaflet overlay does not update in Vue.js app

I have an overlay control on my leaflet map in a vue.js application. It contains two layers. The ILZipCodes layer renders perfectly. However, the "markers" layer does not appear when I select the checkbox in the layer control. Why is this? I reckon I may be setting up the layer control and populating the clusters in the wrong sequence.
Cheers
<template>
<div>
<div class="mx-auto my-6 loader" v-if="isSearching"></div>
<div class="tooManyResultsError" v-if="tooManyResults">
Your search brought back too many results to display. Please zoom in or refine your search with the text box and
filters.
</div>
<div id="leafletMapId"></div>
</div>
</template>
<script>
//The center coordinate and zoom level that the map should initialize to
// to capture all of the continental United States
const INITIAL_CENTER_LATITUDE = 34;
const INITIAL_CENTER_LONGITUDE = -96;
const INITIAL_ZOOM = 4;
/* Leaflet performs slowly with reactivity ("observable" data object variables).
* To work around this, I removed myMap and markers from the data object.
*/
/* If the user zooms out or pans beyond the boundaries of the previous fetch's dataset, then
* the client fetches location data from the server to replace the previous map data. If the user
* zooms or pans but stays within the boundaries of the dataset currently displayed on the map, then
* the client does not run another fetch.
* */
import axios from "axios";
import store from "../store.js";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import "leaflet.markercluster/dist/leaflet.markercluster-src.js";
import "leaflet-ajax/dist/leaflet.ajax.js";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";
export default {
name: "ContactsMap",
mounted() {
this.fetchAggregatedDistrictStats();
},
methods: {
async fetchAggregatedDistrictStats() {
axios.get(... // fetches some statistics for the other overlay layers
);
},
createMapWithLeafletAndMapTiler() {
var $this = this;
var streetTilesLayer = L.tileLayer(MAPTILER_STREETS_URL, {
maxZoom: 18,
minZoom: 2,
attribution: MAPBOX_ATTRIBUTION,
tileSize: 512,
zoomOffset: -1
});
// eslint-disable-next-line
var satelliteTilesLayer = L.tileLayer(MAPTILER_SATELLITE_URL, {
maxZoom: 18,
minZoom: 2,
tileSize: 512,
zoomOffset: -1
});
var baseMaps = {
Satellite: satelliteTilesLayer,
Streets: streetTilesLayer
};
if (myMap != undefined) {
myMap.remove();
}
var myMap = L.map("leafletMapId", {
layers: [streetTilesLayer],
}).setView(this.center, this.zoom);
var markers = L.markerClusterGroup({
iconCreateFunction: function(cluster) {
var count = cluster.getChildCount();
var digits = (count + "").length;
return L.divIcon({
html: "<b>" + count + "</b>" + digits,
className: "cluster digits-" + digits,
iconSize: 22 + 10 * digits
});
}
});
async function fetchLocations(shouldProgrammaticallyFitBounds) {
markers.clearLayers();
markers = L.markerClusterGroup({
chunkedLoading: true,
iconCreateFunction: function(cluster) {
var count = cluster.getChildCount();
var digits = (count + "").length;
return L.divIcon({
html: "<b>" + count + "</b>",
className: "cluster digits-" + digits,
iconSize: 22 + 10 * digits
});
}
});
axios
.get("/maps/" + $this.list.list_id, {
//fetches markerclusters
})
.then(
response => {
$this.tooManyResults = false;
var addressPoints = response.data.recordsList;
for (var i = 0; i < addressPoints.length; i++) {
var a = addressPoints[i];
var title = a[2];
var marker = L.marker(L.latLng(a[0], a[1]));
marker.bindPopup(title);
markers.addLayer(marker); // This is where I'm adding the markers and markerclusters to the layer titled "markers"
// myMap.addLayer(markers); //If I uncomment this, then the markers layer is always on the map, i.e. not as an overlay layer
}
},
error => {
$this.isSearching = false;
document.getElementById("leafletMapId").style.display = "block";
store.setErrorMessage("Network error searching list", error);
}
);
}
myMap.on("zoomend", handlerFunction);
myMap.on("dragend", handlerFunction);
var defaultPolygonStyle = {
color: "black",
weight: 1,
opacity: 0.8,
fillOpacity: 0.1
};
var NationalCongressional = new L.geoJson.ajax(
"http://localhost:8080/assets/geo/NationalCongressional.json",
{
style: defaultPolygonStyle,
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.NAMELSAD);
if (feature.properties.NAMELSAD == "Congressional District 8") {
layer.setStyle({ color: "orange" });
}
}
}
);
function getColorFromRedBlueRange(d) {
return d > 0.8
? "#FF0000"
: d > 0.7
? "#FF006F"
: d > 0.55
? "#FF00EF"
: d > 0.45
? "#DE00FF"
: d > 0.3
? "#BC00FF"
: d > 0.2
? "#6600FF"
: "#00009FF";
}
var ILZipCodes = new L.geoJson.ajax(
"https://raw.githubusercontent.com/OpenDataDE/State-zip-code-GeoJSON/master/il_illinois_zip_codes_geo.min.json",
{
// style: defaultPolygonStyle,
onEachFeature: function(feature, layer) {
layer.bindPopup(
feature.properties.ZCTA5CE10 +
", " +
$this.zipData[feature.properties.ZCTA5CE10]
);
layer.setStyle({
color: getColorFromRedBlueRange(
$this.zipData[feature.properties.ZCTA5CE10]
),
weight: 0,
fillOpacity: 0.3
});
}
}
);
var overlays = {
Voters: voterGroup,
ILZipCodes: ILZipCodes,
};
L.control.layers(baseMaps, overlays).addTo(myMap);
fetchLocations(true);
}
}
};
You add voterGroup to your Layers Control, instead of your markers.
Then simply do not re-assign a MarkerClusterGroup into your markers variable (after you use clearLayers) and you should be fine.

Customize the tooltip of Chart.js

I'm using the last version of vue and vue-chart.js.
I'd like to customize the tooltip which is displayed when hovering a point.
Issue
The tooltip is not changed from the default one
Question
How to customize the tooltip. Ultimately I'd like to be able to click on a link in the tool tip to trigger a dialog that would display details taken from data contained in my vue component.
Vue.component('line-chart', {
extends: VueChartJs.Line,
mounted () {
this.renderChart({
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'Data One',
backgroundColor: '#f87979',
data: [40, 39, 10, 40, 39, 80, 40]
}
]
}, {
tooltips: {
custom: function(tooltipModel) {
// Tooltip Element
var tooltipEl = document.getElementById('chartjs-tooltip');
// Create element on first render
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = "<table></table>"
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
if (tooltipModel.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltipModel.yAlign) {
tooltipEl.classList.add(tooltipModel.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltipModel.body) {
var titleLines = tooltipModel.title || [];
var bodyLines = tooltipModel.body.map(getBody);
var innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
var colors = tooltipModel.labelColors[i];
var style = 'background:' + colors.backgroundColor;
style += '; border-color:' + colors.borderColor;
style += '; border-width: 2px';
var span = '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
innerHtml += '<tr><td>' + span + body + '</td></tr>';
});
innerHtml += '</tbody>';
var tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
// `this` will be the overall tooltip
var position = this._chart.canvas.getBoundingClientRect();
// Display, position, and set styles for font
tooltipEl.style.opacity = 1;
tooltipEl.style.left = position.left + tooltipModel.caretX + 'px';
tooltipEl.style.top = position.top + tooltipModel.caretY + 'px';
tooltipEl.style.fontFamily = tooltipModel._fontFamily;
tooltipEl.style.fontSize = tooltipModel.fontSize;
tooltipEl.style.fontStyle = tooltipModel._fontStyle;
tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px';
}
},
responsive: true,
maintainAspectRatio: false
})
}
})
var vm = new Vue({
el: '.app',
data: {
message: 'Hello World'
}
})
https://codepen.io/anon/pen/ooyMMG
Remove this from html=
tooltips: {
Add this one line = enabled:false,
custom: function(tooltipModel)

Dynamically update lines in Highcharts time series chart

Here I'm working on Highcharts time series chart with live streaming data, based on the sample jsfiddle. In the fiddle there shows 4 lines named as input1, input2, input3, & input 4 and it is updated with live random data but in my actual project the input values are updated via MQTT. In actual project, sometimes, when we push streaming data, there will be increase or decrease in no: of inputs (such as input5, input6 like wise). So how can we add new line or remove line dynamically in time series chart with streaming data.
javascript code :
$(function() {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series;
var length = series.length;
setInterval(function() {
var x = (new Date()).getTime(), // current time
a0 = Math.random();
a1 = Math.random();
a2 = Math.random();
series[0].addPoint([x, Math.random()], true, true);
for (var i = 1; i < length; i++) {
series[i].addPoint([x, Math.random()], false, true);
}
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
legend: {
enabled: true
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
exporting: {
enabled: false
},
series: [{
name: 'input1',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'input2',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'input3',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'input4',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});

DataTables image (or at least image title) export to PDF

Using DataTables and Buttons (NOT TableTools, which is retired) extension. Some cells have progressbars and small icons. Is there a way to export these images (or at least their titles) to PDF? Found some possible hacks on this page, but all of them were for retired TableTools.
Checked https://datatables.net/reference/button/pdf and https://datatables.net/reference/api/buttons.exportData%28%29 but couldn't find any method to achieve this goal. Tested by adding this code:
stripHtml: false
but whole HTML code (like img src=...) was included in PDF file instead of images.
If exporting images isn't possible, is there a way to export at least alt or title attribute of each image? That would be enough.
I assume you are using pdfHtml5. dataTables is using pdfmake in order to export pdf files. When pdfmake is used from within a browser it needs images to be defined as base64 encoded dataurls.
Example : You have rendered a <img src="myglyph.png"> in the first column of some of the rows - those glyphs should be included in the PDF. First create an Image reference to the glyph :
var myGlyph = new Image();
myGlyph.src = 'myglyph.png';
In your customize function you must now
1) build a dictionary with all images that should be included in the PDF
2) replace text nodes with image nodes to reference images
buttons : [
{
extend : 'pdfHtml5',
customize: function(doc) {
//ensure doc.images exists
doc.images = doc.images || {};
//build dictionary
doc.images['myGlyph'] = getBase64Image(myGlyph);
//..add more images[xyz]=anotherDataUrl here
//when the content is <img src="myglyph.png">
//remove the text node and insert an image node
for (var i=1;i<doc.content[1].table.body.length;i++) {
if (doc.content[1].table.body[i][0].text == '<img src="myglyph.png">') {
delete doc.content[1].table.body[i][0].text;
doc.content[1].table.body[i][0].image = 'myGlyph';
}
}
},
exportOptions : {
stripHtml: false
}
}
Here is a an example of a getBase64Image function
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL("image/png");
}
If you just want to show the title of images in the PDF - or in any other way want to manipulate the text content of the PDF - then it is a little bit easier. The content of each column in each row can be formatted through the exportOptions.format.body callback :
buttons : [
{
extend : 'pdfHtml5',
exportOptions : {
stripHtml: false
format: {
body: function(data, col, row) {
var isImg = ~data.toLowerCase().indexOf('img') ? $(data).is('img') : false;
if (isImg) {
return $(data).attr('title');
}
return data;
}
}
}
]
The reason format.body cannot be used along with images is that is only let us pass data back to the text node part of the PDF document.
See also
http://pdfmake.org/#/gettingstarted (look for Images section)
https://github.com/bpampuch/pdfmake/blob/master/examples/images.js
Since no suggestions received, I had to make a hack in order to get PDF file formatted the way I want.
In case someone has the same issue, you can use hidden span to display image alt/title near image itself. I'm sure it's not the best practice, but it will do the trick. So the code will look like:
<img src='image.png' alt='some_title'/><span class='hidden'>some_title</span>
This way datatables will show only the image, while PDF file will contain text you need.
This is my CODE!
HTML
<div class="dt-btn"></div>
<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>
JAVASCRIPT
$.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: 11, 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:
// NAME
var _text = { margin:[0, 0, 0, 3], color:"#000000", fillColor:'#ffffff', bold:true, fontSize:13, alignment:'center', text:bodytext[j] };
break;
case 1:
// GRADE
var _text = { margin:[0, 0, 0, 3], color:"blue", fillColor:'#ffffff', bold:false, fontSize:11, alignment:'left', text:bodytext[j] };
break;
case 3:
// CODE
var _text = { margin:[0, 0, 0, 3], color:"#000000", fillColor:'#ffffff', bold:true, fontSize:11, alignment:'left', text:bodytext[j] };
break;
default:
// OTHERS
var _text = { margin:[0, 0, 0, 3], color:"#000000", fillColor:'#ffffff', bold:false, fontSize:11, 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 } ]
});
var table = $('#table').DataTable();
table.buttons().container().appendTo('.dt-btn');
$('.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');
});
$.fn.dataTable.Buttons.defaults.dom.container.className = '';
$.fn.dataTable.Buttons.defaults.dom.button.className = 'btn';
PHP
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]);
}
[Sample][1]: https://i.stack.imgur.com/35Wlm.jpg
In addition to davidkonrad's answer. I created dynamically all base64 images and used them in Datatables pdfmake like this:
for (var i = 1; i < doc.content[2].table.body.length; i++) {
if (doc.content[2].table.body[i][1].text.indexOf('<img src=') !== -1) {
html = doc.content[2].table.body[i][1].text;
var regex = /<img.*?src=['"](.*?)['"]/;
var src = regex.exec(html)[1];
var tempImage = new Image();
tempImage.src = src;
doc.images[src] = getBase64Image(tempImage)
delete doc.content[2].table.body[i][1].text;
doc.content[2].table.body[i][1].image = src;
doc.content[2].table.body[i][1].fit = [50, 50];
}
//here i am removing the html links so that i can use stripHtml: true,
if (doc.content[2].table.body[i][2].text.indexOf('<a href="details.php?') !== -1) {
html = $.parseHTML(doc.content[2].table.body[i][2].text);
delete doc.content[2].table.body[i][1].text;
doc.content[2].table.body[i][2].text = html[0].innerHTML;
}
}