Can't get child field font in pdf-lib.js - javascript

I am trying to get a list of fields and which fonts are assigned to them. I can use form.getFields() to get a list of fields in the form. I can then run through the "dict" to find the font name - Easy!
Ex1
However, when I am working with a field that has "Child Fields", for example, a pdf with text fields of the same name, it does not have this font parameter.
It only has "/Kids" which contains some sort of reference I haven't been able to understand
Ex2
I have also tried this:
createPDFAcroFields(fields\[1\].acroField.Kids())
However, it returns a blank array. Any help would be greatly appreciated.
Here's a jsFidle that grabs the fields and can show you the objects that are missing the font in the console!
https://jsfiddle.net/xek1stmz/13/
<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>
</head>
<script>
const { PDFDocument } = PDFLib
async function getFieldFonts() {
// Fetch the PDF with form fields
const formUrl = 'https://partners.metas.global/Code39.pdf'
const formPdfBytes = await fetch(formUrl).then(res => res.arrayBuffer())
// Load a PDF with form fields
const pdfDoc = await PDFDocument.load(formPdfBytes)
// Get the form containing all the fields
form = pdfDoc.getForm();
fields = form.getFields();
console.log(fields);
}
getFieldFonts();
</script>
</html>

Related

How can I use a parameter to change HTML text?

I'm using an API, and am trying to access the value of product.shoeName to change text on my HTML page. This is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="shoepoo.js">
</script>
</head>
<body>
<div>
<p id="text" style="color:purple;
font-weight:bold;font-size:20px;">
</p>
<script type="text/javascript"> shoeName(); </script>
</div>
</body>
</html>
const SneaksAPI = require('sneaks-api');
const sneaks = new SneaksAPI();
//getProducts(keyword, limit, callback) takes in a keyword and limit and returns a product array
function shoeName(){
sneaks.getProducts("Jumbo Blazer", 1, function(err, products){
products.forEach(
function names (product) {
document.getElementById("text").innerHTML = product.shoeName;
})
});
};
Basically, I want product.shoeName to be shown as text, but nothing is showing up. How can I fix this? I understand it's a local function which is probably stopping the data from being shown (or something like that), but how can I work around this?
Made below changes in shoepoo.js
products.forEach((product)=> {
document.getElementById("text").innerHTML = product.shoeName;
});
But you need to create dynamic HTML components if there is multiple data in products. Otherwise, it set the last shoeName in the paragraph component.

HTML encoding/decoding issue, when using JS to get from JSON data sample

I have a website and want to display text. The text is in German and comes from a JSON data set I have. This is retrieved from a localhost API URL for now. The German words have the special characters replaced with HTML encoded ones. For example, erzählt is saved in the JSON data as erz&#228hlt. When I make the textContent of my paragraph tag to the JSON German text, the HTML encoding does not work. It does work however if I just copy and paste it manually in. How can I trigger the encoding to work and have it show correctly?
Code:
Gets random German word from JSON API, puts text into paragraph. Encoding issue.
erz&#228hlt is shown instead of erzählt .
JSON example:
{ "id": "32", "ename": "Smile.", "gname": "L&#228cheln!" }
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
</head>
<h4>German:</h4>
<div>
<p id="gname">
</div>
<script>
const api_url = 'http://localhost:3000/fyp/api/grandom.php';
async function getData() {
const repsonse = await fetch(api_url);
const data = await repsonse.json();
var i = Math.floor((Math.random() * 16534) + 0);
const { gname, ename } = data[i];
document.getElementById('gname').textContent = gname;
document.getElementById('ename').textContent = ename;
}
getData();
</script>
Any help or advice appreciated. If anything needs explaining please let me know.
If your string contains HTML entities like &#228 then it isn’t text, it is HTML.
textContent expects you to pass plain text to it, not HTML source code.
Use innerHTML instead.
const value = "erz&#228hlt";
text.textContent = value;
html.innerHTML = value;
<div id=text></div>
<div id=html></div>
use innerHTML instead of innetText to solve your problem
function getData() {
const data = { "id": "32", "ename": "Smile.", "gname": "L&#228cheln!" };
document.getElementById('gname').innerHTML = data.gname;
document.getElementById('ename').innerHTML = data.ename;
}
getData();
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
</head>
<body>
<h4>German:</h4>
<div>
<p id="gname"></p>
<p id="ename"></p>
</div>
<body>

Issue with API url: cannot seem to pass parameters correctly

I'm new at APIs and am trying for the first time to create a gallery using Flickr API, but I'm really struggling getting it to work properly.
I have created the url correctly, and if I insert the search parameters directly in the url, when I console log I can see the correct list of images. The issue occurs when I'm trying to pass parameters from variables into the url. And the error manifests in two different ways, depending whether I put the url variable before or after the parameters variables.
Case 1:
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=${searchWord}&per_page=${perPage}&page=${page}&format=json&nojsoncallback=1`;
var searchWord = document.getElementById('input').value;
var perPage = 50;
var page = 1;
In this case it will console log data, but using parameters of its choice.
Case 2:
var searchWord = document.getElementById('input').value;
var perPage = 50;
var page = 1;
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=${searchWord}&per_page=${perPage}&page=${page}&format=json&nojsoncallback=1`;
In this case it will return the following error message: {stat: "fail", code: 3, message: "Parameterless searches have been disabled. Please use flickr.photos.getRecent instead."}
I seem to not be passing parameters to the url correctly, cause I'm also having an issue when trying to create the gallery itself, where when I'm trying to pass the necessary ids from the images in the API array to the image url I'm creating, these parameters end up being undefined.
This is the code I've written:
function createGallery(photos) {
for (let photo of Object.keys(photos)) {
const imgElem = document.createElement('li');
imgElem.innerHTML = `<img src='https://farm{${photo.farm}}.staticflickr.com/{${photo.server}}/{${photo.id}}_{${photo.secret}}_[mstzb].jpg'></img>`;
imgElem.setAttribute('img-id', photo.id);
gallery.append(imgElem);
}
}
Just for an overview, here is the last bit of my JS:
//Fetch API
async function start() {
const response = await fetch (url)
const data = await response.json()
console.log(data)
createGallery(data)
}
//Call functions
search()
And here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<input type="text" id="input">
<button id="search">Go</button>
<ul id="gallery"></ul>
</main>
<script src="script.js"></script>
</body>
</html>
Anyone can explain what I'm doing wrong?? Thanks so much in advance :)
EDIT: I tried appending the variables using pluses instead of using template literals, like so:
var url = 'https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text='+searchWord+'&per_page='+perPage+'&page='+page+'&format=json&nojsoncallback=1';
But both ways give exactly the same result.
You are basically appending the parameters incorrectly.
You have the following:
var perPage = 50;
var page = 1;
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=${searchWord}&per_page=${perPage}&page=${page}&format=json&nojsoncallback=1`;
When you define that url it should be similar to this ..
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=' + searchWord + '&per_page=' + perPage + '&page=' + page + '&format=json&nojsoncallback=1'
Please note the difference there, we are actually just building up the url var by appending the JS variables to the String. There is no ${} access to the declared page and perPage JS vars...

Can you match words in a url using a RegEx array?

I'm trying to grab specific words from a URL using RegEx. I've included the words as an Array but I can't seem to match or filter any of the words in the array. I always get an error that 'filter' is not a function although i appear to be using it much the same as others have before.
function replaceInput() {
var leadUrl = document.URL;
var utm_sources = [/linkedin/, /smartbrief/, /email_paid/, /paid_social/];
var get_source = leadUrl.filter(value => utm_sources.test(value));
var setUtm = get_source;
document.getElementById("LeadSourceTitle").placeholder = setUtm;
}
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src="utm-url-test.js"></script>
</head>
<body>
<h1>Form test</h1>
<p>Populate the webform input with the utm of the url.</p>
<form>
<input id="LeadSourceTitle" placeholder="This should be replaced with UTM" onfocus="replaceInput()"></input>
</form>
</body>
</html>
Ideally what I want to do is check to see whether these words exist, then add a value to a form input with the corresponding value.
Thanks
If I read your code correct, you are looking for the path of an url, not the url itself. The path can be found in location.pathname. Using RegExp.match delivers null if nothing is matched, and an array (you filter if necessary) if a match is found.
So, do something along the lines of:
const re = /\/linkedin\/|\/smartbrief\/|\/email_paid\/|\/paid_social\//i;
const path = location.pathname.match(re);
const pathFaked1 = "/linkedin/?foo=bar&email_paid=1".match(re);
const pathFaked2 = "/email_paid/nope/shouldpaynow".match(re);
console.log(path);
console.log(pathFaked1.join(", "));
console.log(pathFaked2.join(", "));

Create a dynamic dropdown form that loads its data from a JSON file using JQuery

In a class, I was asked to make a dynamic drop-down menu in a form using HTML5 and JavaScript. I did that here.
Now, I need to call data from a JSON file. I looked at other answers on SOF and am still not really understanding how to use JQuery to get info from the JSON file.
I need to have 2 fields: the first field is a Country. The JSON key is country and the value is state. A copy of the JSON file and contents can be found here. The second drop-down field adds only the values / arrays related to its associated Country.
Here is a copy of my HTML5 file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a copy of the JS file I wrote so far that tries to get the data from the JSON file and fails:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the content from the other JS file that adds the field instruction:
var selectYourCountry = document.getElementById('selectCountry');
selectYourCountry.innerHTML = "Select Your Country: ";
var selectYourState = document.getElementById('selectState');
selectYourState.innerHTML = "Select Your State";
This was supposed to at least add the values to the field, but nothing but empty boxes appear on the web page.
I then need to make a conditional statement like the one at here but calling or referencing data from the JSON file.
I have only taken some HTML and JavaScript courses, not JQuery and JSON. So, your help will greatly increase my knowledge, which I will be very grateful for.
Thank you!!
I found this SOF answer and changed my JS file to the following:
$(document).ready(function()
{
$('#locationSelector').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"countryState.JSON",
dataType: "json",
success: function (data) {
$.each(data.country,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#locator');
});
}
});
});
});
And, I edited my HTML document as follows:
<form id="locationSelector" enctype='application/json'></form>
I removed and added back the <select> tags and with the following at least I get a blank box:
`<form id="locationSelector" enctype='application/json'>
<select id="locator"></select>
</form>`
I feel like I am getting closer, but am still lost.
Can you try this:
$.get("countryState.JSON", function( data ) {
var html = "";
$.each(data.d, function(i, el) {
console.log(el);
html += "<option value='"+Your value+"'>"+Your displayed text+"</option>";
});
$('#state').html(html);
});

Categories