Hi i'm using html2pdf on my React project and i'm going through problems when i try to generate the pdf document.
The problem is that in Android/desktop the UI freeze for a while (time that take to generate pdf file) and then the download work fine. In iphone the UI freeze and never recover, i can't interact with others components like a table or a combo, it only recover if I close the explorer and reopen and when I do that the pdf file appears in the screen with the right format and look.
Here is what i'm doing:
const PdfDownloader = (props) => {
const exportToPDF = (fileName) => {
let opt = {
margin: 0.5,
filename: `${fileName}.pdf`,
image: {type: 'jpeg', quality: 0.98},
html2canvas: {scale: 2},
jsPDF: {unit: 'in', format: 'letter', orientation: 'portrait'}
};
html2pdf().set(opt).from(pdfContainerRef.current).save();
}
return (
<div>
<Button className={styles["max-width-initial"]} block
onClick={() => exportToPDF('my_crazy_file')}>
Descargar PDF
</Button>
</div>
)
}
I have no idea what i'm doing wrong, or if something missing in my code or i'm in front of a bug.
Related
Goal: Copy an image from HDD and get it(by pasting it) on my Flutter web app
What I tried:
Clipboard doesn't support image type.
Pasteboard works if I add images manually (from the app), but I need to add images from the desktop by copying it and for this it doesn't work. In particular the error is that image type is not supported.
Manually doing it using Javascript APIs and the result is the same of pasteboard.
I hope that my answer is clear. Thank you!
Example code using Pasteboard:
import 'package:flutter/material.dart';
import 'package:pasteboard/pasteboard.dart';
class TestPage extends StatefulWidget {
const TestPage({super.key});
#override
State<TestPage> createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
#override
Widget build(BuildContext context) {
return Column(
children: [
Container(
width: 500,
height: 500,
color: Colors.red,
),
TextButton(
onPressed: () async {
// works if you copy text
var text = await Pasteboard.text;
print("text: $text");
// works if you copy text, returns null if you copy an image
var html = await Pasteboard.html;
print("text: $html");
// Returns always null
var image = await Pasteboard.image;
print(image);
},
child: const Text('Click me', style: TextStyle(fontSize: 20)),
),
],
);
}
}
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 trying to do from my dynamic HTML(where I am taking data in tables and just text from DB), by using jspdf return just empty file pdf.
<script>
$("#btn-print").click(() => {
var pdf = new jsPDF();
pdf.addHTML(document.section, function () {
pdf.save("report.pdf");
});
});
</script>
It would be better to use html2pdf which uses combination of html2canvas,jsPDF and has multiple options for a rich pdf conversion of web page
using a sample table (used static data but should work same for dynamic too)
function genPDF() {
var element = document.getElementById('pdfContent');
var opt = {
margin: 1,
filename: 'myfile.pdf',
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
// New Promise-based usage:
html2pdf().from(element).set(opt).save();
}
See working example here
Do not forget to include cdn links
Hit GeneratePDF Button to download as pdf and check in downloads location
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
);
}