PdfMake list of items to Repeat (checkbox next to text) - javascript

I am using the pdfMake and I Ihave a text next to a image I would like to repeat that part in my docdefintion.
I would like to repeate this part of my pdfmake
{
columns: [
{
image: "checked",
height: 10,
width: 10
},
{
stack: [
{
columns: [
{
text: 'First column first line',
width: '50%',
margin: [5, 0, 0, 0],
}
]
}
],
width: '*'
}]
}
Here is my docDefinition
let docDefinition = {
pageSize: 'LEGAL',
//pageOrientation: 'landscape', //may be usefull in some case
pageMargins: [40, 80, 40, 60],
content: [
{
...
this.getFailureLocationObject(),
...
}
};
pdfMake.createPdf(docDefinition).download('Intervention' + '19060023');
}
I have made this function that should return a object list (ol) I have o the object that I want to push into ol when the function retuns o there is no problem my image is displayed next to the text However when I return ol insted there is a wierd result where the image and text are no longer aligned and no mater how may objects I add to ol the result is the same there is only one image displayed next to the text. How can I fix this issues thank you for your help.
getFailureLocationObject() {
const ol = [];
var o = {
columns: [
{
image: "checked",
height: 10,
width: 10
},
{
stack: [
{
columns: [
{
text: 'First column first line',
width: '50%',
margin: [5, 0, 0, 0],
}
]
}
],
width: '*'
}]
};
ol.push(o);
ol.push(o);
return o;
}
Here you can try what I have made so far. And see the issus I have hard coded 'First column first line','First column Second line','First column Third line'. However I would like the method this.getFailureLocationObject(), too loop and make the list.
Try it out here!
https://stackblitz.com/edit/angular-pdfmake-example-3f14km?file=src%2Fapp%2Fapp.component.ts

After a bit of testing with the code you provided, I figured out that the problem is the reference of the objects.
So, when pdfmake gets the values, somehow, if both have same reference (are the same object) it mixes them.
I came to this conclusion because when you change the code you have with:
getFailureLocationObject() {
const ol = [];
var o = {
columns: [
{
image: 'checked',
height: 10,
width: 10,
},
{
stack: [
{
columns: [
{
text: 'First column first line',
width: '50%',
margin: [5, 0, 0, 0],
},
],
},
],
width: '*',
},
],
};
ol.push(o);
o = JSON.parse(JSON.stringify(o));
ol.push(o);
return ol;
}
The error no longer occurs. Note that JSON.parse(JSON.stringify(o)) creates a new JSON object with the same content as o, meaning the two objects in the array are different (as the objects are not the same)
This might be an issue to be reported to the developers of the plugin to be fixed. For now, the solution is to add different objects to the array using clone. There is a good explaination on how and why to use cloning here.
Feel free to ask for clarification if needed!

Related

Why does Cytoscape go into an "infinite" loop in this specific situation?

If I clone a layout configuration with Object.assign and try to use that layout, cytoscape quickly causes an out of memory error. I can work around this by just defining a second layout mostly identical to the first and not cloning, but I am interested to know the reason behind the problem, or if it's a possible bug in cytoscape.
With this example code, click add and layout 2 right after loading the page and it will hang/run out of memory. (Have your task manager handy to kill your tab or browser.) Different combinations of adding nodes and running the cloned layout will mostly hang, but not always.
let cy
const layout1 = {
name: 'euler',
springLength: edge => 80,
mass: node => 4,
randomize: true,
animate: false,
gravity: -1.2,
maxIterations: 1000,
maxSimulationTime: 4000,
}
const layout2 = Object.assign({}, layout1, {
fit: false,
animate: true,
randomize: false,
})
document.addEventListener('DOMContentLoaded', function() {
cy = cytoscape({
container: document.getElementById('cy'),
layout: layout1,
style: [
{
selector: 'node',
style: {
label: 'data(id)',
},
},
],
elements: [
{ data: { id: 'a' } },
{ data: { id: 'b' } },
{ data: { id: 'a_b', source: 'a', target: 'b' } },
],
})
})
function add() {
cy.add([
{ data: { id: 'c' } },
{ data: { id: 'd' } },
{ data: { id: 'c_d', source: 'c', target: 'd' } },
])
// cy.layout(layout2).run()
}
function doLayout1() {
cy.layout(layout1).run()
}
function doLayout2() {
cy.layout(layout2).run()
}
function addAndLayout2() {
add()
doLayout2()
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.5.0/cytoscape.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cytoscape-euler#1.2.1/cytoscape-euler.min.js"></script>
</head>
<style>
body {
height: 100%;
}
#cy {
height: 100%;
flex-grow: 1;
}
.main {
height: 100vh;
display: flex;
flex: 1;
}
</style>
<body>
<button onclick="add()">add nodes</button>
<button onclick="doLayout1()">layout 1</button>
<button onclick="doLayout2()">layout 2</button>
<button onclick="addAndLayout2()">add and layout 2</button>
<div class="main">
<div id="cy"></div>
</div>
</body>
</html>
This has nothing to do with Ojbect.assign (even if you did not copy the object properly, it should not hang).
The reason is the randomize option. For this particular graph, when the randomize option is set to false, the layout never ends. Just remove randomize: false from the second layout, or after adding the new nodes and before running layout2, run the random layout (or just randomize the nodes manually) -- the layout2 will terminate.
The problem is that: the layout must terminate at some point (in the worst case when the umber of max iterations is reached). But this particular layout never terminates.
The interesting thing is that this simple graph turns out to be one of the worst cases for some other layout algorithms as well (for randomized: false). I tried cose-bilkent. It also takes a little bit longer and terminates when the maximum number of iterations is reached (setting numIter option to lower number will result in early termination, worse quality) -- but the result is really bad.

C3 and React - DOMException

I'm trying to use C3 to render a chart in my React project.
The problem
What I do is dynamically generate an id (UUID) and attach it to a div in my chart component. I then call some code after the component has rendered in componentDidMount. This is a common pattern, I have seen it in other projects.
At first, everything seemed fine. However, after repeatedly refreshing the page, sometimes the chart generation does not work. The error I get is:
DOMException: Failed to execute 'querySelector' on 'Document': '#a-really-long-id' is not a valid selector.
What I tried
I tried using setTimeout to delay when the chart was attached, but curiously I still got the same result, even after a 10 second delay. This leads me to believe that this is not a race condition, and caused by something else. Maybe C3 reads the DOM once and does not respond to changes? But that would not explain why it works sometimes...
Even trying to select the element by id from the Chrome developer console did not work.
Code
Here is my full component code:
// assets/js/index.jsx
import React from 'react';
import uuid from 'uuid/v4';
import c3 from 'c3';
class Chart extends React.Component {
constructor(props) {
super(props);
this.id = uuid();
this._update = this._update.bind(this);
}
_update() {
const data = this.props.data;
this.chart = c3.generate({
bindto: `#${this.id}`,
data: {
columns: [
['Male', 0],
['Female', 0],
['Brand', 0]
],
type: 'bar',
colors: {
Male: '#0066CC',
Female: '#FF6666',
Brand: '#808080'
},
groups: [
['Male', 'Female', 'Brand']
],
order: null
},
bar: {
width: {
ratio: 0.3
}
},
transition: {
duration: 500
},
tooltip: {
show: false
},
axis: {
x: { show: false },
y: { show: false },
},
size: { width: 220, height: 320 },
grid: {
x: { show: false }
},
legend: {
show: false
}
});
setTimeout(function() {
this.chart.load({
columns: [
['Male', data.male],
['Female', data.female],
['Brand', data.brand]
]
});
}, 500);
}
componentDidMount() {
this._update();
}
render() {
return (
<div id={this.id} className="chart"></div>
);
}
}
export default Chart;
This can be added as a comment, but since its big, adding it as an answer.
Are you using html4/ html5 semantics?
As per HTML4 (https://www.w3.org/TR/html401/types.html)
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
As per HTML5 (https://www.w3.org/TR/html5/dom.html)
When specified on HTML elements, the id attribute value must be unique
amongst all the IDs in the element’s tree and must contain at least
one character. The value must not contain any space characters.
Your uuid might be generating a valid Id sometimes and sometimes it might not (not sure how uuid works)
If you are not using HTML5 semantics, you can simply add <!DOCTYPE html>
at the top of your html document and give a try.
Also,
You used settimeout in your logic and within that you used this.Chart
this, now will refer to settimeout rather than the class.
Can you try changing
setTimeout(function() {
this.chart.load({
columns: [
['Male', data.male],
['Female', data.female],
['Brand', data.brand]
]
});
}, 500);
to
setTimeout( () => {
this.chart.load({
columns: [
['Male', data.male],
['Female', data.female],
['Brand', data.brand]
]
});
}, 500);

Creating a custom library in javascript for a table

I'm trying to build a custom library for my table, I want to add an option where for each column (th) I may be able to defined their width depends to what I declared. For example I only need to define the width of the first and second column (th) and I have 8 columns, there rest of the column should have width.
My sample snippets inside my table prototype:
init: function (el, options) {
column: {
width: [20, 200, 500]
}
}
I am not really sure how to, since I'm starting to learn javascript. For now I'm just up to adding the width, sooner or later I'll be adding more options inside the column, like color etc.
Additional information: I want pure JavaScript without using other library (jQuery) to my library.
Model-wise you probably want something like:
{
columns: [ {
label: "Foo",
width: 50 // px
}, {
label: "Bar",
width: 100 // px
}, {
label: "Baz",
width: "*"
} ]
}
instead of
{
column_widths: [ 50, 100, "*" ]
column_labels: [ "Foo", "Bar", "Baz" ]
}
The "*" would translate to a column with no defined width so the browser will decide how wide it is. Whether that is desirable or not is up to you.

Json data not showing in extjs grid

Given data in the form:
var grid_data = [ {Hello: 'World'}, {Jesus:'Navas'} ]
I wish to draw a grid like so:
The grid shows with 2 rows but with no data, I can't find the problem in the following code:
var grid_store = Ext.create('Ext.data.Store', {
fields: [
{name: 'Property'},
{name: 'Value'}
],
data: grid_data
});
// create the Grid
var grid_view = Ext.create('Ext.grid.Panel', {
store: grid_store,
renderTo: 'info_panel',
stateful: true,
stateId: 'stateGrid',
columns: [
{
text : 'Property',
width : 100,
sortable : true,
dataIndex: 'Property'
},
{
text : 'Value',
width : 80,
sortable : false,
dataIndex: 'Value'
}
],
height: 350,
width: 600,
title: 'Array Grid',
viewConfig: {
stripeRows: true
}
});
Renders to:
<div id="info_panel"></div>
If you're wondering how I got the example image, I changed the store to an ArrayStore and re-formatted the data into arrays, but I'd prefer to miss out that step and insert the data as-is.
edit:
I think what I'm really asking for is a way to alert extjs to use the JSON keys as values, as opposed to most of the grid examples out there that take the form:
{value: 'Hello'}, {property: 'World'}
As one of the commenters and your edit suggested, your grid is built to consume a json with 'Property' and 'Value' being the keys for the json objects. I don't know if it's possible for you to change the source of the data to send in the reformatted json, but if not, you can always just run a quick loop to do so after receiving the data:
var new_data = [];
Ext.each(grid_data, function(obj) {
for (var prop in obj) {
new_data.push({
Property: prop,
Value: obj[prop]
});
}
}, this);

Render dynamic components in ExtJS 4 GridPanel Column with Ext.create

I've got an ExtJS (4.0.7) GridPanel that I'm populating from a store. The values that I display in the GridPanel's column need to have a different view depending on the type of data that's in the record.
The ultimate goal is that records with "double" or "integer" value for the record's type property present a slider to the user that they can adjust, and a type of "string" just renders some read-only text.
I've created a custom Column to do this. It inspects the type in the renderer and determines what to render.
I've got the "string" working fine with the code below, but struggling with how I can dynamically create and render the more complicated slider control in the column.
This simplified example is just trying to render a Panel with a date control in it as if I can get that going, I can figure out the rest of the slider stuff.
Ext.define('MyApp.view.MyColumn', {
extend: 'Ext.grid.column.Column',
alias: ['widget.mycolumn'],
stringTemplate: new Ext.XTemplate('code to render {name} for string items'),
constructor: function(cfg){
var me = this;
me.callParent(arguments);
me.renderer = function(value, p, record) {
var data = Ext.apply({}, record.data, record.getAssociatedData());
if (data.type == "string") {
return me.renderStringFilter(data);
} else if (data.type == "double" || data.type == "integer") {
return me.renderNumericFilter(data);
} else {
log("Unknown data.type", data);
};
},
renderStringFilter: function(data) {
// this works great and does what I want
return this.stringTemplate.apply(data);
},
renderNumericFilter: function(data) {
// ***** How do I get a component I "create" to render
// ***** in it's appropriate position in the gridpanel?
// what I really want here is a slider with full behavior
// this is a placeholder for just trying to "create" something to render
var filterPanel = Ext.create('Ext.panel.Panel', {
title: 'Filters',
items: [{
xtype: 'datefield',
fieldLabel: 'date'
}],
renderTo: Ext.getBody() // this doesn't work
});
return filterPanel.html; // this doesn't work
}
});
My problem really is, how can I Ext.create a component, and have it render into a column in the gridpanel?
There are a few ways that I have seen this accomplished. Since the grid column is not an Ext container it can not have Ext components as children as part of any configuration the way other container components can. Post grid-rendering logic is required to add Ext components to cells.
This solution modifies your custom column render so that it puts a special css class on the rendered TD tag. After the grid view is ready, the records are traversed and the custom class is found for appropriate special columns. A slider is rendered to each column found.
The code below is a modified version of the ext js array grid example provided in the Sencha examples. The modification mixes in the custom column renderer and the post grid rendering of sliders to TD elements.
This example only includes enough modification of the Sencha example to show the implementation ideas. It lacks separated view and controller logic.
This is modified from here
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.data.Model'
]);
Ext.onReady(function() {
// sample static data for the store
Ext.define('Company', {
extend: 'Ext.data.Model',
fields: ['name', 'price', 'change', 'pctChange', 'lastUpdated', 'type']
});
var myData = [
['3m Co', 71.72, 2, 0.03, '9/1/2011', 'integer'],
['Alcoa Inc', 29.01, 4, 1.47, '9/1/2011', 'string'],
['Altria Group Inc', 83.81, 6, 0.34, '9/1/2011', 'string'],
['American Express Company', 52.55, 8, 0.02, '9/1/2011', 'string'],
['American International Group, Inc.', 64.13, 2, 0.49, '9/1/2011', 'integer'],
['AT&T Inc.', 31.61, 4, -1.54, '9/1/2011', 'integer'],
['Boeing Co.', 75.43, 6, 0.71, '9/1/2011', 'string'],
['Caterpillar Inc.', 67.27, 8, 1.39, '9/1/2011', 'integer'],
['Citigroup, Inc.', 49.37, 1, 0.04, '9/1/2011', 'integer'],
['E.I. du Pont de Nemours and Company', 40.48, 3, 1.28, '9/1/2011', 'integer'],
['Exxon Mobil Corp', 68.1, 0, -0.64, '9/1/2011', 'integer'],
['General Electric Company', 34.14, 7, -0.23, '9/1/2011', 'integer']
];
// create the data store
var store = Ext.create('Ext.data.ArrayStore', {
model: 'Company',
data: myData
});
// existing template
stringTemplate = new Ext.XTemplate('code to render {name} for string items');
// custom column renderer
specialRender = function(value, metadata, record) {
var data;
data = Ext.apply({}, record.data, record.getAssociatedData());
if (data.type == "string") {
return stringTemplate.apply(data);;
} else if (data.type == "double" || data.type == "integer") {
// add a css selector to the td html class attribute we can use it after grid is ready to render the slider
metadata.tdCls = metadata.tdCls + 'slider-target';
return '';
} else {
return ("Unknown data.type");
}
};
// create the Grid
grid = Ext.create('Ext.grid.Panel', {
rowsWithSliders: {},
store: store,
stateful: true,
stateId: 'stateGrid',
columns: [{
text: 'Company',
flex: 1,
sortable: false,
dataIndex: 'name'
}, {
text: 'Price',
width: 75,
sortable: true,
renderer: 'usMoney',
dataIndex: 'price'
}, {
text: 'Change',
width: 75,
sortable: true,
dataIndex: 'change',
renderer: specialRender,
width: 200
}, {
text: '% Change',
width: 75,
sortable: true,
dataIndex: 'pctChange'
}, {
text: 'Last Updated',
width: 85,
sortable: true,
renderer: Ext.util.Format.dateRenderer('m/d/Y'),
dataIndex: 'lastUpdated'
}],
height: 350,
width: 600,
title: 'Irm Grid Example',
renderTo: 'grid-example',
viewConfig: {
stripeRows: true
}
});
/**
* when the grid view is ready this method will find slider columns and render the slider to them
*/
onGridViewReady = function() {
var recordIdx,
colVal,
colEl;
for (recordIdx = 0; recordIdx < grid.store.getCount(); recordIdx++) {
record = grid.store.getAt(recordIdx);
sliderHolder = Ext.DomQuery.select('.slider-target', grid.view.getNode(recordIdx));
if (sliderHolder.length) {
colEl = sliderHolder[0];
// remove div generated by grid template - alternative is to use a new template in the col
colEl.innerHTML = '';
// get the value to be used in the slider from the record and column
colVal = record.get('change');
// render the slider - pass in the full record in case record data may be needed by change handlers
renderNumericFilter(colEl, colVal, record)
}
}
}
// when the grids view is ready, render sliders to it
grid.on('viewready', onGridViewReady, this);
// modification of existing method but removed from custom column
renderNumericFilter = function(el, val, record) {
var filterPanel = Ext.widget('slider', {
width: 200,
value: val,
record: record,
minValue: 0,
maxValue: 10,
renderTo: el
});
}
});
I did something like this when I needed to render a small chart (essentially a spark chart) in a grid column. This solution is similar to sha's, but it's more robust and delegates the rendering to the component being rendered rather than the Column, which doesn't really have a render chain.
First, the column class:
Ext.define("MyApp.view.Column", {
extend: "Ext.grid.column.Column",
// ...
renderer: function (value, p, record) {
var container_id = Ext.id(),
container = '<div id="' + container_id + '"></div>';
Ext.create("MyApp.view.Chart", {
type: "column",
// ...
delayedRenderTo: container_id
});
return container;
}
});
Note the delayedRenderTo config option. Just like renderTo, this will be the DOM ID of the element that the chart component will render to, except that it doesn't need to be present in the DOM at the time of creation.
Then the component class:
Ext.define("MyApp.view.Chart", {
extend: "Ext.chart.Chart",
// ...
initComponent: function () {
if (this.delayedRenderTo) {
this.delayRender();
}
this.callParent();
},
delayRender: function () {
Ext.TaskManager.start({
scope: this,
interval: 100,
run: function () {
var container = Ext.fly(this.delayedRenderTo);
if (container) {
this.render(container);
return false;
} else {
return true;
}
}
});
}
});
So during initComponent(), we check for delayed render and prepare that if necessary. Otherwise, it renders as normal.
The delayRender() function itself schedules a task to check every so often (100ms in this case) for the existence of an element with the given ID — i.e., to check whether the column has rendered. If not, returns true to reschedule the task. If so, renders the component and returns false to cancel the task.
We've had good luck with this in the field, so I hope it works for you too.
By the way, I was developing this as a part of answering my own question about ExtJS charting. That thread has the results of my performance testing. I was rendering 168 chart components in grid columns in 3-4s across most browsers and OSes. I imagine your sliders would render much faster than that.
Try something like this:
renderNumericFilter: function () {
var id = Ext.id();
Ext.defer(function () {
Ext.widget('slider', {
renderTo: id,
width: 200,
value: 50,
increment: 10,
minValue: 0,
maxValue: 100,
});
}, 50);
return Ext.String.format('<div id="{0}"></div>', id);
}
But I must say whatever you're trying to do - it doesn't sound right :) I don't think a bunch of sliders inside the grid will look good to the user.

Categories