Cannot Generate SVG using MathJax-node on sample - svg

MathJax and Node newbie is getting undefined output when trying to generate svg using the slightly modified sample from here https://github.com/mathjax/MathJax-node
// a simple TeX-input example
var mjAPI = require("mathjax-node");
mjAPI.config({
MathJax: {
// traditional MathJax configuration
}
});
mjAPI.start();
var yourMath = 'E = mc^2';
mjAPI.typeset({
math: yourMath,
format: "TeX", // or "inline-TeX", "MathML"
svg:true, // was mml:true
}, function (data) {
if (!data.errors) {console.log(data.mml)}
});
Sample run:-
C:\Users\user\Desktop\math-eqn>node math-eqn.js
undefined
The original sample works fine:-
C:\Users\user\Desktop\math-eqn>node math-eqn.js
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block" alttext="E = mc
^2">
<mi>E</mi>
<mo>=</mo>
<mi>m</mi>
<msup>
<mi>c</mi>
<mn>2</mn>
</msup>
</math>

You need to change data.mml to data.svg in the console.log() since you disabled MathML generation.

Related

Why is svg generated by MathJax.js different than the svg generated by MathJax-node

I am writing an web app that saves html to onenote. In order to save math formulas, I plan to convert math formulas to svg by MathJax.js and then convert svg to png, because the html/css supported in onenote api is limited.
But it seems the svg generated by MathJax.js in browser is not a valid svg. I tested it with a simple math formula: $$a^2 + b^2 = c^2$$ (demo code) and copy the svg to jsfiddle and it displays nothing.
Then I tried to write a MathJax-node demo and copy the svg to jsfiddle again, it looks good. Here is my demo code, it's almost the same as the GitHub repo demo:
// a simple TeX-input example
const fs = require('fs')
var mjAPI = require("mathjax-node");
mjAPI.config({
MathJax: {
// traditional MathJax configuration
}
});
mjAPI.start();
var yourMath = String.raw`a^2 + b^2 = c^2`
mjAPI.typeset({
math: yourMath,
format: "TeX", // or "inline-TeX", "MathML"
svg: true, // or svg:true, or html:true
}, function (data) {
if (!data.errors) {console.log(data.svg)}
// will produce:
// <math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
// <mi>E</mi>
// <mo>=</mo>
// <mi>m</mi>
// <msup>
// <mi>c</mi>
// <mn>2</mn>
// </msup>
// </math>
fs.writeFile('math.txt', data.svg, (error) => {
console.log(error)
})
});
I also tested two svg with cloudconvert, it's the same result. Why are the two svg different? Do I miss something?
The difference is due to a specific setting: useGlobalCache
By default, MathJax (docs) sets this to true while mathjax-node (docs) sets this to false.
On the server MathJax-node does not have any document context and produces self-contained SVGs. On the client, MathJax has a full document context and thus can re-use the SVG paths across equations.

svg convert to canvas - can't generate multi pages pdf

I have 12 graphs and I want to generate pdf with 2 pages each page has 6 graphs.
However, when I convert svg to canvas, then the jspdf can only see part of both sub-dives.
$('#downloadx2').click(function() {
var svgElements = $("#body_id").find('svg');
//replace all svgs with a temp canvas
svgElements.each(function() {
var canvas, xml;
// canvg doesn't cope very well with em font sizes so find the calculated size in pixels and replace it in the element.
$.each($(this).find('[style*=em]'), function(index, el) {
$(this).css('font-size', getStylex(el, 'font-size'));
});
canvas = document.createElement("canvas");
canvas.className = "screenShotTempCanvas";
//convert SVG into a XML string
xml = (new XMLSerializer()).serializeToString(this);
// Removing the name space as IE throws an error
xml = xml.replace(/xmlns=\"http:\/\/www\.w3\.org\/2000\/svg\"/, '');
//draw the SVG onto a canvas
canvg(canvas, xml);
$(canvas).insertAfter(this);
//hide the SVG element
////this.className = "tempHide";
$(this).attr('class', 'tempHide');
$(this).hide();
});
var doc = new jsPDF("p", "mm");
var width = doc.internal.pageSize.width;
var height = doc.internal.pageSize.height;
html2canvas($("#div_pdf1"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png', 0.1);
doc.addImage(imgData, 'PNG', 5, 0, width, height/2,'','FAST');
doc.addPage();
}
});
html2canvas($("#div_pdf2"), {
onrendered: function(canvas2) {
var imgData2 = canvas2.toDataURL(
'image/png', 0.1);
doc.addImage(imgData2, 'PNG', 5, 0, width, height/2,'','FAST');
doc.save('.pdf');
}
});
});
<body id="body_id">
<div id="div_pdf1" >
<svg></svg>
<svg></svg>
<svg></svg>
</div>
<div id="div_pdf1" >
<svg></svg>
<svg></svg>
<svg></svg>
</div>
</body>
When I run this code, the generated pdf will view two pages with same canvas the first one (div_pdf1) div. So how to get both of them appearing in pdf as two pages.
You seem to be trying to run 2 parts in sequence but that's not how javascript works and actually runs your code.
No big deal, just a small misunderstanding between your mental model and the engine that executes the code.
A quick temporary debugging tool to see what's going on and verify that there is a discrepancy is to add console.log to key points and check the sequence of their printout once you run the code.
console.log('[1] just before: svgElements.each');
svgElements.each(function() {
console.log('[2] just after: svgElements.each');
And also around this part of the code:
console.log('[3] just before html2canvas-div_pdf1');
html2canvas($("#div_pdf1"), {
console.log('[4] just after html2canvas-div_pdf1');
Finally around this part of the code:
console.log('[5] just before html2canvas-div_pdf2');
html2canvas($("#div_pdf2"), {
console.log('[6] just after html2canvas-div_pdf2');
I suspect you'll see the code doesn't print the log lines in the order you think they will.
Next, you can try wrapping the 2 calls to html2canvas with one setTimeout function and force a delay in the execution of that code by an arbitrary amount of milliseconds.
Note that this is not the recommended final production quality solution but it will make the code output what you want.

How to get char code of fontawesome icon?

I'd like to use fontawesome icons in SVG scope. I cannot achieve it in common way, but I can add <text> element containing corresponding UTF-8 char and with font set to fontawesome, like that:
<text style="font-family: FontAwesome;">\uf0ac</text>
To make it clear I wrote a switch for getting useful icons:
getFontAwesomeIcon(name) {
switch (name) {
case 'fa-globe':
return '\uf0ac'
case 'fa-lock':
return '\uf023'
case 'fa-users':
return '\uf0c0'
case 'fa-ellipsis-h':
return '\uf141'
default:
throw '# Wrong fontawesome icon name.'
}
}
But of course that's ugly, because I must write it myself im my code. How can I get these values just from fontawesome library?
You can avoid producing such a list and extract the information from the font-awesome stylesheet on the fly. Include the stylesheet and set the classes like usual, i. e.
<tspan class="fa fa-globe"></tspan>
and you can do the following:
var icons = document.querySelectorAll(".fa");
var stylesheet = Array.from(document.styleSheets).find(function (s) {
return s.href.endsWith("font-awesome.css");
});
var rules = Array.from(stylesheet.cssRules);
icons.forEach(function (icon) {
// extract the class name for the icon
var name = Array.from(icon.classList).find(function (c) {
return c.startsWith('fa-');
});
// get the ::before styles for that class
var style = rules.find(function (r) {
return r.selectorText && r.selectorText.endsWith(name + "::before");
}).style;
// insert the content into the element
// style.content returns '"\uf0ac"'
icon.textContent = style.content.substr(1,1);
});
My two answers for two approaches to the problem (both developed thanks to ccprog):
1. Setting char by class definition:
In that approach we can define element that way:
<text class="fa fa-globe"></text>
And next run that code:
var icons = document.querySelectorAll("text.fa");
// I want to modify only icons in SVG text elements
var stylesheets = Array.from(document.styleSheets);
// In my project FontAwesome styles are compiled with other file,
// so I search for rules in all CSS files
// Getting rules from stylesheets is slightly more complicated:
var rules = stylesheets.map(function(ss) {
return ss && ss.cssRules ? Array.from(ss.cssRules) : [];
})
rules = [].concat.apply([], rules);
// Rest the same:
icons.forEach(function (icon) {
var name = Array.from(icon.classList).find(function (c) {
return c.startsWith('fa-');
});
var style = rules.find(function (r) {
return r.selectorText && r.selectorText.endsWith(name + "::before");
}).style;
icon.textContent = style.content.substr(1,1);
});
But I had some problems with that approach, so I developed the second one.
2. Getting char with function:
const getFontAwesomeIconChar = (name) => {
var stylesheets = Array.from(document.styleSheets);
var rules = stylesheets.map(function(ss) {
return ss && ss.cssRules ? Array.from(ss.cssRules) : [];
})
rules = [].concat.apply([], rules);
var style = rules.find(function (r) {
return r.selectorText && r.selectorText.endsWith(name + "::before");
}).style;
return style.content.substr(1,1);
}
Having that funcion defined we can do something like this (example with React syntax):
<text>{getFontAwesomeIconChar('fa-globe')}</text>

Handlebars.js misses JSON data

I've got template file loaded by Require.js via this:
main-app.js
define([
'backboneLoader',
'handlebars',
'text!templates/main.html',
'text!appdata.json'
],
function(
Backbone,
Handlebars,
MainTemplate,
AppData
) {
"use strict";
return Backbone.View.extend({
initialize : function() {
this.render();
},
render : function() {
var template = Handlebars.compile(MainTemplate);
var output = template(AppData);
this.$el.append(output);
console.log("appData:\n" + AppData);
console.log("MainTemplate:\n" + MainTemplate);
console.log("Output:\n" + output);
//smth extra
return this;
}
});
}
);
MainTemplate (main.html)
<ul>
<li><b>Version:</b> {{version}}</li>
<li><b>Author:</b> {{author}}</li>
</ul>
AppData (appdata.json)
{version: "0.0.1", author: "John Doe"}
And output:
<ul>
<li><b>Version:</b></li>
<li><b>Author:</b></li>
</ul>
While expected output:
<ul>
<li><b>Version:</b> 0.0.1</li>
<li><b>Author:</b> John Doe</li>
</ul>
Any ideas what am I doing wrong? Thank you!
UPD:
Problem solved. Here is updated main-app.js:
define([
'backboneLoader',
'handlebars',
'text!templates/main.html!strip',
'text!appdata.json'
],
function(
Backbone,
Handlebars,
mainTemplate,
appData
) {
"use strict";
return Backbone.View.extend({
initialize : function() {
this.render();
},
render : function() {
var template = Handlebars.compile(mainTemplate);
var output = template(eval("(" + appData + ")")); //Object is expected by template(), not JSON.
this.$el.append(output);
console.log("appData:\n" + appData);
console.log("template:\n" + mainTemplate);
console.log("Output:\n" + output);
//smth extra
return this;
}
});
}
);
The problem is AppData is a string of JSON, not an actual Object. Simply change from:
var output = template(AppData);
to
var output = template(JSON.parse(AppData));
You may need to include json2.js to add JSON support for older browsers (<=IE7).
Here is a jsFiddle repro of your template function, the template transformations seems working, the problem is probably located in the text! function in require.js code, try to debug the text! function.
Try also to add the !strip function when loading the template: 'text!templates/main.html!strip',
The documentation suggests it :For HTML/XML/SVG files, there is another option. You can pass !strip, which strips XML declarations so that external SVG and XML documents can be added to a document without worry.

plotting Graph with flot

I want to plot graph using flot and mysql but an exception occurs
getData.php
$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
echo "[";
while($result = mysql_fetch_array($sql))
{
//print_r($result);
echo "[".$result['msgCount'].",".$result['From_user']."]"."\n";
}
echo "]";
And for plotting
<div id="plotarea" style="width:600px;height:300px;">
<script type="text/javascript">
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
$.ajax({
url:"getData.php",
type:"post",
success:function(data)
{
alert(data);
$.plot($("#plotarea"),data,options);
//alert(data);
}
})
</script>
</div>
What is wrong with this code?
Next I want to plot graph with one of the axis is time.
$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
while($result = mysql_fetch_array($sql))
{
$user_data[] = array($result['msgCount'],$result['From_user']);
}
echo json_encode($user_data);
The above will eliminate issues with comma separation (which, from what I can tell, you never resolved).
Next, the javascript:
<script type="text/javascript">
$(function () {
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
$.get("getData.php", function(data){
$.plot($("#plotarea"),data,options);
},
json);
});
</script>
Notice that I changed $.ajax to $.get, since you weren't passing any data from the page to the script, a post is not necessary. And if you use $.get, all of the setting names are assumed.
Also notice that I pulled the script out of the html and put it within the jquery window.onload syntax : $(function () { . This would go in the head of your html.
From what I can tell, you aren't really in need of ajax, since you didn't define any sort of event that would trigger the $.ajax function. It looks like you are using ajax to call a script when you could just put the script into the same script that loads the page, like:
<?php
$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
while($result = mysql_fetch_array($sql))
{
$user_data[] = array($result['msgCount'],$result['From_user']);
}
?>
<script type="text/javascript">
$(function () {
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
var userposts = <?php echo json_encode($user_data); ?>;
$.plot($("#plotarea"),userposts,options);
</script>
<style type="text/css">
#plotarea {
width: 600px, height: 300px;
}
</style>
</head>
<body>
.....//Put whatever before the div
<div id="plotarea"></div>
.....//Finish up the page.
Firstly it looks like the JavaScript list you are creating with your PHP code isn't separating each data point list item with a comma separator.
According to the jQuery $.ajax documentation the first argument passed to the success function is the data returned from the server, formatted according to the 'dataType' parameter. You haven't provided a dataType parameter. The docs say it will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response if no dataType has been specified.
I'm guessing the data getting passed to the plot function is a plain old string instead of a JavaScript list object as expected by Flot. Adding a dataType: 'json' option to your $.ajax call should fix this up.
What you're trying to output is a json document in the php side, which will directly be parsed to a java script array (either manually or automatically by libraries like jquery)
So there is no need to print json in php instead you can easily feed data into a php array and use the json_encode function to easily convert it to a json string.
A small example could help
you were trying to output
echo "[".$result['msgCount'].",".$result['From_user']."]"."\n";
which in java script [] = array and you are creating [[]] = array inside array.
But when the array is big, it's cumbersome to echo in php.
What do we do.
An array structure is similar in php.
You will need to add data into php as an "array inside array"
eg: php array(array(1,2,3)) = [[1,2,3]].
How to map it to json?
easy==> echo json_encode(array(array(1,2,3));
Cheers

Resources