2
Imagine that I identify within a text a span element that starts and ends with the class "color-green":
<span data-id="1" class="cor-verde">O texto está assim <strong>parte em negrito</strong></span>
Using Javascript, you would have to turn this text into an output by dividing it through the spaces of words:
<span data-id="1"><span class="cor-verde">O</span> <span class="cor-verde">texto</span> <span class="cor-verde">está</span> <span class="cor-verde">assim</span> <span class="cor-verde"><strong>parte em negrito</strong></span></span>
The proposal is so that when exporting a PDF, this element is recognized in the layout, that today only in HTML this formatting works.
I tried something like this, but for some reason it’s breaking the text:
window.onload = function(){
var formatContentToPrint = function (content) {
var marks = content.querySelectorAll('span');
// var iel = document.getElementsByTagName("i");
if (marks.length) {
for(var i in marks) {
if(marks[i].childNodes.length) {
for(var n in marks[i].childNodes) {
var nodeRm = marks[i].childNodes[n];
if (nodeRm.nodeName == 'I') {
marks[i].removeChild(nodeRm);
break;
}
}
}
if (marks[i].attributes && marks[i].attributes.length) {
for(var j in marks[i].attributes) {
if(marks[i].attributes[j].name == 'data-id') {
var mark = document.querySelector('[data-id="'+marks[i].attributes[j].value+'"]');
var listAttributes = [];
for (var m in mark.attributes) {
if(typeof mark.attributes[m] == "object") {
listAttributes.push(mark.attributes[m].name+'="'+mark.attributes[m].value+'"');
}
}
mark.removeAttribute('class');
var words = mark.innerHTML.split(' ');
var spans = [];
if (words.length) {
for (var k in words) {
spans[k] = '<span '+listAttributes.join(' ')+'>'+words[k]+'</span>';
}
}
mark.innerHTML = spans.join(' ');
}
}
}
}
}
return content;
}
var content = document.getElementById('content');
content = formatContentToPrint(content);
doc.innerHTML = content.innerHTML;
}
In the example of Fiddle works normal, i simulated a situation that he breaks the code - click here
When I use this method in a text of my system, it is breaking, see in the images:
Cool, it looks like it worked: https://jsfiddle.net/ivanferrer/j3km5yd4/6/
– Ivan Ferrer
Error now using real case: https://jsfiddle.net/ivanferrer/c7jpd052/
– Ivan Ferrer
I’m out now but then I’ll look
– Sam
Thanks, quiet...
– Ivan Ferrer
Show me the full text that is giving error.
– Sam
The link is complete: https://jsfiddle.net/ivanferrer/takvxsen/
– Ivan Ferrer
The link I posted from the actual case above is also a full text...
– Ivan Ferrer
Here is the same example, but using the old method, you still have a problem: https://jsfiddle.net/ivanferrer/takvxsen/3/
– Ivan Ferrer
Take a look now.
– Sam
Thanks @Sam, I think now it’s gone for good... without breaking anything.
– Ivan Ferrer