Text under image not printed properly if the td contains an image in Jspdf autotable - jspdf

This is my table td This is the pdf rendered using autotable. I want to display the image first and then the text under it. Any help will be appreciated. Thanks in advance.
What I did try is the below code.
didDrawCell: function(data) { if (data.column.index === 3 && data.cell.section === 'body') { var td = data.cell.raw; var img = td.getElementsByTagName('img')[0]; var dim = data.cell.height - data.cell.padding('vertical'); var textPos = data.cell.textPos; if(img){ doc.addImage(img.src, textPos.x, textPos.y, dim, dim); } } },

Related

AddEventListener only works with the last picture

I have one problem. addEventListener only works with the last element of the loop. I know what is the problem, but I can't figure it out. I get the JSON object from another function with the information. Later on the left side there should be clickable pictures. After clicking it I should get the same picture on the right side showed. Still it works only with the last one.
function myFunction(obj) {
var listItems = document.getElementsByClassName("newimg");
for (var i = 0; i < obj.length; i++) {
(function (i) {
document.getElementById("imgSmall").innerHTML += `<br></br><img id="${i}" class="newimg" src=${obj[i].download_url} >`;
let p = obj[i];
listItems[i].addEventListener('click', function() { makeithappen(p);},true);
}(i));
//obj[i].width,obj[i].height,obj[i].author,obj[i].download_url>
}
}
function makeithappen(k) {
document.getElementById("imgLarge").innerHTML = `<br class="text"> AUTHOR: ${k.author}, WIDTH: ${k.width}, HEIGHT: ${k.height}</br><img class="img2" src=${k.download_url} >`;
}
For quick fix.
Replace in your code
listItems[i].addEventListener('click', function() { makeithappen(p);},true);
with
listItems[i].onload = function() {
listItems[i].addEventListener('click', function () { makeithappen(p); }, true);
}
So when you got your listItems you weren't finished with the creation of more images. So new image means new list.
for (let i = 0; i < obj.length; i++) {
document.getElementById("imgSmall").innerHTML += `<br></br><img id="${i}" class="newimg" src=${obj[i].download_url}>`;
const listItems = document.getElementsByClassName("newimg");
listItems[i].addEventListener('click', function () { makeithappen(p); }, true);
}
function makeithappen(k) {
document.getElementById("imgLarge").innerHTML = `<br class="text"> AUTHOR: ${k.author}, WIDTH: ${k.width}, HEIGHT: ${k.height}</br><img class="img2" src=${k.download_url} >`;
}
Pleas do refactor <br></br> into something with css, margin or padding or whatever. This will then allow you to create the images with let div = document.createElement('img') and bind the event listener directly div.addEventlistener(...)

Textarea functions don't work with contenteditable elements that are not textareas

I'm trying to make a scrollbar stay down with this function (Tampermonkey, on the website: 'https://dictation.io/speech'):
setInterval(function() {
document.getElementsByClassName('ql-editor').scrollTop = document.getElementsByClassName('ql-editor').scrollHeight;
}, 500);
It worked before on another website.
I've fixed the height of the text box, so this scrollbar appears when there is enough of text:
div.notepad {
height : 771px;
}
I've tried doing this:
setInterval(function() {
document.getElementById("speech").scrollTop = document.getElementById("speech").scrollHeight;
}, 500);
and this (to make it read only, but it also doesn't work):
document.getElementById("speech").readOnly = true;
document.getElementsByClassName("ql-editor").readOnly = true;
I'm simply trying to keep the scrollbar always down. And I tried all possible ids and classnames. It worked very well on another website (the textbox was such: <textarea class="-metrika-nokeys" name="docel" id="docel" style="width: 100%;" cols="80" rows="20" spellcheck="true"></textarea>). But nothing has any effect on the text box on this website.
Thank you for any help in advance!
P.S. The problem is universal. This code (and when it's ".ql-editor" instead of '#speech') also doesn't work:
var input = document.querySelector('#speech');
var textarea = document.querySelector('#speech');
var reset = function(e) {
var context = this;
setTimeout(function() {
var len = context.value.length;
context.setSelectionRange(len, len);
}, 100);
};
input.addEventListener('copy', reset, false);
textarea.addEventListener('copy', reset, false);
I was able to solve it (probably not the best solution) by creating a textarea, copying text there from the div, and applying all those functions to that textarea.
Here is the code:
Creating a textarea:
var div = document.getElementById("speech");
var input = document.createElement("textarea");
input.setAttribute("id", "normaltext");
input.name = "post";
input.cols = "80";
input.rows = "2";
div.appendChild(input); //appendChild
Copying everything from the div to the textarea:
setInterval(function copyText() {
$("#normaltext").val($(".ql-editor").text());
}, 100);
Applying functions:
var input1 = document.querySelector('#normaltext');
var textarea1 = document.querySelector('#normaltext');
var reset = function(e) {
var context = this;
setTimeout(function() {
var len = context.value.length;
context.setSelectionRange(len, len);
}, 100);
};
input1.addEventListener('copy', reset, false);
textarea1.addEventListener('copy', reset, false);
setInterval(function() {
document.getElementById("normaltext").scrollTop = document.getElementById("normaltext").scrollHeight;
}, 500);
That works for me, but maybe someone will come up with a better solution.

HTML2Canvas creating multiple divs

I'm trying to create a PDF using jsPDF and HTML2Canvas.
I have multiple DIVs to insert into the PDF.
If I try to put all DIVs into a container and render once then it only puts the first page height into the PDF.
Can't figure out how to render multiple divs and stick them in the same PDF so that it keeps going page by page.
JAVASCRIPT
function genPDF() {
html2canvas(document.getElementById("container"), {
onrendered: function (canvas) {
var img = canvas.toDataURL();
var doc = new jsPDF();
doc.addImage(img, 'PNG');
doc.addPage();
doc.save('test.pdf');
}
});
}
HTML
<div id="container">
<div class="divEl" id="div1">Hi <img src="img1.JPG"> </div>
<div class="divEl" id="div2">Why <img src="img2.PNG"> </div>
</div>
<button onClick="genPDF()"> Click Me </button>
Add each of your images separately.
You need to wait for all the html2canvas renderings are done and added to pdf and then save your final pdf.
One way to achieve this by using JQuery and array of promises, actual code would look like this:
function genPDF() {
var deferreds = [];
var doc = new jsPDF();
for (let i = 0; i < numberOfInnerDivs; i++) {
var deferred = $.Deferred();
deferreds.push(deferred.promise());
generateCanvas(i, doc, deferred);
}
$.when.apply($, deferreds).then(function () { // executes after adding all images
doc.save('test.pdf');
});
}
function generateCanvas(i, doc, deferred){
html2canvas(document.getElementById("div" + i), {
onrendered: function (canvas) {
var img = canvas.toDataURL();
doc.addImage(img, 'PNG');
doc.addPage();
deferred.resolve();
}
});
}
For me it works like that:
$('#cmd2').click(function () {
var len = 4; //$x(".//body/div/div").length
var pdf = new jsPDF('p', 'mm','a4');
var position = 0;
Hide
for (let i = 1;i <= len; i++){
html2canvas(document.querySelector('#pg'+i),
{dpi: 300, // Set to 300 DPI
scale: 1 // Adjusts your resolution
}).then(canvas => {
pdf.addImage(canvas.toDataURL("images/png", 1), 'PNG', 0,position, 210, 295);
if (i == len){
pdf.save('sample-file.pdf');
}else{
pdf.addPage();
}
});
}
});
You could try this, using the follwing javascript references in the HTML. Html2Canvas and jsPDF are quite picky with versions you use.
https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"
https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"
var forPDF = document.querySelectorAll(".js-panel-pdf");
var len = forPDF.length;
var thisPDF = new jsPDF('p', 'mm', [240, 210]); //210mm wide and 297mm high
for (var i = 0; i < forPDF.length; i++) {
html2canvas(forPDF[i], {
onrendered: function(canvas) {
thisPDF.addImage(canvas.toDataURL("images/png", 1), 'PNG', 0, 0, 210, 295);
if (parseInt(i + 1) === len) {
thisPDF.save('sample-file.pdf');
} else {
thisPDF.addPage();
}
}
});
}
Stuart Smith - This is not working it does not allow to download the pdf
here is java script code
function generatePDF(){
var imgData;
var forPDF = document.querySelectorAll(".summary");
var len `enter code here`= forPDF.length;
var doc =new jsPDF('p','pt','a4');
for (var i = 0; i < forPDF.length; i++){
html2canvas(forPDF[i],{
useCORS:true,
onrendered:function(canvas){
imgData = canvas.toDataURL('image/jpg',1.0);
var doc =new jsPDF('p','pt','a4');
doc.addImage(imgData,'jpg',10,10,500,480);
if (parseInt(i + 1) === len) {
doc.save('sample-file.pdf');
} else {
doc.addPage();
}
}
});
}
}

Anystock comparisonMode same value in tooltip

When using a stock chart, I am using the comparisonMode with a date. The value displayed by the crosshair is correct, but the value in the tooltip is the real value (not compared). How could I display the compared value instead?
As you can see on the picture, the compared value is 107.1 but the tooltip is displaying the actual value 893.5. I am using anychart 8.0.0
I'm glad to inform you that in the new version of AnyStock 8.1.0 the calculated change value is available right from the point information. It may be used in tooltips and legends. I guess this is exactly what you were looking for.
The example of using this feature you may find on this link.
Now the context of every point includes valueChange and valuePercentChange properties.
This feature requires a few additional lines of JS code, I prepared an example below to show how it works. Now compared value is shown in cross-hair label, in the tooltip, and in legend.
anychart.onDocumentReady(function() {
var dataTable = anychart.data.table();
dataTable.addData(get_dji_daily_short_data());
var firstMapping = dataTable.mapAs({'value': 1});
var secondMapping = dataTable.mapAs({'value': 3});
chart = anychart.stock();
var plot = chart.plot();
var series0 = plot.line(firstMapping);
var series1 = plot.line(secondMapping);
var yScale = plot.yScale();
// Set comparison mode.
yScale.comparisonMode("value");
var xScale = chart.xScale();
chart.container("container");
chart.draw();
//reference points of both series
var firstVisibleValue0 = null;
var firstVisibleValue1 = null;
//after chart rendering format tooltip and legend
getVisibleValues();
tooltipLegendFormat(firstVisibleValue0, firstVisibleValue1);
//after every scroll change recalculate reference points
//and reformat tooltip and legend
chart.scroller().listen('scrollerchange', function() {
getVisibleValues();
tooltipLegendFormat(firstVisibleValue0, firstVisibleValue1);
});
function getVisibleValues() {
// Gets scale minimum.
var minimum = xScale.getMinimum();
//select data from mappings
var selectable0 = firstMapping.createSelectable();
var selectable1 = secondMapping.createSelectable();
// Sets value for search.
var select0 = selectable0.search(minimum, "nearest");
var select1 = selectable1.search(minimum, "nearest");
// get values in first visible points
firstVisibleValue0 = select0.get('value');
firstVisibleValue1 = select1.get('value');
}
function tooltipLegendFormat(firstVisibleValue0, firstVisibleValue1) {
//format tooltips and legends of both series
series0.tooltip().format(function () {
return 'Series 0: ' + Math.round(this.value - firstVisibleValue0);
});
series0.legendItem().format(function(){
return 'Series 0: ' + Math.round(this.value - firstVisibleValue0);
});
series1.tooltip().format(function () {
return 'Series 1: ' + Math.round(this.value - firstVisibleValue1);
});
series1.legendItem().format(function(){
return 'Series 1: ' + Math.round(this.value - firstVisibleValue1);
});
}
});
html, body, #container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://cdn.anychart.com/releases/8.0.1/js/anychart-base.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.0.1/js/anychart-stock.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.0.1/js/anychart-exports.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.0.1/js/anychart-ui.min.js"></script>
<script src="https://cdn.anychart.com/csv-data/dji-daily-short.js"></script>
<link rel="stylesheet" href="https://cdn.anychart.com/releases/8.0.1/css/anychart-ui.min.css" />
<div id="container"></div>

Get Current rows cells values one by one on "BindingSelectionChanged" event from table in html form in Word using office.js

Hello I am creating a application using office.js which will be used in excel and word application addIn and I have written some code that actually gives the text of entire row cell by cell. but as my requirement was to maintain styles and of every cell and store them in database so that when again addin runs it should load the data in same format it was stored. Currently it is just text i am getting in response. I have asked a similar question like this which was to get the text with styles from current cell that really works great.
How do I get the formatting the Current cell of the table in Word using office.js
There is another thing if it is possible to get the cell html by row and column position that will also solve the problem.
Thank you!
Hi i found the solution of my problem but this is solution for word only this is not working in excel but this was working for me so i am writing here :-
function Addtable() {
var document = Office.context.document;
var headers = [["Cities"]];
var rows = [['<b>Hello there</b> <ul><li>One</li><li>Two</li></ul>'], ['Roma'], ['Tokyo'], ['Seattle']];
var html = '<table>';
html += '<thead>';
for (var i = 0; i < headers.length; i++) {
html += '<tr>';
var cells = headers[i];
for (var j = 0; j < cells.length; j++) {
html += '<th>' + cells[j] + '</th>';
}
html += '</tr>';
}
html += '</tr>';
html += '</thead>';
html += '<tbody>';
for (var i = 0; i < rows.length; i++) {
html += '<tr>';
var cells = rows[i];
for (var j = 0; j < cells.length; j++) {
html += '<td>' + cells[j] + '</td>';
}
html += '</tr>';
}
html += '</tbody>';
html += '</table>';
Office.context.document.setSelectedDataAsync(html, { coercionType: Office.CoercionType.Html }, function (asyncResult) {
document.bindings.addFromSelectionAsync(Office.BindingType.Table, function (result) {
console.log(result);
var binding = result.value;
binding.addHandlerAsync(Office.EventType.BindingSelectionChanged, onBindingSelectionChanged);
});
});
}
The above is the function that i call when i want to generate a table with html values in it.
and bellow is is code that i am using to get the value of the current cell and replacing with some dummy value.
var onBindingSelectionChanged = function (results) {
if (!isExecuted) {
Word.run(function (context) {
var tableCell = context.document.getSelection().parentTableCell;
context.load(tableCell);
return context.sync()
.then(function () {
if (tableCell.isNull == true) {
//selection is not within a cell.....
console.log("selection not in a header");
}
else {
// the selection is inside a cell! lets get the content....
var body = tableCell.body;
var html = tableCell.body.getHtml();
var tableHtml = tableCell.body.getHtml();
context.sync()
.then(function () {
var cellHtml = html.value;
var newHtml = "<table><tr><td><ul><li>yellow</li></ul></td></tr></table";
// Option 1
body.insertHtml(newHtml, Word.InsertLocation.replace);
// Option 2
//body.clear();
//body.insertHtml(newHtml, Word.InsertLocation.end);
return context.sync().then(function () {
console.log('HTML was successfully replaced.');
}).catch(function (e) {
console.log(e.message);
});
}).catch(function (e) {
console.log(e.message);
});
}
}).catch(function (e) {
console.log(e.message);
});
});
isExecuted = true;
}
else {
isExecuted=false;
}
};
Thank you!

Resources