I have a web site developed using React JS for Navigators, on my computer is working ok, but in a tablet I have an issue. I implemented a simple file chooser filering images only. The problem happens when I took the photo using the camera, it is the camera app in the device, but it doesn't always return to my web site the photo, sometimes there navigator is closed or sometimes a message appears that say the memory is not enough to complete the task.
The problem occurs around once per every ten photos taken, it sounds like a memory leak.
I am using the DropzoneComponent in React to load the image, here is my code:
Component:
import DropzoneComponent from 'react-dropzone-component';
Cod:
<DropzoneComponent
config={componentConfig}
eventHandlers={eventHandlers}
djsConfig={djsConfig}
/>
The configuration:
const djsConfig = {
addRemoveLinks: true,
autoProcessQueue: false,
maxFiles: 1,
maxFilesize: 1,
acceptedFiles: "image/png,image/jpeg",
dictDefaultMessage: 'Drop here the image or select',
dictFileTooBig: 'File is too big',
dictInvalidFileType: 'Invalid file',
};
const componentConfig = {
iconFiletypes: ['.jpg', '.png'],
showFiletypeIcon: true,
postUrl: 'no-url'
};
When the image is loaded I do this things to process the image, but this method is not called.
addedfile = (file) => {
alert('OLA K ASE')
this.dropzone.removeAllFiles();
Resizer.imageFileResizer(
file, //is the file of the new image that can now be uploaded...
900, // is the maxWidth of the new image
900, // is the maxHeight of the new image
'JPEG', // is the compressFormat of the new image
92, // is the quality of the new image
0, // is the rotatoion of the new image
uri => {
this.setState({ src: uri });
}, // is the callBack function of the new image URI
'base64' // is the output type of the new image
);
}
Related
I am using Cordova-electron with ReactJS to build a desktop application. we need to implement print-preview in our application instead of showing the default system dialog for printing.
The community says there is no default way to achieve this in electron, we need to do it manually. I used html2pdf.js,jsPDF to generate PDF from the client-side but none of these are giving the exact PDF we need, all have some alignment issues, font issues, and page-break issues, etc. please suggest me a proper solution for this issue.
I am attaching code to generate PDF by using html2pdf.js which I have used
var opt = {
margin: 1,
filename: 'myfile.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 1, logging: true, width: '1024', dpi: 100, letterRendering: true },
jsPDF: { unit: 'mm', orientation: 'portrait', format: 'a4' },
pagebreak: { after: '.page-break' }
}
var worker = html2pdf().set(opt).from(componentRef.current).to('pdf').output('blob').then(d => {
console.log('pdf-file', d);
var blob = new Blob([d], { type: "application/pdf" });
console.log('Blob-pdf', blob);
var url = URL.createObjectURL(blob);
var printWindow = window.open(url, '', 'width=800,height=500');
}).catch(d => {
console.error('error in PDF generation', d);
})
Unfortunately, the electron does not have a print preview, you can use nw.js instead of the electron if you want a print preview
I am working on a React project.
Here, I am trying to generate a PDF file (invoice) and upload it to Google Drive.
following code shows how I tried to create the file but I could not get the PDF file I needed. I would like to know how to generate the PDF file using html2pdf.js lib.
function createPDF() {
console.log('create PDF function works!');
let element = document.getElementById('report_component');
let opt = {
margin: 1,
filename: 'my-invoice.pdf',
image: {type: 'jpeg', quality: 0.98},
html2canvas: {scale: 2},
jsPDF: {unit: 'in', format: 'a4', orientation: 'portrait'}
};
// New Promise-based usage:
// window.html2pdf().set(opt).from(element).save(); // I do not want to save/download the PDF using the web browser.
// I want to get the PDF file. I tried like this;
let value = window.html2pdf().set(opt).from(element).toContainer().toCanvas().toImg().toPdf().output();
// const blob = new Blob([value], { type: 'application/pdf'});
let file = new File([value], 'my-invoice.pdf', {
type: 'application/pdf',
});
/* Here I try to implement the code to upload the PDF file to Google Drive.
* First I need to get the PDF File. */
console.log(file);
}
If any one searching an answer for this question. here it is;
I wanted to create a report(invoice) using HTML. Below you can find how I designed my invoice.
Note: Please note that I included html2pdf.js as a script in HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Invoice</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
</head>
<body>
<section id="my_invoice">
<!-- I designed the invoice here -->
</section>
</body>
</html>
Most of the existing code tutorials show us to download the generated PDF. Following JavaScript code will help you to download the PDF. When you run this code, browser will open a window and asks where to download this PDF file. Then, you can save the PDF file easily.
let element = document.getElementById('my_invoice');
let opt = {
margin: 1,
filename: 'my-invoice.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
};
// New Promise-based usage:
html2pdf().set(opt).from(element).save();
But my requirement was slightly different. I just wanted to create the PDF file. Then, do something with that file. In my scenario, I wanted to upload that generated PDF file to Google Drive. Following code segment shows how I use html2pdf.js to generate the PDF file(blob). Please note that I used .outputPdf() method to get the blob. For more information, you can refer to the html2pdf.js Worker API documentation.
/** Creates the PDF report document.
* #return Promise: resolves if PDF report generates successfully,
* otherwise rejects. */
function createPDF() {
return new Promise(async (resolve, reject) => {
console.log('create PDF function executed!');
let element = document.getElementById('my_invoice');
let opt = {
margin: 1,
filename: 'my-invoice.pdf',
image: {type: 'jpeg', quality: 0.95},
html2canvas: {scale: 2, useCORS: true},
jsPDF: {unit: 'in', format: 'a4', orientation: 'portrait'}
};
try {
const blob = await window.html2pdf().set(opt).from(element).outputPdf('blob', 'my-invoice.pdf');
resolve(blob);
} catch (e) {
reject(e);
}
});
}
Hope you learnt something. Cheers!
I am using fineuploader to upload images and pdf files for my contact form. But when i try uploading pdf files, it cause an unknown error exception even if i add the pdf extention to the allowedExtensions array.
Images are uploaded without problems.
Here ist my config code:
var DEFAULT_CONFIG = {
autoUpload: true,
cors: {
expected: true,
},
maxConnections: 2,
element: document.getElementById('fine-uploader'),
request: {
endpoint: SERVICE_ENDPOINT,
forceMultipart: false,
params: SERVICE_PARAMS,
},
validation: {
sizeLimit: 1024 * 1024 * 50,
allowedExtensions:["bmp","gif","jpg","jpeg",
"pcx","png","tga","tiff", "tif", "doc", "docx", "pdf"],
},
workarounds: {
iosEmptyVideos: false,
}
};
How to add existing files on server to dropzone with right work all functions and right styling?
I wrote a function to add files: addCustomFile(file, thumbnail_url , responce)
Powered by Version: 4.0.1 stable
Correct working: maxFiles limit, event maxfilesexceeded, event success and others
$("#dropzone-images").dropzone({
url: "...",
paramName: 'image_temp',
maxFiles: 1,
init: function () {
this.addCustomFile = function(file, thumbnail_url , responce){
// Push file to collection
this.files.push(file);
// Emulate event to create interface
this.emit("addedfile", file);
// Add thumbnail url
this.emit("thumbnail", file, thumbnail_url);
// Add status processing to file
this.emit("processing", file);
// Add status success to file AND RUN EVENT success from responce
this.emit("success", file, responce , false);
// Add status complete to file
this.emit("complete", file);
}
this.addCustomFile(
// File options
{
// flag: processing is complete
processing: true,
// flag: file is accepted (for limiting maxFiles)
accepted: true,
// name of file on page
name: "The name",
// image size
size: 12345,
// image type
type: 'image/jpeg',
// flag: status upload
status: Dropzone.SUCCESS
},
// Thumbnail url
"http://.../img.jpg",
// Custom responce for event success
{
status: "success"
}
);
}
});
I am using Plupload js plugin to upload multiple images in one request. This plugin is working like if someone adding 5 images at a time then post request will go 5 times to upload each of images separately. As we know Post request require unique csrf token but in my case due to same token after one time, post request is failing.
Here is my code ...
<c:set var="csrfTokenVal"><csrf:token-value uri="<%=request.getRequestURI()%>"/></c:set>
<script>
var csrftokenV="${csrfTokenVal}";
$("#uploader").plupload({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url:'/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+csrftokenV,
// User can upload no more then 20 files in one go (sets multiple_queues to false)
max_file_count: 10,
chunk_size: '1mb',
// Resize images on clientside if we can
resize : {
width : 600,
height : 610,
quality : 90,
//crop: true // crop to exact dimensions
},
filters : {
// Maximum file size
max_file_size : '1mb',
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
]
},
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
// Views to activate
views: {
list: true,
thumbs: false, // Show thumbs
active: 'thumbs'
},
init: {
FilesAdded: function(up, files) {
$("#uploader_filelist").show();
},
FileUploaded: function(up, file, info, res) {
var imageObjectArray=$.parseJSON(info.response);
for(i=0;i<imageObjectArray.objectList.length; i++){
$('#showfilelist ul').append("<li><a class='delIcon-image' href='#delete' id='delSurgeryImageIcon'></a><a id=" + imageObjectArray.objectList[i].uid + " class='cboxElement imguid' href='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' target='_blank'><img src='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' border='0'>"+"</a> <strong>"+noteAddedMsg+"</strong><span class='image-created'>"+imageObjectArray.objectList[i].formattedDate+" "+byMsg+" "+imageObjectArray.objectList[i].userName+" </span></li>");
}
$("#uploader_filelist").empty().hide();
_SPINE.colorboxOverlay.coloboxPopup();
_SPINE.surgeryNotes.deleteImages();
$(".plupload_done .plupload_file_thumb").removeClass("hide")
},
ChunkUploaded: function (up, file, response) {
response = $.parseJSON(response.response || "null");
if (response.chunk == 3) {
up.stop();
up.start();
}
console.log(file.loaded);
}
},
// Flash settings
flash_swf_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.swf',
// Silverlight settings../assets/js
silverlight_xap_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.xap'
});
</script>
Here you can see I am generating scrf token (csrftokenV) and sending it in url to make it post supported.
Now the problem is if I am uploading more than 1 images (lets say 3), then 3 time post request will go. Each time i will get same csrf token and after uploaing first image, furthure images will not work and i will get this exception ....
WARNING: potential cross-site request forgery (CSRF) attack thwarted (user:<anonymous>, ip:127.0.0.1, uri:/**/image, error:request token does not match session token)
Please help me to solve this problem. Thanks
Finally One of my friend had solved the issue. It can't be possible to handle this issue through client side script so we leverage the power of Java. We had updated the csrfToken based on new request and sent it out with response.
Here is a solution ..
private String updateToken(HttpServletRequest request)
{
final HttpSession session = request.getSession(false);
CsrfGuard csrfGuard = CsrfGuard.getInstance();
csrfGuard.updateTokens(request);
String newToken=(String) session.getAttribute(REQUEST_TOKEN);
return newToken;
}
Setting newToken in response ...
response.setResult(this.updateToken(request));
return response;
Now we can change the url in beforeUpload event and set new token in the url.
BeforeUpload: function(up, file)
{
up.settings.url='/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+tokenRefresh
}
FileUploaded: function(up, file, info, res)
{
var imageObjectArray=$.parseJSON(info.response);
tokenRefresh=imageObjectArray.result;
}