Electron.js cannot save pdf files via jspdf - javascript

My goal is to save some parts of the view from current window as a PDF file, using canvas first. I used a solutions proposed in this tutorial.
$('#to_pdf').on('click', function(){
const filename = "myfile.pdf"
html2canvas(document.querySelector('#myElement'))
.then(canvas => {
let pdf = new jsPDF('p', mm', 'a4')
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0,0,211,298)
pdf.save(filename)
})
})
After clicking on button with 'to_pdf' id html2canvas should transform part of my view into canvas and then save it as pdf to the user's directory. Im inside this function, everything is executed without any errors. However pdf.save(filename) is not working since I cannot save pdf.
Is this an electron restriction which prevent me from saving files by default? How can I fix it?

This Code is working fine(single quote is missing)
after i add single quote
let pdf = new jsPDF('p', mm', 'a4')<----------jsPDF('p', 'mm', 'a4')
working code in my electron app
$('#to_pdf').on('click', function(){
const filename = "myfile.pdf"
html2canvas(document.querySelector('#myElement'))
.then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4')
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0,0,211,298)
pdf.save(filename)
})
})

Related

The "jspdf" library, when inserting the same image, loads it into the browser again each time. How to fix it?

Using the jspdf library, I am creating a pdf file. It has headers. Site logo in headers. I noticed that for each sheet of the pdf file, the library reloads the logo (logo requests are visible in the Network tab). This slows down the formation of the pdf file. And in general, not very good, the picture is the same, why upload it several times.
Is it possible to make the image load not for each sheet of the pdf file, but once for the entire pdf file?
Here is the code to insert the image:
let doc = new jsPDF('p', 'pt');
...
let pageCount = doc.internal.getNumberOfPages();
...
let logoImg = new Image();
logoImg.src = logoImgPath;
...
for (let i = 1; i <= pageCount; i++) {
// This line inserts an image into a pdf sheet. In the Network tab in the browser, I noticed that the picture is loaded for each sheet. Is there any way to make that the image is loaded only once - for the entire pdf file?
doc.addImage(logoImg, 'png', 10, 10, 100, 80);
}

How to download React Component as PDF with High Resolution?

I have been building a bottle label making application using React. People are able to create customized labels as they want. I have already add the functionality to let the users download the results in the form of a PDF.
Generating a PDF file from React Components
I implemented download React component to PDF by reference above link.
html2canvas & jsPDF.
Btw there's a quality issue. If I zoom in the downloaded PDF file, the quality is not good. (React component size is 380px * 380px).
Instead of it, if I zoomin(500%) the chrome browser and then download PDF, the quality is very good even zoom in on PDF reader(Foxit Reader or Chrome PDF Viewer).
Maybe the PDF resolution that downloaded using the html2canvas & jsPDF seems like according on component size.
So I have to ask customers to download PDF after they zoomin the browser(500%) if they want PDF with high resolution? lol. That's not.
I read the several articles about downloading PDF but not find solution yet.
Is there any method to implement above function as code?
As reference, this is my code which download pdf using html2canvas & jsPDF.
const printRef = React.useRef<HTMLDivElement>(null);
...
const handleDownloadPdf = async () => {
const element: any = printRef.current;
const canvas = await html2canvas(element);
const data = canvas.toDataURL("image/png");
const pdf = new jsPDF("portrait", "px", [380, 380]);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
pdf.addImage(data, "PNG", 0, 0, pdfWidth, pdfHeight);
pdf.save("label.pdf");
};
...
<div ref={printRef} style={{ height: "380px" }}>
<Label/>
</div>
I found another solution. I should control the size of canvas.
html2canvas(element, {
scale: 5,
}).then(function (canvas) {
var data = canvas.toDataURL("image/png");
pdf.addImage(data, "PNG", 0, 0, pdfWidth, pdfHeight);
pdf.save("label.pdf");
});

How can we export pdf created in jspdf as an image?

I've created a pdf in my program using jspdf, I'm providing an option to download as image or as pdf, so Can I use jspdf in some way or the pdf I created using jspdf in someway to store it as image?
I
Transform HTML into image first and then into PDF. To turn HTML into image uses the html2canvas and through the addImage method you create the PDF.
Example:
const html_source = document.getElementById('contentID'); // Get html
html2canvas(html_source).then(function(canvas) { // Convert to canvas
let imgData = canvas.toDataURL('image/png'); // Generates image that you can store
let pdf = new jsPDF('p', 'mm', 'a4'); //Create PDF, Note that you use the same image to create the PDF
pdf.addImage(imgData, 'PNG', 10, 10);
pdf.save('test.pdf');
})

Can you insert a PDF generated by PDFKit into a MongoDB collection?

I'm generating a PDF using the PDFKit library and I would like to insert the generated PDF into a MongoDB collection. On the client side a user should be able to see the list of files in the collection and choose one of these files to download.
As of now I'm saving the PDF in the collection as a Uint8Array and I can then click on the file at the front end to download it.
However, my problem is that the file seems to be corrupt. It will not open in Adobe Reader or in Chrome.
I've tried saving it to the collection with and without PDFKits compression.
Is this possible to do? Or do I have a bad approach to this.
Any help with this would be great and thanks in advance!
Server Side
Most of the code here is based off of this post on the PDFKit GitHub
var doc = new PDFDocument();
var stream = require('stream');
var converter = new stream.PassThrough();
doc.pipe(converter);
var data = [];
converter.on('data', function(chunk) {
data.push(chunk);
});
converter.on('end', Meteor.bindEnvironment( function () {
var buffer = Buffer.concat(data);
PdfFiles.insert({ data:buffer, userID:userId });
}));
// Adding content to the PDF
doc.end();
Client Side
'click .downloadPDF': function (event) {
event.preventDefault();
var file = UserFiles.findOne({userID:Meteor.userId()});
var FileSaver = require('file-saver');
var blob = new Blob(file.data, {type: "application/pdf"});
FileSaver.saveAs(blob, "AwesomePDF");
}
I got the code to work as intended simply by changing:
var blob = new Blob(file.data, {type: "application/pdf"});
to
var blob = new Blob([file.data], {type: "application/pdf"});

How to open (not save) a generated blob array of a pdf (Intel XDK-Android)?

I want to know a properly and proved way to open (not save) a generated blob array of a pdf with some default app for that (e.g. Adobe reader) if I am developing for Android with Intel XDK and Cordova.
Unsuccessfully I tried this (generated with jspdf):
function createPDF(){
console.log("generating pdf...");
var doc = new jsPDF();
doc.text(20, 20, 'HELLO!');
doc.setFont("courier");
doc.setFontType("normal");
doc.text(20, 30, 'This is a PDF document generated using JSPDF.');
doc.text(20, 50, 'YES, Inside of cordova!');
pdfOutput = doc.output();
console.log(pdfOutput);
var buffer = new ArrayBuffer(pdfOutput.length);
var array = new Uint8Array(buffer);
for (var i = 0; i < pdfOutput.length; i++) {
array[i] = pdfOutput.charCodeAt(i);
}
var pdfAsDataUri = "data:application/pdf;base64," + array;
window.open(pdfAsDataUri);
}
Also I tried a lot of example but nothing works, just in case, none error is shown in console.
Thank you all.
You can create a Blob from pdfOutput, then create a Blob URL from Blob using URL.createObjectURL()
var blob = new Blob([pdfOutput], {type:"application/pdf"});
var url = URL.createObjectURL(blob);
var pdfAsDataUri = url;
window.open(pdfAsDataUri);
plnkr http://plnkr.co/edit/xt5uVvskmcgSlf13xVVM?p=preview
Finally I can do it splitting the problem to:
*One button to create the document
*One button to create the pdf content
*One button to write the pdf content into the created document
*One button to open the file
*Only Cordova File plugin
And following and adapting the solution in this post:
https://github.com/pwlin/cordova-plugin-file-opener2/issues/60
Later I´ll do a video tutorial because this issue seems to be common and hard to solve.

Categories