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
Related
I am using the jsPDF library for converting a table into a PDF file.
The current code that I have used is giving off an error, that autoTable is not a function.
Here is the code.
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"sap/ui/core/util/Export",
"sap/ui/core/util/ExportTypeCSV"
],
function (Controller, JSONModel, Export, ExportTypeCSV) {
"use strict";
return Controller.extend("c.g.modalproject1.controller.Root", {
onInit: function () {
var oModel1 = new JSONModel("./model/vegetableDataJSON.json");
this.getView().setModel(oModel1, "veg");
console.log("data : ", oModel1);
},
openDialog1: function () {
if (!this.pdialog1) {
this.pdialog1 = this.loadFragment({
name: "c.g.modalproject1.fragments.mTables"
});
}
this.pdialog1.then(function (oDialog) {
oDialog.open();
})
new sap.m.MessageToast.show("Table Loaded");
},
closeDialog: function () {
this.byId("newDialog1").close();
sap.m.MessageToast.show("Table closed ! ");
// var vegTable = this.getView().byId("vegiesMTable");
// vegTable.setGrowing(false);
// vegTable.setGrowingScrollToLoad(false);
},
downloadCSV: function () {
// Show a toast message to indicate that the file is downloading
sap.m.MessageToast.show("Downloading Excel..");
// Create a new Export object with the specified export type and options
var oExport = new Export({
exportType: new ExportTypeCSV({
separatorChar: ","
}),
models: this.getView().getModel("veg"),
rows: {
path: "/vegetablesRootNode"
},
columns: [{
name: "Title",
template: {
content: "{title}"
}
},
{
name: "Type",
template: {
content: "{type}"
}
},
{
name: "Description",
template: {
content: "{description}"
}
},
{
name: "Price",
template: {
content: "{price}"
}
},
{
name: "Rating",
template: {
content: "{rating}"
}
}]
});
// Save the file and handle any errors that may occur
oExport.saveFile().catch(function (oError) {
sap.m.MessageToast.show("Error when downloading data. Browser might not be supported!\n\n" + oError);
}).then(function () {
// Destroy the export object
oExport.destroy();
});
},
downloadPDF:function()
{
sap.m.MessageToast.show("Downloading into PDF started !");
var oModel2 = this.getView().getModel("veg");
console.log("check data = ", oModel2);
var oColumns = ["Title","Type","Description","Price","Rating"];
var oRows = [];
oRows = oModel2.oData.vegetablesRootNode;
console.log(oColumns);
console.log(oRows);
//var pdfDoc = new jsPDF('p', 'pt', 'letter');
var pdfDoc = new jsPDF();
pdfDoc.text(20, 20, "Vegetables Table");
pdfDoc.autoTable(oRows, oColumns);
pdfDoc.save("test.pdf");
//pdfDoc.output("save","t.pdf");
}
});
});
The last function is the code that runs to save the table data into PDF.
Can you please help.
These are the files that are included in my project folder.
Manifest.json
Adding just text, and most of the functionality that is available (via methods) from jsPDF works fine. I have created PDFs with just text from this app as well.
It works fine for adding text and downloads fine. But for Table data, it doesnt work.
I tried various ways but didn't get to solve it at all.
I tried to make a POC with this library and it works :-)
Configure the framework so that it can load the libraries
sap.ui.loader.config({
// activate real async loading and module definitions
async: true,
// load thirparty from cdn
paths: {
"thirdparty/jsPDF": "https://unpkg.com/jspdf#2.5.1/dist/jspdf.umd.min",
"thirdparty/jsPDFautoTable": "https://unpkg.com/jspdf-autotable#3.5.28/dist/jspdf.plugin.autotable"
},
// provide dependency and export metadata for non-UI5 modules
shim: {
"thirdparty/jsPDF": {
amd: true,
exports: "jspdf"
},
"thirdparty/jsPDFautoTable": {
amd: true,
exports: "jspdf",
deps: ["thirdparty/jsPDF"]
}
}
});
You can put that code on top on your Component.js file
Idea is to configure the framework to load libraries from CDN as AMD module with dependencies.
It's a bit tricky in your case and I'm not sure I understand the mechanism; what I imagine is that autoTable is a jsPDF plugin so we need jsPDF (dependency); the plugin overload jsPDF and returns jsPDF object
For sap.ui.loader here the official doc. :
https://sapui5.hana.ondemand.com/sdk/#/api/sap.ui.loader/methods/sap.ui.loader.config
Loads and consumes libraries
sap.ui.require(["thirdparty/jsPDFautoTable"], (jsPDFautoTable) => {
var doc = new jsPDFautoTable.jsPDF();
doc.autoTable({ html: '#my-table' });
doc.save('table.pdf');
});
Either with sap.ui.define or sap.ui.require to load the library on the fly when needed
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 have little knowledge on promises ,
What i have been doing is to convert html to pdf , thankfully html2pdf works great ,
Now where I was stuck is getting the pdf as a file and post to server with form-data
I have somehow found to get pdf encoded string from here
But it is a promise and i have a function as :
genPDF:function(){
var element = document.getElementById('canvasId');
var opt = {
filename: 'nobutton.pdf',
image: { type: 'jpeg', quality: 0.98 },
// html2canvas: { scale: 2 },
};
html2pdf().from(element).set(opt).toPdf().output('datauristring').then(function (res) {
var blobString = res;
console.log(blobString);
});
}
But here it doesn't log at first time , but then the function is called again and then logs , why is that ?? could i get it for the first time the function called ?
Can some one help me how to get the pdf from html2pdf as a file so that can append it to form-data , any help is really appreciated , Thanks :)
#Sophie - here is the asnyc version as discussed in the comments.
async genPDF() {
var element = document.getElementById('canvasId');
var opt = {
filename: 'nobutton.pdf',
image: { type: 'jpeg', quality: 0.98 },
// html2canvas: { scale: 2 },
};
let blobString = await html2pdf().from(element).set(opt).toPdf().output('datauristring');
console.log(blobString);
}
I have a view that i need to export to pdf but to show this view i need to send a parameter to specific route and i don't know how to call route instead html file.
My route:
viewBicsDetails(req, res)
{
var ref = req.params.stamp;
var info = request.query("query");
var compounds = request.query("query");
return Promise.all([info, compounds]).then(function(results)
{
console.log(results[0]);
res.render('management-bic-details', {info : results[0], compounds: results[1]});
});}
How can I export this render to pdf? i installed the html-pdf npm library.
https://www.npmjs.com/package/html-pdf
var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});
In readFileSync i should put the route.. but how?
Thank you
Solution 1, with HTML and PDF templates
Make pdf template and fill it with javascript code. HTML and PDF templates will be different!
There are a lot packages with this functionality. For example, pdffiller
Solution 2, with single HTML template
Under the hood html-pdf implements this approach.
Fill HTML template.
Render image via phantomjs or any headless browser.
Compile image to a single pdf file.