How to set font for html2pdf in jsPDF? - javascript

I need to use a Bengali font while generating my pdf. I have converted the font using fontconverter and it works fine for adding text. I mean the following things are working, i.e., I can see my Bengali Text in the generated pdf -
var doc = new jsPDF();
doc.setFont('SolaimanLipi', 'normal');
doc.text("অতীশ", 10, 60);
doc.setFont('SolaimanLipi', 'normal'); // set font
doc.setFontSize(50);
However, doc.setFont('SolaimanLipi', 'normal') is not working if use html2pdf. For instance, following code is not working.
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.setFont('SolaimanLipi', 'normal');
html2pdf(document.body, pdf, function (canvas) {
var iframe = document.createElement('iframe');
iframe.setAttribute('style', 'position:absolute;right:0; top:0; bottom:0; height:100%; width:500px;font-family:SolaimanLipi;');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
}
);
What is the way of setting font for html2pdf?

Related

Using jsPDF to create a PDF from an iframe

Ok, I have scoured the internet for a solution to this but I can't find anything. I am trying to find a way to save the contents of an iframe as a PDF. I am always running into an issue where the PDF is just blank. It seems that jsPDF is the only way. I'm kind of wondering if the reason this isn't working is because of the fromHTML() function. I'm not sure. If any of you have figured out a solution I would be very appreciative!!
Here is some sample code you can try in an HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script>
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
source = $('#frame')[0];
specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
pdf.fromHTML(
source,
margins.left,
margins.top, {
'width': margins.width,
'elementHandlers': specialElementHandlers
},
function (dispose) {
pdf.save('Test.pdf');
}, margins);
}
</script>
<button onclick="javascript:demoFromHTML();">PDF</button>
<iframe id="frame" src='https://wikipedia.org/wiki/Main_Page' style="width: 75%;height: 75%;"></iframe>
Go through this article : Convert HTML/CSS Content to a Sleek Multiple Page PDF File Using jsPDF JavaScript library. The provided script allows you to convert any HTML element to PDF. I modified the generate() function slightly so that it takes any HTML element id name and export it as PDF file:
generate = function(doc)
{
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.setFontSize(18);
pdf.fromHTML(document.getElementById(doc),
margins.left, // x coord
margins.top,
{
// y coord
width: margins.width// max width of content on PDF
},function(dispose) {
headerFooterFormatting(pdf, pdf.internal.getNumberOfPages());
},
margins);
var iframe = document.createElement('iframe');
iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:650px; padding:20px;');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
};
It works 100% on Chrome but Im not sure about other browsers.
Try this solution.
<button id="generatePDF">Generate PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$( '#generatePDF' ).click( function()
{
var pdf = new jsPDF('a4');
pdf.text("Some text inside PDF", 10, 10);
$( '#docpdf' ).attr('src', pdf.output('datauristring'));
});
</script>
<iframe id="docpdf" style="background-color:#EEE; height:400px;">
PDF goes here
</iframe>
A wild guess here but I think this has to do with the fact that Iframes from other domains are protected.
Read into 'cross-domain policy', if it's the cause I'm quite sure you can't work around it very easy.
try
var source = window.document.getElementsByTagName(tagName)[0];
instead of
source = $('#frame')[0];

Add FontAwesome Icon in jsPdf

I am using jspdf.debug.js latest version.
FontAwesome icons used in a web page are not rendering in pdf.
I added a FontAwesome user icon in the page.Refer to the image.(Left one is HTML and pdf output is on right)
Below is my code snippet.
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.addFont('FontAwesome', 'FontAwesome', 'normal');
pdf.setFont('FontAwesome');
pdf.canvas.height = 72 * 11;
pdf.canvas.width = 72 * 8.5;
html2pdf(document.body, pdf, function(pdf){
var iframe = document.createElement('iframe');
iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:500px');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
});
jspdf does not support special symbols. Here is the gitHub issue.
See info in this answer.
I did in this way and all works with font Awesome 5...
Following this article i uploaded the fa-solid-900-normal.ttf at https://peckconsulting.s3.amazonaws.com/fontconverter/fontconverter.html
I got the js file and import it.
In Angular i did in this way
constructor() {
var callAddFont = function () {
this.addFileToVFS('fa-solid-900-normal.ttf', jsPDFfonts.fontawesome5_fa_solid_900);
this.addFont('fa-solid-900-normal.ttf', 'fa-solid-900', 'normal');
};
jsPDF.API.events.push(['addFonts', callAddFont])
}
where jsPDFfonts.fontawesome5_fa_solid_900 is the content of the file
Then during the print process for printing an icon i did in this way
pdf.setFont('fa-solid-900', 'normal');
pdf.setFontSize(10);
pdf.text('\uf6f0', 15, 15*index);
i printed directly the unicode of the icon

Using jspdf to save html page as pdf, saved pdf contains incomplete page content if browser is zoomed, Why?

I am using jspdf and html2canvas combination to save html page as pdf. A pdf copy of current page is saved the moment you click a button. The problem is, if you zoom in the page, and then click the button, the saved pdf contains incomplete portion of the current page. Most of the part not visible on page due to zooming, gets cut off in the saved pdf page. What is the solution?
Below is the js code being invoked upon click of save button-
var pdf = new jsPDF('l', 'pt', 'a4');
var source = $('#someId')[0];
var options = {
background : '#eee'
};
pdf.addHTML(source, options, function(){
pdf.save('abcd.pdf');
});
EDIT
Taking idea from Saurabh's approach, I tried quite a similar thing, but without writing code for any extra div element. Before saving to pdf I made the screen size of a fixed width, and after printing I brought back the width back to default normal. It is working fine for, if it fails, we can always fix the height of the screen too, so that it appears fine in generated pdf despite zooming. Below is the code used by me:-
var pdf = new jsPDF('l', 'pt', 'a4');
var source = $('#someId')[0];
var options = {
background : '#eee'
};
var width = source.clientWidth;
source.style.width = '1700px';
pdf.addHTML(source, options,
function(){
pdf.save('abcd.pdf');
source.style.width = width+'px';
});
Here is how I managed to get the full page pdf while the page is zoomed in using jsPDF's new .html() method. First, I force the page zoom level back to 100% before converting it to pdf. It's important to reset the scale in html2canvas option after that, otherwise it'll returns a blank page.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"
integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
crossorigin="anonymous"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<!-- html2canvas 1.0.0-alpha.11 or higher version is needed -->
<script>
function download() {
// Bring the page zoom level back to 100%
const scale = window.innerWidth / window.outerWidth;
if (scale != 1) {
document.body.style.zoom = scale;
}
let pdf = new jsPDF('p', 'pt', 'a4');
pdf.html(document.getElementById('idName'), {
html2canvas: {
scale: 1 // default is window.devicePixelRatio
},
callback: function () {
// pdf.save('test.pdf');
window.open(pdf.output('bloburl')); // to debug
}
});
}
</script>
Update: A better way is to adjust the html2canvas.scale according to the scale factor.
function download() {
let pWidth = pdf.internal.pageSize.width; // 595.28 is the width of a4
let srcWidth = document.getElementById('idName').scrollWidth;
let margin = 18; // narrow margin - 1.27 cm (36);
let scale = (pWidth - margin * 2) / srcWidth;
let pdf = new jsPDF('p', 'pt', 'a4');
pdf.html(document.getElementById('idName'), {
x: margin,
y: margin,
html2canvas: {
scale: scale,
},
callback: function () {
window.open(pdf.output('bloburl'));
}
});
}
I was going through the same problem,
To do this what I did is I made a copy of printing div and while clicking print button I attached div copy to my dom with margin-top:500px
After I got its image then I hide this copy of the div, and set margin-top:0px
I hope this will work for you.

convert web page to a pdf with styles

I want to convert a web page to PDF including all the styles I've added.
I've used jspdf.js and html2Canvas. But I got only a blur picture in PDF form.
I've searched for many JavaScript codes but didn't find a correct one.
Script I have written is:
function getPDF() {
html2canvas(document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL("Image/jpeg");
//window.open(img);
var doc = new jsPDF({
unit: 'px',
format: 'a4'
});
doc.addImage(img, 'JPEG', 0, 0, 440, 627);
doc.save("download");
}
});
}
Thank You!
There may be a few things that are contributing.
Your encoder options for the canvas.toDataURL are missing, so you're getting the defaults. The defaults may be creating a low quality image. Try this for the highest quality JPEG image:
var img = canvas.toDataURL("Image/jpeg", 1.0);
You might also try creating your jsPDF object with measurements, rather than pixels:
var pdf = new jsPDF("p", "mm", "a4"); // jsPDF(orientation, units, format)
And when you add the image, scale it to the dimensions of the page:
pdf.addImage(imgData, 'JPEG', 10, 10, 190, 277); // 190x277 mm # (10,10)mm
See if that gives you a better image quality.

How to export multiple html tables and multiple d3 generated graphs into a single pdf

Basically I have multiple tables that are generated in html (also the data may vary depends on how much data are in the database, so I want the tables on pdf to be scalable as well, meaning no fixed size.) In addition, I have a d3 generated graph too on the same page.
What I want to know is..is there any way to turn everything displayed on the page into a pdf like a screenshot? I know there is phantomJS but it requires you to install and deploy on the local environment, and our project won't allow it.. so is there any 3rd party libraries that I can import and use to export them into a single PDF?
Please help
Using SaveSvg.js
https://gist.github.com/enjoylife/0ae74717a29862c5d8c5
and using jspdf was able to make it work
d3.select("#save").on("click", function(){
var html = d3.select("svg")
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node().parentNode.innerHTML;
//console.log(html);
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html);
var img = '<img src="'+imgsrc+'">';
d3.select("#svgdataurl").html(img);
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d");
var image = new Image;
image.src = imgsrc;
image.onload = function() {
context.drawImage(image, 0, 0);
//save and serve it as an actual filename
binaryblob();
var a = document.createElement("a");
a.download = "sample.png";
a.href = canvas.toDataURL("image/png");
/* Added as png to jspdf */
var doc = new jsPDF();
doc.addImage( a.href, "png", 0,0);
doc.save("test.pdf");
var pngimg = '<img src="'+a.href+'">';
d3.select("#pngdataurl").html(pngimg);
a.click();
};
});
jspdf alignment and css is good
http://plnkr.co/edit/nNSvHL8MZcT6nNKg9CG9?p=preview

Categories

Resources