Mathquill how to write formula into pdf file - javascript

I'm trying to create a webpage where users are able to write formulas (rendered by mathquill).
This is the code:
createButton(document.body,
function()
{
var para1 = parent.frame1.document.createElement("p");
para1.setAttribute("id","Line"+i.toString());
var t1 = parent.frame1.document.createTextNode("Line "+i.toString()+":");
para1.appendChild(t1);
parent.frame1.document.body.appendChild(para1);
var para = parent.frame1.document.createElement("p");
para.setAttribute("id","math"+i.toString());
para.setAttribute("class", "mq-math-mode");
var t = parent.frame1.document.createTextNode("");
para.appendChild(t);
parent.frame1.document.body.appendChild(para);
latex = $('#basic-latex').on('keydown keypress', function() {
var prev = latex.val();
setTimeout(function() {
var now = latex.val();
if (now !== prev) mq.latex(now);
});
});
mq = MQ.MathField(para, {
autoSubscriptNumerals: true,
handlers: { edit: function() {
if (!latex.is(':focus')) latex.val(mq.latex());
} }
});
//latex.val(mq.latex());
//mathField = MQ.MathField(para, {spaceBehavesLikeTab: true});
i = i+1;
}
, "Create new line");
Then, I would like to save formulas in a pdf file.
I'm using the package jsPDF, but I'm not able to write the rendered formulas in the pdf. Is anybody able to help me?
Thanks a lot in advance
I add the code to create the PDF.
var doc = new jsPDF();
var str = mq.latex();
var src = 'http://latex.codecogs.com/png.latex?'+str
var som = new Image();
som.src = src;
var imgData = 'data:image/png;base64,'+ Base64.encode(som);
doc.addImage(imgData, 'png', 10, 50);
doc.save('Test.pdf');

Related

How I can save file with script Photoshop?

I want to write a script that would substitute different text from a text file into my shalon and save the image in jpeg format.
An error occurs: "This function may not be available in this version of Photoshop" on this line:
activeDocument.saveAs(saveFile, jpgSaveOptions, true,Extension.LOWERCASE);
My code:
while(!myFile.eof)
{
line = myFile.readln();
createText(line);
var thistimestamp = Math.round(new Date().getTime() / 1000);
saveFile = new File( "/c/Users/marki/Desktop/Temp001/" +thistimestamp)
saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.matte = MatteType.NONE;
saveOptions.quality = 9;
app.activeDocument.saveAs(saveFile, saveOptions, true,Extension.LOWERCASE);
}
I use Adobe Photoshop: 2017.0.0 20161012.r.53 2016/10/12:23:00:00 CL 1094006 ( x64)
You missed off the extension :D
saveFile = new File( "c:\\temp\\" + thistimestamp) + ".jpg");
Taking that your script createFile() is well defined and working, you are missing document creation command app.documents.add() before you start issuing commands. You are also missing file open procedures. When added, the code works fine:
function createText(fface, size, colR, colG, colB, content, tX, tY) {
var artLayerRef = app.activeDocument.artLayers.add()
artLayerRef.kind = LayerKind.TEXT
textColor = new SolidColor();
textColor.rgb.red = colR;
textColor.rgb.green = colG;
textColor.rgb.blue = colB;
textItemRef = artLayerRef.textItem
textItemRef.font = fface;
textItemRef.contents = content;
textItemRef.color = textColor;
textItemRef.size = size
textItemRef.position = new Array(tX, tY)
}
var myFile = new File("/c/temp/myfile.txt");
myFile.open('r');
while(!myFile.eof) {
app.documents.add();
line = myFile.readln();
createText(line,10,2,2,2,line,10,10);
var thistimestamp = Math.round(new Date().getTime() / 1000);
saveFile = new File( "/c/temp/" +thistimestamp)
saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.matte = MatteType.NONE;
saveOptions.quality = 9;
app.activeDocument.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);
}
This code is tested with version 20.0.2 20181219.r.30 2018/12/19: 1202136 x64
The text file content is:
And the result in Photoshop is:
Of course, all three documents are saved as jpegs in c:\temp.
In case you don't have a working createText function, you can find an example in this article. The function in this example is taken from that article.

Clarification and some assistace in my javascript code

I have a question and also in need for help with my code.
I'm trying to create a script that can update metadata on picture. user can upload multiple images and the script automatically update the metadata like latitude and longitude from a list.
As i am a newbie in java script i can not understand why when i pass all my coordinates inside reader.onload it only take the last one and assign it to all my pictures.
My idea is: I loop through the images and assign to each image one coordinate chronologically, then i convert the coordinate to exifByte. Till here is all working fine but when i try to attach the exifByte to each image inside reader.onload it takes the last coordinate and assign it to all my images.
I hope the code below is clear enough for you guys
Any explanation or help would be much appreciated
Thanks
<script>
function Initialize() {
var fileCatcher = document.getElementById('file-catcher');
var fileInput = document.getElementById('file-input');
var fileListDisplay = document.getElementById('file-list-display');
var fileList = [];
var renderFileList, dispimg;
var x = [];
var jpeg;
fileInput.addEventListener('change', function (evnt) {
var files = evnt.target.files;
fileList = [];
for (var i = 0; i < fileInput.files.length; i++) {
fileList.push(fileInput.files[i]);
var file = fileInput.files[i];
x = (i);
var gpsIfd = {};
var rutedata = '<?php echo "$str" ?>';
points = rutedata.split(";").reverse();
for (var j=0; j<(points.length-x); j++) {
var mData = points[j].split(',');}
console.log("current point:");
console.log(x)
var lat = (mData[0]);
var lng = (mData[1]);
gpsIfd[piexif.GPSIFD.GPSLatitudeRef] = lat < 0 ? 'S' : 'N';
gpsIfd[piexif.GPSIFD.GPSLatitude] = piexif.GPSHelper.degToDmsRational(lat);
gpsIfd[piexif.GPSIFD.GPSLongitudeRef] = lng < 0 ? 'W' : 'E';
gpsIfd[piexif.GPSIFD.GPSLongitude] = piexif.GPSHelper.degToDmsRational(lng);
var exifObj = { "GPS":gpsIfd};
var exifBytes = piexif.dump(exifObj);
var c = document.createDocumentFragment();
var reader = new FileReader();
reader.onload = (e) => { // this is the problem loop only the last point'
var jpeg = piexif.insert(exifBytes, e.target.result);
console.log(lat); // here is logging the last point only
var image = new Image();
image.src = jpeg;
image.width = 500;
var el = $("<div></div>").append(image);
$("#resized").prepend(el);
};
reader.readAsDataURL(fileInput.files[i]);
}
renderFileList();
});
}
</script>
Since reader is async in nature, you get the last lat-lang. You can use closure to keep data. Else create a function to pass data.
More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
(function (byte, lats) {
var reader = new FileReader();
reader.onload = (e) => {
var jpeg = piexif.insert(byte, e.target.result);
console.log(lats); // here is logging the last point only
var image = new Image();
image.src = jpeg;
image.width = 500;
var el = $("<div></div>").append(image);
$("#resized").prepend(el);
};
})(exifBytes, lat);

How to save mxworkflow editor as Xml using javascript

Iam using mxWorkflow -Editor to draw workflow process
then i tried to save the workflow as xml but it is not working
i tried this
function GetXML(container)
{
var graph = new mxGraph(container);
var enc = new mxCodec();
var node = enc.encode(graph.getModel());
var model = graph.getModel();
try
{
// var graph = new mxGraph(container);
graph.model.addListener(mxEvent.CHANGE, function (sender, evt) {
var changes = evt.getProperty('edit').changes;
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change instanceof mxChildChange &&
change.change.previous == null) {
graph.startEditingAtCell(change.child);
break;
}
}
});
}
finally
{
// Updates the display
model.endUpdate();
// graph.getModel().endUpdate();
}
// Adds an option to view the XML of the graph
document.body.appendChild(mxUtils.button('View XML', function()
{
var encoder = new mxCodec();
var node = encoder.encode(graph.getModel());
mxUtils.popup(mxUtils.getXml(node), true);
}));
I've looked at few posts & documentation , but didn't find anything
use function mxUtils.getPrettyXml
var button = mxUtils.button('View XML', function() {
var encoder = new mxCodec();
var node = encoder.encode(graph.getModel());
mxUtils.popup(mxUtils.getPrettyXml(node), true);
});
document.appendChild(button);

Select thumbnails with PDFjs

After upload a pdf i show with PDF.js a thumbnails and work it.
$(document).ready(function () {
if (!PDFJS.workerSrc && typeof document !== 'undefined') {
// workerSrc is not set -- using last script url to define default location
PDFJS.workerSrc = (function () {
'use strict';
var scriptTagContainer = document.body ||
document.getElementsByTagName('head')[0];
var pdfjsSrc = scriptTagContainer.lastChild.src;
return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
})();
PDFJS.workerSrc = 'pdfjs-dist-master/build/pdf.worker.js';
}
$("#pdfInp").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
showInCanvas(e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
function showInCanvas(url) {
// See README for overview
'use strict';
// Fetch the PDF document from the URL using promises
var pdfAsArray = convertDataURIToBinary(url);
PDFJS.getDocument(pdfAsArray).then(function (pdf) {
// Using promise to fetch the page
// Get div#container and cache it for later use
var container = document.getElementById("container");
// Loop from 1 to total_number_of_pages in PDF document
for (var i = 1; i <= pdf.numPages; i++) {
// Get desired page
pdf.getPage(i).then(function(page) {
var scale = .3;
var viewport = page.getViewport(scale);
var div = document.createElement("div");
// Set id attribute with page-#{pdf_page_number} format
div.setAttribute("id", "page-" + (page.pageIndex + 1));
// This will keep positions of child elements as per our needs
//div.setAttribute("style", "position: relative");
div.setAttribute("class", "page");
// Append div within div#container
container.appendChild(div);
// Create a new Canvas element
var canvas = document.createElement("canvas");
// Append Canvas within div#page-#{pdf_page_number}
div.appendChild(canvas);
var node = document.createElement("p");
var textnode = document.createTextNode("pagina " + (page.pageIndex + 1));
node.appendChild(textnode);
div.appendChild(node);
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
});
}//END LOOP
});
}
});
But i want select a multiple thumbnail show it. I think possible with the class css. This the code
$.fn.seleziona = function() {
var menuSel = $(this);
menuSel.find('.page').on('click', function() {
if ($(this).hasClass('open')) {
$(this).removeClass('open');
} else {
$(this).addClass('open');
}
});
};
$(document).ready(function(){
$("#container").seleziona();
});
end not work. That code worked only the DOM be present before the upload

Javascript DOM Mouse Event is not working for IE and Mozilla

Working on the Custom File upload application. I have 2 major issues:
The following given below code is not Opening the File Dialogue Box for Mozilla and IE.
In Chrome its working, but when I select File on First Click, it never adds file to the body. But in second click it adds the file which was Browse in First Click to the body.
Any help for the above issues will be appreciated.
function perform1Click(node) {
alert("INIT");
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
node.dispatchEvent(evt);
alert(3)
getFile(evt);
}
function getFile(event) {
var files = event.target.files;
var totalSize = 0;
if (totalSize > 1024*10) {
alert('Total size exceed 1 Mb.');
return;
}
//alert(files)
//alert(files.length);
for (var i = 0, f; f = files[i]; i++) {
displayFileList(f.name, f.size);
totalSize = totalSize+f.size;
}
}
function displayFileList(name, size) {
if (name != '') {
var top_plugin = document.getElementById('top_plugin');
// create tag
var ptag = document.createElement("p");
// create div
var divBox = document.createElement("div");
divBox.setAttribute('class', 'divBox');
// create input[type='checkbox']
var inputCheckBox = document.createElement("input");
inputCheckBox.setAttribute('type', 'checkbox');
inputCheckBox.setAttribute('id', 'checkboxClass')
// add checkbox to div.
divBox.appendChild(inputCheckBox);
// create text node for divBox and add it to divBox.
var txtNode = document.createTextNode(name);
divBox.appendChild(txtNode)
var sizeDivBox = document.createElement("p");
sizeDivBox.setAttribute('style', 'clear:both; display: inline-block;');
var txtSizeNode = document.createTextNode(size);
sizeDivBox.appendChild(txtSizeNode);
divBox.appendChild(sizeDivBox);
// add divBox to ptag.
ptag.appendChild(divBox);
//ptag.appendChild(divTxt);
// add ptag to top_plugin div.
top_plugin.appendChild(ptag);
}
// if file value is not null, make it blank.
if (name != '')
{
name = '';
}
}
I got the solution for the same problems. Please find below the new code.
function uploadDFiles() {
var file = document.getElementById('_file');
file.click();
try {
file.addEventListener("change", getFileName);
}
catch (e) {
file.attachEvent("onclick", getFileNameOnIE);
alert("Error:: "+e.description);
}
}
function getFileName(event) {
var files = event.target.files;
for (var i = 0, f; f = files[i]; i++) {
var fileName = f.name;
var fileSize = f.size;
var fSize = bytesToSize(fileSize, 2);
displayFileList(fileName, fSize);
}
}
But now I have new problem. This code is not working in IE.For IE i am using attachEvent method and its not working. Please find below the code:
function getFileNameOnIE(event) {
alert(event.type);
var files = event.target;
alert(files.length);
for (var i = 0, f; f = files[i]; i++) {
displayFileList(f.name, f.size);
}
}
Can someone provide me the solution for the same now?
--
Tks
Bharat

Categories