Extract inputs list (fields) from a pdf file to create an html form in react js

Asked
Active3 hr before
Viewed126 times

11 Answers

extractfieldscreateinputsreact
90%

In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().,Overall, this makes it so that <input type="text">, <textarea>, and <select> all work very similarly - they all accept a value attribute that you can use to implement a controlled component.,In React, a <textarea> uses a value attribute instead. This way, a form using a <textarea> can be written very similarly to a form that uses a single-line input:

<form>
   <label>
      Name:
      <input type="text" name="name" />
   </label>
   <input type="submit" value="Submit" />
</form>
load more v
88%

Unlike most elements in an HTML document, form fields can get keyboard focus. When clicked—or activated in some other way—they become the currently active element, the main recipient of keyboard input.,By default, most types of HTML elements cannot be focused. But you can add a tabindex attribute to any element, which will make it focusable.,A lot of field types use the <input> tag. This tag’s type attribute is used to select the field’s style. These are some commonly used <input> types:

Fields

/n

A web form consists of any number of input fields grouped in a <form> tag. HTML allows a number of different styles of fields, ranging from simple on/off checkboxes to drop-down menus and fields for text input. This book won’t try to comprehensively discuss all field types, but we will start with a rough overview.

<form>
load more v
72%

So I will briefly work you through a simple example of generating pdf from the MoviesDB API. This demo is going to demonstrate generating the best movies of the year.,While going through the documentation when I was trying to pick the appropriate library for my use-case there were some features of React-pdf that convinced me to use it, I will briefly talk about them:,Before I used this library I never thought it was possible to generate PDF on the client-side, Not only does react-pdf allow you do that but get to use JSXesque syntax to structure and design the PDF document. I know the demo is quite trivial but I think this library might be useful in some use cases.

project│ package.json││└─── Public││ 150. png││ index.html││ star.png│││└─── src│ Movie.jsx│ MovieList.jsx |
   constant.js |
   index.js |
   styles.css
load more v
65%

The most basic way of working with forms in React is to use what are referred to as “uncontrolled” form inputs. What this means is that React doesn’t track the input’s state. HTML input elements naturally keep track of their own state as part of the DOM, and so when the form is submitted we have to read the values from the DOM elements themselves.,instant input validation: we can give the user instant feedback without having to wait for them to submit the form (e.g. if their password is not complex enough),In order to associate the ref with an input, it’s passed to the element as the special ref attribute. Once this is done, the input’s underlying DOM node can be accessed via this.nameEl.current.

In order to do this, React allows us to create a “ref” (reference) to associate with an element, giving access to the underlying DOM node. Let’s see how to do this:

class SimpleForm extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the DOM element
    this.nameEl = React.createRef();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    alert(this.nameEl.current.value);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>Name:
          <input type="text" ref={this.nameEl} />
        </label>
        <input type="submit" name="Submit" />
      </form>
    )
  }
}
load more v
75%

Retrieving values from HTML input elements in a form is one of the most basic tasks in JavaScript. React.js makes it easy by allowing you to define an object whose attributes are bound against the input elements of a form. This way, an update to the value of an input element will automatically update the value of the object's attribute that it was bound to.,Bind the value of the object's attributes to its corresponding HTML input element's value attribute.,Now that you have the customer object as part of the state, bind the object's values to the value attribute of your HTML input elements using JSX. This can be found in the component's render() method:

1
import React from 'react';
2
3
export default class CustomerForm extends React.Component {
   4 constructor(props) {
      5 super(props);
      6
      7 this.state = {
         8 customer: {
            9 firstName: props.firstName,
            10 lastName: props.lastName,
            11 status: props.status
            12
         }
         13
      }
      14
   }
   15
}
load more v
40%

In your App.js file, create a basic form that with a name field and a file input.,Now, add state in the component to store the name and the file data.,Now that the basic form is set up, create a custom file uploader component that can be reused across multiple forms in the app.

1import React from "react";
2
3const App = () => {
4  return (
5    <div className="App">
6      <form>
7        <input type="text" />
8
9        <input type="file" />
10      </form>
11    </div>
12  );
13};
load more v
22%

Every field requires the same chunks of code, which can easily get verbose as your forms get more complex. And this verbosity has consequences, as verbose code is harder to maintain, and is also harder to refactor as your business requirements change.,The beauty of the KendoReact Form is just how easy it is to customize everything you see to meet your real-world requirements.,TIP: Check out the KendoReact Form Design Guidelines for best practices and usage examples for building great forms in React.

Let’s start by looking at an implementation of this form with no libraries, as it’ll show some of the challenges inherent to building forms with React today. The code to implement the form is below. Don’t worry about understanding every detail, as we’ll discuss the important parts momentarily.

import React from "react";
import countries from "./countries";

export default function App() {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [country, setCountry] = React.useState("");
  const [acceptedTerms, setAcceptedTerms] = React.useState(false);

  const handleSubmit = (event) => {
    console.log(`
      Email: ${email}
      Password: ${password}
      Country: ${country}
      Accepted Terms: ${acceptedTerms}
    `);

    event.preventDefault();
  }

  return (
    <form onSubmit={handleSubmit}>
      <h1>Create Account</h1>

      <label>
        Email:
        <input
          name="email"
          type="email"
          value={email}
          onChange={e => setEmail(e.target.value)}
          required />
      </label>

      <label>
        Password:
        <input
          name="password"
          type="password"
          value={password}
          onChange={e => setPassword(e.target.value)}
          required />
      </label>

      <label>
        Country:
        <select
          name="country"
          value={country}
          onChange={e => setCountry(e.target.value)}
          required>
          <option key=""></option>
          {countries.map(country => (
            <option key={country}>{country}</option>
          ))}
        </select>
      </label>

      <label>
        <input
          name="acceptedTerms"
          type="checkbox"
          onChange={e => setAcceptedTerms(e.target.value)}
          required />
        I accept the terms of service
      </label>

      <button>Submit</button>
    </form>
  );
}
load more v
60%

Form.js: Form component renders a form and contains all the logic to make it controlled form and submitting the form.,ES2015 introduced the ability to create objects with dynamic keys based on JavaScript expression called as computed property names. We use computed property names to update the state of all the input fields based on the name attribute of inputs. ,NewBoxForm.js: This component is responsible to show the form to users to enter the properties of the box they wanted to create. The form is a controlled form i.e. it stores the values of the input field in states and updates it in real-time according to user interaction with input fields of the form. It invoked handle submit callback after submitting the form which in return invoke the create method of BoxList component passing the form values to create the box.

Syntax : 

const obj = {
   : value
}
load more v
48%

The idea is to convert : HTML -> Canvas -> PNG (or JPEG) -> PDF,Rendering react as pdf is generally a pain, but there is a way around it using canvas. ,Steps : HTML -> Image (PNG or JPEG) -> PDF

import React, {Component, PropTypes} from 'react';

// download html2canvas and jsPDF and save the files in app/ext, or somewhere else
// the built versions are directly consumable
// import {html2canvas, jsPDF} from 'app/ext';


export default class Export extends Component {
  constructor(props) {
    super(props);
  }

  printDocument() {
    const input = document.getElementById('divToPrint');
    html2canvas(input)
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF();
        pdf.addImage(imgData, 'JPEG', 0, 0);
        // pdf.output('dataurlnewwindow');
        pdf.save("download.pdf");
      })
    ;
  }

  render() {
    return (<div>
      <div className="mb5">
        <button onClick={this.printDocument}>Print</button>
      </div>
      <div id="divToPrint" className="mt4" {...css({
        backgroundColor: '#f5f5f5',
        width: '210mm',
        minHeight: '297mm',
        marginLeft: 'auto',
        marginRight: 'auto'
      })}>
        <div>Note: Here the dimensions of div are same as A4</div> 
        <div>You Can add any component here</div>
      </div>
    </div>);
  }
}
load more v
23%

You should use constructor under the class MyComponent extends React.Component

constructor(props) {
   super(props);
   this.onSubmit = this.onSubmit.bind(this);
}
load more v
90%

An Input component displays an input, or a dropdown list, a list of radio buttons, etc. Such components allow to edit a record property, and are common in the <Edit> and <Create> components, and in the List Filters.,If, instead of showing choices as a dropdown list, you prefer to display them as a list of radio buttons, try the <RadioButtonGroupInput>. And if the list is too big, prefer the <AutocompleteInput>.,If you want to let the user choose a value among a list of possible values that are always shown (instead of hiding them behind a dropdown list, as in <SelectInput>), <RadioButtonGroupInput> is the right component.

// in src/posts.js
import * as React from "react";
import { Edit, SimpleForm, ReferenceInput, SelectInput, TextInput, required } from 'react-admin';

export const PostEdit = (props) => (
    <Edit title={<PostTitle />} {...props}>
        <SimpleForm>
            <TextInput disabled source="id" />
            <ReferenceInput label="User" source="userId" reference="users" validate={[required()]}>
                <SelectInput optionText="name" />
            </ReferenceInput>
            <TextInput source="title" label="Post title" validate={[required()]} />
            <TextInput multiline source="body" initialValue="Lorem Ipsum" />
        </SimpleForm>
    </Edit>
);
load more v

Other "extract-fields" queries related to "Extract inputs list (fields) from a pdf file to create an html form in react js"