Dynamically creating ODT using WebODF / Javascript - javascript

Using javascript, I need to create an .odt file and populate the contents with data in javascript variables. The only thing that I have found that might work is WebODF. An example that seems similar to it is here.
When I am trying to do something similar to PDF with pdfkit (using node) I can do something like this:
PDFDocument = require('pdfkit');
var doc = new PDFDocument();
doc.pipe(fs.createWriteStream(fileName));
doc.text("Fist line");
doc.text("Second line");
Is it possible to do something similar to it using WebODF? I've found ops.OpInsertText, but I'm not sure how I can use it to actually insert text.
Again, ideally the solution is only in javascript.

If I got your question right, you want to create a new file dynamically using data in JavaScript variable.
You ca refer this answer to load a file from javascript variable in form of byte Array.
And this will get you up and running with a odt file ,which you can save to desired location.
function saveByteArrayLocally(error, data) {
var mime = "application/vnd.oasis.opendocument.text";
var blob = new Blob([data.buffer], {type: mime});
var res = $http({
method: 'POST', url: myWebServiceUrl,
headers: {'Content-Type': undefined},
data: blob
});
res.success(function(data, status, headers, config) {
console.log(status);
});
}
NOTE: You can use multer,express.js framework to design services as backend to save files.

This may help you.In this example I am attaching the Value returned from promt to the cursor position inside the webodf. You can similarly insert data to any other elements offest().
pressing crtl+space will show a promt, and whatever we type there is inserted to odf.
function insertBreakAtPoint(e) {
var range;
var textNode;
var offset;
var key = prompt("Enter the JSON Key", "name");
{% raw %}
var key_final = '{{address.'+key+'}}';
{% endraw %}
var caretOverlay=$('.webodf-caretOverlay').offset();
if (document.caretPositionFromPoint) {
range = document.caretPositionFromPoint(
caretOverlay.left, caretOverlay.top
);
textNode = range.offsetNode;
offset = range.offset;
} else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(
caretOverlay.left, caretOverlay.top
);
textNode = range.startContainer;
offset = range.startOffset;
}
#only split TEXT_NODEs
if (textNode.nodeType == 3) {
var replacement = textNode.splitText(offset);
var keynode = document.createTextNode(key_final);
textNode.parentNode.insertBefore(keynode, replacement);
}
}
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 32 && evtobj.ctrlKey)
insertBreakAtPoint();
}
document.onkeydown = KeyPress;

Related

Randomly pick a line and save each word on that line into each Javascript variable

pick a line depending on variable "number"
then save each of the words on that line into each javascript variable1 and javascript variable2.
if variable number equals 2, pick line 2, set Variables1 to potato ,and set Variables2 to tomato.
//Text file on server
Apple, Oranges
Potato, Tomato
Cake, Muffin
Cheese, Milk
//Java script code in browser.
var number = Math.floor((Math.random() * 4) + 1);
var xhr = new XMLHttpRequest();
xhr.open("GET","http://..........data.txt",false);
xhr.send(null);
What should I do next?
Any help is appreciated
Thanks in advance
You better off chosing random string via your backend server rather than js because servers meant to do that. You could create a page to which you will reffer to and pass path to your file as parameter and set it to return random line from that file. After you parsed that string you can use split() onto your parsed string to get an array of those words. Also you should consider using fetch 'cause it's a replacement for a XHR.
So my js code looks something like this:
function getTextFile(path){
var line = Math.floor(Math.random() * 4);
params = {
path: path,
line: line
}
var data = new FormData();
data.append("json", JSON.stringify(params));
var promise = fetch("http://mysite/myscript.php", {method: 'POST', body: data})
.then((response) => {
return response.text();
}).then((text) => {
if(text != 'error'){
text = text.replace(/(\r\n|\n|\r)/gm, "");
var result = text.split(" ");
//Result will be an array of those values and will look something like that:
//["Cheese", "Milk", "Yogurt"]
}
else{
alert('error');
}
});
}
And then on a backend it looks like that:
$json = (array) json_decode($_POST['json']);
if( validatePath($json['path']) ){
$file = file($json['path']);
$my_string = $file[$json['line']];
echo $my_string;
}
else{
echo 'error';
}
function validatePath($path){
//You should definitely use some other validations
$allowedExtensions = ['txt', 'json'];
$pathinfo = pathinfo($path);
//Right now it's only checking for right extension and
//that's this file ain't located in admin subdir
if(strstr($pathino['dirname'], '/admin') || !in_array($pathinfo['extension'], $allowedExtensions)){
return false;
}
else{
//Check if file exists
if( file_exists($path) ){
return true;
}
else{
return false;
}
}
}
Although not every browser supports fetch and if you want to support more browsers you'll need polyfill.

Vis.js network: how to get data and options back for saving?

My intention is to create simple graph editor using vis.js and the first feature I'm thinking about is to position nodes manually and save that. However, unlike setting options a straight-forward method to get all the options doesn't seem to exist. Is there any reasonable approach to get them (aside trying to track all the changes using events like dragEnd which sounds way too fragile)?
In fact, I'm looking for a way to extract both data (nodes/edges and their settings) and options so that once the network is rendered using those options, it looks the same (or at least similar) to what was saved.
Vis.js provides a simple example to export and import networks as JSON.
There is also an example with basic Editor-functionality like adding/removing nodes and edges
I've created my js functions to get all options.
For example if I would get the group of each node id:
function getGroup(network, id){
var group = network.body.data.nodes._data[id].group;
return group;
}
UPDATE: I don't have a single function to get all options, but for ex. you can get few options value with this function:
function getOptions(network){
var opt = network.options;
return opt;
}
function getLocale(network){
var locale = getOptions(network).locale;
}
function getClickToUse(network){
var clickToUse = getOptions(network).clickToUse;
}
In my case I don't need the global options, as for saving the data here is what I did:
async function saveJSON() {
// For all nodes:
var str = "{\"nodes\":[";
var ns = nodes._data;
ns.forEach(function(n) {
str += JSON.stringify(n);
str += ",";
});
str = str.slice(0,-1) + "],";
// For all edges:
str += "\"edges\":[";
var es = edges._data;
es.forEach(function(e) {
delete e['id'];
str += JSON.stringify(e);
str += ",";
});
str = str.slice(0,-1) + "]}";
console.log($.ajax({
method: "POST",
url: "network.json",
data: str,
success: function(resp) {}
}));
}
As for loading it's like this:
async function loadJSON() {
$.ajax({
method: "GET",
url: "network.json",
cache: false,
success: function(data0) {
network.destroy();
// data0 seems already parsed as JSON by the server
// No need to do: var data1 = JSON.parse(data0);
// console.log(data0);
nodes = new vis.DataSet(data0.nodes);
edges = new vis.DataSet(data0.edges);
data.nodes = nodes;
data.edges = edges;
network = new vis.Network(container, data, options);
} });
}

Save 1st page of a PDF file using JavaScript

I need to extract 1st page of an uploaded PDF file(in SharePoint Online) & save it as a separate PDF file using JavaScript.
After some searching I found this. But I'm not able to understand how it works.
Please help.
As requested in the comment in a previous answer I am posting sample code to just get the first page in its original format, so not as a bitmap.
This uses a third party REST service that can PDF Convert, Merge, Split, Watermark, Secure and OCR files. As it is REST based, it supports loads of languages, JavaScript being one of them.
What follows is a self-contained HTML page that does not require any additional server side logic on your part. It allows a PDF file to be uploaded, splits up the PDF into individual pages and discards them all except for the first one. There are other ways to achieve the same using this service, but this is the easiest one that came to mind.
You need to create an account to get the API key, which you then need to insert in the code.
Quite a bit of the code below deals with the UI and pushing the generated PDF to the browser. Naturally you can shorten it significantly by taking all that code out.
<!DOCTYPE html>
<html>
<head>
<title>Muhimbi API - Split action</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
// ** Specify the API key associated with your subscription.
var api_key = '';
// ** For IE compatibility*
// ** IE does not support 'readAsBinaryString' function for the FileReader object. Create a substitute function using 'readAsArrayBuffer' function.
if (FileReader.prototype.readAsBinaryString === undefined) {
FileReader.prototype.readAsBinaryString = function (file_content) {
var binary_string = "";
var thiswindow = this;
var reader = new FileReader();
reader.onload = function (e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary_string += String.fromCharCode(bytes[i]);
}
thiswindow.content = binary_string;
$(thiswindow).trigger('onload');
}
reader.readAsArrayBuffer(file_content);
}
}
// ** For IE compatibility*
// ** Create a Blob object from the base64 encoded string.
function CreateBlob(base64string)
{
var file_bytes = atob(base64string);
var byte_numbers = new Array(file_bytes.length);
for (var i = 0; i < file_bytes.length; i++) {
byte_numbers[i] = file_bytes.charCodeAt(i);
}
var byte_array = new Uint8Array(byte_numbers);
var file_blob = new Blob([byte_array], {type: "application/pdf"});
return file_blob;
}
// ** Execute code when DOM is loaded in the browser.
$(document).ready(function ()
{
//** Make sure an api key has been entered.
if(api_key=='')
{
alert('Please update the sample code and enter the API Key that came with your subscription.');
}
// ** Attach a click event to the Convert button.
$('#btnConvert').click(function ()
{
// ** Proceed only when API Key is provided.
if(api_key=='')
return;
try
{
// ** Get the file object from the File control.
var source_file = document.getElementById('file_to_split').files[0];
//** Was a file uploaded?
if (source_file)
{
// ** Get the file name from the uploaded file.
var source_file_name = source_file.name;
var reader = new FileReader();
//** Read the file into base64 encoded string using FileReader object.
reader.onload = function(reader_event)
{
var binary_string;
if (!reader_event) {
// ** For IE.
binary_string = reader.content;
}
else {
// ** For other browsers.
binary_string = reader_event.target.result;
}
// ** Convert binary to base64 encoded string.
var source_file_content = btoa(binary_string);
if(source_file_content)
{
// ** We need to fill out the data for the conversion operation
var input_data = "{";
input_data += '"use_async_pattern": false';
input_data += ', "fail_on_error": false';
input_data += ', "split_parameter": 1';
input_data += ', "file_split_type": "ByNumberOfPages"';
input_data += ', "source_file_name": "' + source_file_name + '"'; // ** Always pass the name of the input file with the correct file extension.
input_data += ', "source_file_content": "' + source_file_content + '"'; // ** Pass the content of the uploaded file, making sure it is base64 encoded.
input_data += '}',
// ** Allow cross domain request
jQuery.support.cors = true;
// ** Make API Call.
$.ajax(
{
type: 'POST',
// ** Set the request header with API key and content type
beforeSend: function(request)
{
request.setRequestHeader("Content-Type", 'application/json');
request.setRequestHeader("api_key", api_key);
},
url: 'https://api.muhimbi.com/api/v1/operations/split_pdf',
data: input_data,
dataType: 'json',
// ** Carry out the conversion
success: function (data)
{
var result_code = "";
var result_details = "";
var processed_file_contents = "";
var base_file_name = "";
// ** Read response values.
$.each(data, function (key, value)
{
if (key == 'result_code')
{
result_code = value;
}
else if (key == 'result_details')
{
result_details = value;
}
else if (key == 'processed_file_contents')
{
processed_file_contents = value;
}
else if (key == 'base_file_name')
{
base_file_name = value;
}
});
// ** Show result code and details.
$("#spnResultCode").text(result_code);
$("#spnResultDetails").text(result_details);
if(result_code=="Success")
{
// ** Get first item in the array. This is the first page in the PDF
var processed_file_content = processed_file_contents[0];
// ** Convert to Blob.
var file_blob = CreateBlob(processed_file_content)
// ** Prompt user to save or open the converted file
if (window.navigator.msSaveBlob) {
// ** For IE.
window.navigator.msSaveOrOpenBlob(file_blob, base_file_name + "." + output_format);
}
else {
// ** For other browsers.
// ** Create temporary hyperlink to download content.
var download_link = window.document.createElement("a");
download_link.href = window.URL.createObjectURL(file_blob, { type: "application/octet-stream" });
download_link.download = base_file_name + ".pdf";
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
}
}
},
error: function (msg, url, line)
{
console.log('error msg = ' + msg + ', url = ' + url + ', line = ' + line);
// ** Show the error
$("#spnResultCode").text("API call error.");
$("#spnResultDetails").text('error msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
}
else
{
// ** Show the error
$("#spnResultCode").text("File read error.");
$("#spnResultDetails").text('Could not read file.');
}
};
reader.readAsBinaryString(source_file);
}
else
{
alert('Select file to convert.');
}
}
catch(err)
{
console.log(err.message);
// ** Show exception
$("#spnResultCode").text("Exception occurred.");
$("#spnResultDetails").text(err.message);
}
});
});
</script>
</head>
<body>
<div>
<form id="convert_form">
Select file: <input type="file" id="file_to_split" />
<br /><br />
<button id="btnConvert" type="button">Split PDF</button>
<br /><br />
Result_Code: <span id="spnResultCode"></span>
<br />
Result_Details: <span id="spnResultDetails"></span>
</form>
</div>
</body>
</html>
Big fat disclaimer, I worked on this service, so consider me biased. Having said that, it works well and could potentially solve your problem.
Finally found a solution.
First converting the uploaded PDF to image using PDF.JS, done some customization in the sample code.
Then saved the 1st page image as PDF using jsPDF.
The customized download code,
$("#download-image").on('click', function() {
var imgData = __CANVAS.toDataURL();
var doc = new jsPDF();
doc.addImage(imgData, 0, 0, 210, 300);
doc.save('page1.pdf');
});

jquery to use .get and retrieve variables from text file

I have a list of names in a text file
example:
user1 = Edwin Test //first line of text file
user2 = Test Edwin //second line of text file
I would like each lines data to be set to a variable:
user1 and user2 //so that after jquery loads I can user $user1 and it will give Edwin Test
Text file will be in the same folder as jquery file.
My code:
$.get('users.txt', function(data) {
alert(data);
var lines = data.split("\n");
$.each(lines, function() {
var line=perLine[i].split(' ');
});
});
When i load the page using mamp locally, I am able to see the contents on the file using the alert but when i type for example (user1) in the console it says that the variable is not set.
Here's what I think you want:
$.get('users.txt', function(data) {
var lines = data.split("\n");
$.each(lines, function(i) {
var line = lines[i].split(' = ');
window[line[0]] = line[1];
});
});
later on...
console.log(user1); // "Edwin Test"
var users = {};
var lines = data.split("\n");
$.each(lines, function (key, value) {
var prep = value.split(" = ");
users[prep[0]] = prep[1];
});
To output user1 You would call users.user1
JSFiddle
The code adds lots of variables to the global namespace. Also, it invites bugs because $.get is asynchronous and so code that depends on the variables existing needs to be called where shown in the comment to be guaranteed to work. This would be considered bad style by many, but here's how to do it:
$.get('users.txt', function(data) {
alert(data);
var lines = data.split("\n");
var i,l=lines.length,parts;
for(i=0;i<l;++i){
parts = lines[i].split('=');
if (parts.length == 2){
try {
// window is the global object. window['x']=y sets x as a global
window['$'+parts[0]] = parts[1]; // call the var $something
} catch(e) {}; // fail silently when parts are malformed
}
// put any code that relies on the variables existing HERE
}
});
Here's what you might do instead:
Put the data in an object. Pass the object to a function showVars(vars) that contains the next step.
$.get('users.txt', function(data) {
alert(data);
var lines = data.split("\n");
var i,l=lines.length,parts, vars = {};
for(i=0;i<l;++i){
parts = lines[i].split('=');
if (parts.length == 2){
try {
vars[parts[0]] = parts[1];
} catch(e) {}; // fail silently when parts are malformed
}
showVars(vars); // put any code that relies on the variables existing HERE
}
});
function showVars(vars){
// put whatever uses/displays the vars here
}
Yet another way to make this easier to change the data format. If you can store the data in this format, called JSON:
['Edwin Test','Test Edwin','Someone Else','Bug Tester']
Then the parser is either a one liner array = JSON.parse(jsonString) or sometimes is done for you by jQuery and put in data. JSON can store all kinds of data, and there is support for it in other languages libraries besides Javascript, such as PHP, python, perl, java, etc.
$.get('users.txt', function(data) {
alert(data);
var lines = data.split("\n");
for(var i = 0 ; i < lines.length; i++){
var line=lines[i].split(' ');
});
});
I think you are missing the i in the loop.
I guess you could also do
$.each(lines, function(i) {
var line=lines[i].split(' ');
});
In any event, I would probably recommend that you do this string splitting on the server instead and deliver it to the client in the correct/ready form.

Get JSON data from another page via JavaScript

I have a page where I want to add couple of controls
when I click on 1st control, I want my javascript to open particular JSONpage, gram the content and then output the content in specific <DIV id="one">. Then, when I select some of the elements in div id="one", I want The JavaScript to connect to another JSON page and get another array of data from there.
My question - how do I do the JSON part?
In other words, how do I get JavaScript version of:
$dataSet = json_decode(file_get_contents($url), true);
I am new to JavaScript and this thing takes so much time!!
Got this working
function getDates() {
jQuery(function($) {
$.ajax( {
url : "jsonPage.php",
type : "GET",
success : function(data) {
// get the data string and convert it to a JSON object.
var jsonData = JSON.parse(data);
var date = new Array();
var i = -1;
$.each(jsonData, function(Idx, Value) {
$.each(Value, function(x, y) {
if(x == 'date')
{
i = i + 1;
date[i] = y;
}
});
});
//output my dates; [0] in this case
$("#testArea").html(date[0]);
}
});
});
}

Categories