Add name in pdf from text input inside pdf react js - reactjs

I have a pdf file url (which has a text input in it), which i need to show to user fill his name and submit. I am using pdf-lib to add text field in backend.
In frontend i am using pdf-lib to show pdf file,
Query
I have a text field, which i filled with dummy value, one man punch, when in frontend i change the value and click submit, i am still getting the same value, it's not changing t0 the new value.
Code to load Pdf file from url
const existingPdfBytes = await fetch(url, {
// mode: 'no-cors'
}).then(res => res.arrayBuffer());
const pdfDoc = await PDFDocument.load(existingPdfBytes);
setCurrentPdf(await pdfDoc.saveAsBase64({ dataUri: true }))
Code to show pdf inside iframe
<iframe ref={docRef} style={{width: '100%', height: '35rem'}} title="test-frame" src={currentPdf} type="application/pdf" />
<Button variant='contained' color="primary" onClick={submitClick}>
Submit
</Button>
Code to get File after user enter his name and click submit
const pdfDoc = await PDFDocument.load(docRef.current.src);
// await pdfDoc.save();
const form = pdfDoc.getForm()
const fields = form.getFields()
fields.forEach(field => {
console.log('Signature Value => ',field.getText())
const type = field.constructor.name
const name = field.getName()
// console.log(`${type}: ${name}`)
})
Here is the picture of rendered pdf

Related

Attempting to send uploaded file in React app to backend returning 'undefined'

I'm currently building some functionality in my React web app to upload a picture, display it on the client (this works), but also store the photo details so they can be sent in an axios post to my backend where the image gets stored in the file system.
Here's my code to now:
const SetupDetails = () => {
const [previewPhoto, setPreviewPhoto] = useState(null)
const [photoFile, setPhotoFile] = useState(null)
const uploadPhoto = (e) => {
e.preventDefault()
setPreviewPhoto(URL.createObjectURL(e.target.files[0]))
setPhotoFile(e.target.files[0])
}
const buttonClick = (e) => {
e.preventDefault()
console.log(previewPhoto)
console.log(photoFile)
axios.post("/api/uploadProfilePicture", {
photoFile: photoFile
})
}
const deletePhoto = (e) => {
e.preventDefault()
setPreviewPhoto(null)
setPhotoFile(null)
}
return (
<label for="photo-upload" className="setup-photo-label">Upload</label>
<input className="setup-photo-input" id="photo-upload" type="file" onChange={uploadPhoto} />
{
previewPhoto ?
<div className="preview-photo-container">
<img className="preview-photo" src={previewPhoto} alt="A small thumbnail uploaded by the user." />
<button className="preview-photo-delete" onClick={deletePhoto}>Delete</button>
</div> : null
}
<button className="setup-continue-button" onClick={buttonClick}>Continue</button>
)
}
The basic premise is:
The input calls a function during 'onChange' which updates state to store the details of the photo
The 'photoFile' details are posted to the backend to be stored in the backend
The 'previewPhoto' is used to display a thumbnail of the image to the user
However, the photoFile is returned as undefined, or an empty object, every time.
I'm not 100% sure where I'm going wrong, as the console.log of the 'photoFile' shows the details of the photo, so I'd have thought I could just post that to the backend.
Any advice here would be really appreciated!

Why is filepond sending a GET request at my server index when I remove a preloaded file?

Hi I'm using React filepond to upload files to our server and everything works fine for the most part.
The problem is when I have preloaded files, if I try to remove one of them Filepond sends a GET request to http://myserver.domain/12345.jpg
I don't know why this request is sent and this is not even an available endpoint on my server so it always returns an error with status 404.
My filepond instance is configured like this :
export default function FileField({
name,
control,
rules,
defaultValue = null,
isMultiple,
fileTypes,
component_id,
}) {
const [files, setFiles] = useState(defaultValue || []);
// Controller from React-Hook-Form
//(It's used to save the list of files for later use)
const { field } = useController({ name, control, rules, defaultValue });
// Filepond ref
const pond = useRef(null);
const handleChange = () => {
let files = pond.current.getFiles();
// Set the value of the control field
field.onChange(
files.map((f) => {
return { source: f.serverId, options: { type: 'local' } };
})
);
field.onBlur();
};
return (
<div className='px-4 py-4 rounded bg-window-accent'>
<FilePond
ref={(ref) => (pond.current = ref)}
files={files}
onupdatefiles={setFiles}
onprocessfile={handleChange}
onremovefile={handleChange}
required={rules.required.value}
allowMultiple={isMultiple}
server={`/api/files/${component_id}`}
name={'file'}
acceptedFileTypes={fileTypes}
disabled={rules.disabled}
/>
</div>
);
}
When loading the file the correct endpoint is used GET /api/files/12345?load=12345.jpg
It's just when I click on the (X) The file is removed correctly from the input field but there's that additional GET Request that makes no sense...
This error does not happen when a file is reverted after being just uploaded, only happens when the file is preloaded in the files with option type="local".
The error in console
What can I do to stop filepond from sending this extra request ?

How do I show uploaded image in React.js

So basically I have a field where the user can choose an image to upload, how do I make it so that when the user chooses the image, it displays that image on the screen.
Example, the user uploads the plant2.jpeg , how do i display that image on that same screen. My code is as follows:
import FileBase64 from 'react-file-base64'
//State to handle plant Files
const [plantFile , setPlantFile] = useState(null)
//Handle the input onDone for FileBase64
const handleFiles = (files) => {
setPlantFile(files)
}
<FileBase64
multiple = {false}
onDone = {handleFiles}
/>
The FileBase64 returns an object like below:
{
base64: "data:image/jpeg;base64,/9j/2wCEAAMCAgMCAgMDAwMEAw",
name: "plant2.jpeg",
type: "images/jpeg"
}
Is there a way I can display that image? Anyway I can make that happen?

How to download excel file from API in React?

I have excel file coming from API and I intend to implement a download button for users to click and download the file.
import FileDownload from "js-file-download";
function Download() {
const [facilityName, setFacilityName] = useState("");
const handleClick = (e) => {
e.preventDefault()
Axios({
url: `apiEndpoint/${facilityName}`,
method: "POST",
responseType:"blob",
}).then((res)=>{
console.log("myres", res)
FileDownload(res.data, `${facilityName}.xlsx`)
})
}
return (
<div>
<TextField
className="box"
name="facility_name"
select
required
value={facilityName}
onChange={(e) => setFacilityName(e.target.value)}
/>
<Button onClick={(e) => handleClick(e)}>
Download File
</Button>
</div>
);
}
export default Download;
When I click the download button, the file downloaded as excel but when I open the file, it reads "There was a problem with the content in filename.xlsx and so on". I have to download other excel file by change the {facility} var on the API and still got same error msg, only a blank page.
please i'm confused at this point, what am I missing in order to get the content of the file properly.

React Dropzone Uploader submitting files on drop instead of when i click submit

Exactly what the title says. I'm using React Dropzone Uploader (https://react-dropzone-uploader.js.org/). I use it mainly because i need to display pictures BEFORE uploading so i give the user the chance to select which pictures he wants to upload. The problem is that as soon as i drop or select the images they are sent. How should i go about sending the images once i press submit, because rightnow all it does is Erase the items from the list.
I checked the network tab in DevTools, and it just sends a Post, when i click the little X it doesn't send anything.
// Put files into the form data
const getUploadParams = ({ file }) => {
const body = new FormData();
body.append(`multi-images`, file);
//im guessing here is where they get posted
return { url: `https://page.com/api/album/${categoriaSeleccionada}/${albumSeleccionado}/uploadPhotos`, body
}
}
// called every time a file's `status` changes
const handleChangeStatus = ({ meta, file }, status) => { console.log(status, meta, file) }
// receives array of files that are done uploading when submit button is clicked
const handleSubmit = (files, allFiles) => {
console.log(files.map(f => f.meta))
allFiles.forEach(f => f.remove())
}
return (
<Dropzone
getUploadParams={getUploadParams}
name="multi-image"
inputContent={(image, extra) => (extra.reject ? 'Solo archivos de imagen' : 'Clickea aquĆ­ para buscar o arrastra archivos para subirlos')}
onSubmit={handleSubmit}
multiple={true}
onChangeStatus={handleChangeStatus}
styles={{
dropzone: {
minHeight: "80vh",
maxHeight: "80vh",
maxWidth:"80vw",
border: 0,
overflowX:"hidden"
}
,
previewImage: {
minHeight: 200,
maxWidth: 500
},
preview:{
minHeight:230,
objectFit:"cover"
}
}}
/>
)
}
export default Uploader
Is there a way i can make it wait till i press submit?
There is an autoUpload prop you can set it to false by default it's true.
You can see props docs here
And you can start the uploading manually as mentioned there:
you can call fileWithMeta.restart whenever you want to initiate file upload

Resources