pdfjs: Fill out a form and get the fieldValues - javascript

I'm using pdfjs to display a PDF form (acroforms example). If I fill in some fields, how do I get those annotations.
I've tried:
pdfPage.getAnnotations().then(function(a) {
for(var i = 0;i < a.length; i++) {
console.log(a[i].id + ' - ' + a[i].fieldValue);
}
});
But all I get are empty fieldValues. I guess I'm getting them from the original PDF. How do I access the live document which includes the new annotations?

async getAnnotations() {
var result = {};
var pages = PDFViewerApplication.pdfDocument.numPages;
for (var i = 1; i <= pages; i++) {
var page = await PDFViewerApplication.pdfDocument.getPage(i);
var annotations = await page.getAnnotations();
for (var j = 0; j < annotations.length; j++) {
var element = annotations[j];
// Field Name
if (result[element.fieldName] == null) {
result[element.fieldName] = null;
}
var val = PDFViewerApplication.pdfDocument.annotationStorage.getOrCreateValue(element.id);
if (element.radioButton) {
if (val.value) {
result[element.fieldName] = element.buttonValue;
}
} else if (element.checkBox) {
result[element.fieldName] = val.value ? "On" : "Off";
} else {
result[element.fieldName] = val.value;
}
}
};
return result;
}

You should save values written by user in a local variable
Then you should create a xfdf file ( xml file by Adobe ) , look for Example nere : https://developer.salesforce.com/page/Adobe_XFDF . The xfdf should then be merged with original pdf to produce a new compiled pdf

Related

Save change in custom list display using local storage

I am trying to create a customizable list with links that can be hidden using a class if you click in a button. Also the list have a sortable option that you can move the links on the list, which saves to localstorage.
The problem is that I don't know how to save the class change with the list order in the localstorage if you click the "add/remove" button on each li.
Also, if anyone can help me improve the code I will be grateful, I am a newbie with localstorage and only managed this with a lot of reading in tutorials and documentation.
Here's a working example:
http://codepen.io/RogerHN/pen/EgbOzB
var list = document.getElementById('linklist');
var items = list.children;
var itemsArr = [];
for (var i in items) {
itemsArr.push(items[i]);
}
// localStorage
var ls = JSON.parse(localStorage.getItem('userlist') || '[]');
for (var j = 0; j < ls.length; j++) {
for (i = 0; i < itemsArr.length; ++i) {
if(itemsArr[i].dataset !== undefined){
if (ls[j] === itemsArr[i].dataset.id) {
list.appendChild(itemsArr[i]);
}
}
}
}
$('.list-block.sortable').on('sort', function () {
var newIdsOrder = [];
$(this).find('li').each(function(){
newIdsOrder.push($(this).attr('data-id'));
});
// store in localStorage
localStorage.setItem('userlist', JSON.stringify(newIdsOrder));
});
You want something like this:
var myApp = new Framework7({
swipePanel: 'left'
});
// Export selectors engine
var $$ = Dom7;
var mainView = myApp.addView('.view-main');
var list = document.getElementById('linklist');
var items = list.children;
var itemsArr = [];
for (var i in items) {
itemsArr.push(items[i]);
}
// localStorage
var ls = JSON.parse(localStorage.getItem('userlist') || '[]');
var classes = JSON.parse(localStorage.getItem('classes') || '["","","","","","","","","",""]');
for (var j = 0; j < ls.length; j++) {
for (i = 0; i < itemsArr.length; ++i) {
if(itemsArr[i].dataset !== undefined){
if (ls[j] === itemsArr[i].dataset.id) {
itemsArr[i].className = classes[i];
list.appendChild(itemsArr[i]);
// handle [add/remove] thing
if (classes[i] != "") {
$(itemsArr[i]).find(".checky").removeClass("selected");
}
}
}
}
}
$('.list-block.sortable').on('sort', saveInfo);
$(".restore").click(function(e) {
$(".confirm").show();
$(".shadow").show();
});
$(".no,.shadow").click(function(e) {
$(".confirm").hide();
$(".shadow").hide();
});
$(".yes").click(function(e) {
$(".confirm").hide();
});
$(".lbl").click(function(e) {
$(".toggle-text").toggleClass("blue");
$(".restore").toggle();
$(".checky").toggle();
$("li.hidden").toggleClass("visible");
});
$('.checky').click(function() {
if (!$(this).hasClass("selected")) {
$(this).parent().removeClass("hidden").addClass("visible");
}
else {
$(this).parent().addClass("hidden visible");
}
$(this).toggleClass("selected");
saveInfo();
});
function saveInfo() {
var newUserList = [];
var newClassList = [];
$("#linklist").find('li').each(
function() {
newUserList.push($(this).attr('data-id'));
if ($(this).hasClass("hidden")) {
newClassList.push("hidden");
}
else {
newClassList.push("");
}
});
// store in localStorage
localStorage.setItem('userlist', JSON.stringify(newUserList));
localStorage.setItem('classes', JSON.stringify(newClassList));
console.log("saved.");
}
function reset() {
console.log("Removing data from local storage.");
localStorage.setItem('userlist', '["1","2","3","4","5","6","7","8","9","10"]');
localStorage.setItem('classes', '["","","","","","","","","",""]');
window.location.reload(true);
};
Codepen
Technically, I should've added explanation...

Populate form from JSON.parse

I am trying to re-populate a form from some values in localStorage. I can't quite manage the last part to get the loop to populate my name and values.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
var formInput = s[i];
console.log(s[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}
Could I get some pointers please.
Your issue is in this section of code.
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
You are setting s to the length of the jsn array minus 1, then using it as if it were jsn. I think you intended something like this.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
for (var i = 0; i < jsn.length; i++) {
var formInput = jsn[i];
console.log(jsn[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}

How to fill divs with imgs dynamically?

http://jsfiddle.net/84nv2dmL/
I'm trying to get these images of letters to display in order. I tried creating divs dynamically and filling them with the img, but that didn't work. How can I get these letters to display in order?
jsfiddle code:
function getQueryStringVar(name){
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i=0 ; i < props.length;i++){
var pair = props[i].split("=");
if(pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag){
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
return $.getJSON( flickerAPI, {
tags: tag,
tagmode: "all",
format: "json"
})
.then(function (flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
return url;
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek";
var str = "letter,";
var searchtags = new Array()
for (var i = 0; i < name.length; i++) {
//console.log(str.concat(searchtags.charAt(i)));
searchtags[i] = str.concat(name.charAt(i));
}
for (var j = 0; j < name.length; j++){
var request = getLetterImage(searchtags[j]);
request.done(function(url) {
$("body").append("<img src="+ url + "></img>");
//var ele = document.createElement("div");
//ele.setAttribute("class", "img" + j--);
//document.body.appendChild(ele);
//$("<img src="+ url +"></img>").appendTo("img"+j);
});
}
//$("#img"+i).html("<img src="+ url + "></img>");
});
You basically need to keep track of the order that you are appending your images to the DOM, and make sure that they are in sync with the letters in the name. Created a fiddle with a fix. Comments are in line:
http://jsfiddle.net/84nv2dmL/2/
function getQueryStringVar(name) {
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i = 0; i < props.length; i++) {
var pair = props[i].split("=");
if (pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag) {
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
return $.getJSON(flickerAPI, {
tags: tag.char,
tagmode: "all",
format: "json"
})
.then(function(flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
// return an object with url AND index
return {
ind: tag.ind,
img: url
};
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek";
var urls = new Array(name.length); // array or URLs, in correct order
var urlCounter = []; // keeps count or URLs received
var str = "letter,";
var searchtags = new Array();
for (var i = 0; i < name.length; i++) {
searchtags[i] = {
char: str.concat(name.charAt(i)),
ind: i
};
}
for (var j = 0; j < name.length; j++) {
var request = getLetterImage(searchtags[j]);
request.done(function(url) {
// when request is done, place image url in 'urls' array, in the correct order
urls[url.ind] = url.img;
// push object to the counter array, just to keep count
urlCounter.push(url);
// check if all image urls have been collected
checkComplete();
});
}
function checkComplete() {
// if the number of URLs received is equal
// to the number of characters in the name
// append the images from the ordered array
if (urlCounter.length == name.length) {
for (var k = 0; k < urls.length; k++) {
$("body").append("<img src=" + urls[k] + "></img>");
}
}
}
});
$("#div_id").append("<img src="+ url + "></img>");
Here div_id is the id you gave to the div.
Append adds img tag with source src to it.
Please give the html code too along with the script to help understand the problem better

Save values into an array from a function which is called consecutively

I have a function which is called when a file is needed to be read in a folder. In this case since i have 3 files in that folder, it is called 3 times consecutively. I need to save all files info into array mapped_data2 like that:
mapped_data2[0] = inner_data1 //first file info,
mapped_data2[1] = inner_data2 //second file info etc.
However using my code i am having just the first files information 3 times. I am a bit confused with global variables, if you can point out the problem, i would appreciate it.
here is the code:
var mapped_data = [];
var mapped_data2 = [];
function o(msg) {
if (msg.data) {
var inner_data = [];
var lines = msg.data.split('\n'); //read lines of a file
for (var i = 2; i < lines.length; i++) {
if (lines[i].length > 0) {
.. //do same data format here
inner_data.push([son, vactual, voutput]);
}
}
mapped_data = inner_data;
}
else {
if (msg.topic == "/somefolder/somefolder") {
for (var i = 0; i < msg.args.length; i++) {
var filename = msg.args[i];
aw.get(filename);
}
}
}
}
function de() { //where i wanted to use these files info
for (var i = 0; i < 3; i++) {
mapped_data2[i] = { key: "Group" + (i + 1), values: mapped_data };
}
var datam = mapped_data2;
var den = JSON.stringify(datam);
document.write(den);
};
function init() {
..//create new client called aw for the server application and start it;
..//if the connection is established:
aw.onmessage = o;
aw.get("/somefolder/somefolder"); // request list of files in a folder
};
//when html page is being onload, call the functions init() and de()
var mapped_data2 = [];
function o(msg) {
var mapped_data = []; // this doesn't need to be global
if (msg.data) {
var inner_data = [];
...
mapped_data = inner_data;
} else {
...
}
mapped_data2.push({ key: "Group" + mapped_data2.length + 1, values: mapped_data };)
// do more stuff as in den()
}

Retrieving rich text box sharepoint in javascript

I have CustomNewForm for inserting items in the sharepoint list.
The fields are "Reason" and "Reason OverView"; both Multiple Line Rich Text fields. I need to copy some text from "Reason" to "Reason Overview".(A substring)
I tried to get this done with workflow but couldn't find a solution to get a substring of a form field.
I am trying to get the value from "Reason" field in javascript; but unable to do so.
MY CODE :: (not working)
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
alert('Hi');
Original.innerHTML=Reason.innerHTML;
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>
Any way to get this done??
I solved it using this
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
var reasonText = RTE_GetEditorDocument(Reason.id);
var reasonOverviewText = reasonText.body.innerText;
if(reasonOverviewText.length>=20)
{
reasonOverviewText = reasonOverviewText.substring(0,20)+'......';
Original.innerText = reasonOverviewText;
}
else
{
Original.innerText = reasonOverviewText;
}
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>

Categories

Resources