Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsPDF addHTML exporting low quality image to PDF

Simple question searching from last 2 days but didnt find solution i am converting html to pdf using this addHTML api of jsPDF

$('#loadPdf').on('click', function() {
        var pdf = new jsPDF('p', 'in', 'a4');
        pdf.addHTML($('#complete')[0], function() {
            pdf.save('new.pdf');
            pdf.output('datauri');
        });
    });

this is producing blur image pdf the text is showing blurry. I searched a lot find some links (share below) but didn't get answer.

html2canvas-generates-blurry-images

addHTML image quality

jspdf and addHTML / blurry font

is there any way available to get high quality image pdf. If i don't use addHTML api and use any other then image is not displaying in pdf. help please

like image 659
Mohammad Faizan khan Avatar asked Mar 20 '15 12:03

Mohammad Faizan khan


3 Answers

Try with this: html2canvas + jspDF.js
My pdf quality issue got solved with this

function createPDFObject() {
  html2canvas(document.getElementById("main"), {
   onrendered:function(canvas) {

  var contentWidth = canvas.width;
  var contentHeight = canvas.height;

  //One page pdf shows the height of canvas generated by html page;
  var pageHeight = contentWidth / 592.28 * 841.89;
  //html page height without pdf generation
  var leftHeight = contentHeight;
  //Page offset
  var position = 0;
  //a4 paper size [595.28841.89], width and height of image in pdf of canvas generated by html page
  var imgWidth = 595.28; 
  var imgHeight = 592.28/contentWidth * contentHeight;

  //Return picture dataURL, parameters: picture format and sharpness (0-1)
  var pageData = canvas.toDataURL('image/jpeg', 1.0);

  //Direction is vertical by default, dimension ponits, format A4 [595.28841.89]
  var pdf = new jsPDF('', 'pt', 'a4');
  
  //There are two heights to distinguish, one is the actual height of the html page, and the height of the generated pdf page (841.89)
  //When the content does not exceed the display range of one page of pdf, paging is not required
  if (leftHeight < pageHeight) {
      pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
  } else {
      while(leftHeight > 0) {
          pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
          leftHeight -= pageHeight;
          position -= 841.89;
          //Avoid adding blank pages
          if(leftHeight > 0) {
            pdf.addPage();
          }
      }
  }
   pdf.save('stone.pdf');

  }
 });
like image 105
Jeny Avatar answered Nov 02 '22 17:11

Jeny


It looks like that many are still using pdf.addHTML() and have the same low quality issue. pdf.addHTML() is actually deprecated now. The new vector-supporting API, pdf.html(), works much better. See their sample for yourself. Here is the working code using jsPDF and html2canvas 1.0.0-alpha.11 :

<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>
<script>
    function download() {
        let pdf = new jsPDF('l', 'pt', 'a4');
        pdf.html(document.getElementById('id'), {
            callback: function () {
                //pdf.save('test.pdf');
                window.open(pdf.output('bloburl')); // to debug
            }
        });
    }
</script>
like image 41
Weihui Guo Avatar answered Nov 02 '22 16:11

Weihui Guo


This issue is related to scaling. In my case i have doubled the height and width at run time in angular application. This had resolve my issue. You can try also with increasing height and weight. It will resolve the issue.

import * as jsPDF from 'jspdf';
import * as html2canvas from "html2canvas";
import * as $ from 'jquery';
export class Print {
    static exportTwo(elem: any,progress:any) {
        var canvasToImage = function (canvas: any) {
            var img = new Image();
            var dataURL = canvas.toDataURL('image/png', 0.92);
            img.src = dataURL;
            return img;
        };
        var canvasShiftImage = function (oldCanvas: any, shiftAmt: any) {
            shiftAmt = parseInt(shiftAmt) || 0;
            if (!shiftAmt) { return oldCanvas; }

            var newCanvas = document.createElement('canvas');
            newCanvas.height = oldCanvas.height - shiftAmt;
            newCanvas.width = oldCanvas.width;
            var ctx = newCanvas.getContext('2d');
            ctx['imageSmoothingEnabled'] = false; /* standard */
            ctx['mozImageSmoothingEnabled'] = false; // Firefox 
            ctx['oImageSmoothingEnabled'] = false; // Opera /
            ctx['webkitImageSmoothingEnabled'] = false; // Safari /
            ctx['msImageSmoothingEnabled'] = false; // IE */
            //ctx.fillStyle = "#";
            var img = canvasToImage(oldCanvas);
            ctx.drawImage(img, 0, shiftAmt, img.width, img.height, 0, 0, img.width, img.height);

            return newCanvas;
        };


        var canvasToImageSuccess = function (canvas: any) {
            var l = {
                orientation: 'p',
                unit: 'mm',
                format: 'a4',
                compress: true,
                fontSize: 40,
                lineHeight: 1,
                autoSize: false,
                printHeaders: true
            };
            var pdf = new jsPDF(l),
                pdfInternals = pdf.internal,
                pdfPageSize = pdfInternals.pageSize,
                pdfScaleFactor = pdfInternals.scaleFactor,
                pdfPageWidth = pdfPageSize.width,
                pdfPageHeight = pdfPageSize.height,
                totalPdfHeight = 0,
                htmlPageHeight = canvas.height,
                htmlScaleFactor = canvas.width / (pdfPageWidth * pdfScaleFactor),
                safetyNet = 0;
            while (totalPdfHeight < htmlPageHeight && safetyNet < 15) {
                var newCanvas = canvasShiftImage(canvas, totalPdfHeight);
                pdf.addImage(newCanvas, 'PNG', 0, 0, pdfPageWidth, pdfPageHeight, 'NONE', 'SLOW');

                totalPdfHeight += (pdfPageHeight * pdfScaleFactor * htmlScaleFactor);

                if (totalPdfHeight < (htmlPageHeight)) {
                    pdf.addPage();
                }
                safetyNet++;
            }
            var source = $('#print')[0];
            pdf.save('invoice.pdf');
        };

        var bigCanvas = $("<div>").appendTo($('#print'));  // This will be the 2x sized canvas we're going to render
        var scaledElement = $('#print').clone()
            .css({
                'margin': '2%',
                'padding': '1%',
                'transform': 'scale(2,2)',
                'transform-origin': '0 0',
            })
            .appendTo(bigCanvas);

        var oldWidth = scaledElement.width();
        var oldHeight = scaledElement.height();

        var newWidth = oldWidth * 2;
        var newHeight = oldHeight * 2;

        bigCanvas.css({
            'width': newWidth+200,
            'height': newHeight+200,
            'margin': '2%',
            'padding': '1%',
        })

        html2canvas(bigCanvas[0]).then((canvas: any) => {
            canvasToImageSuccess(canvas);
            bigCanvas.remove();
            progress.done();
        });
    }
}
like image 1
Dhanik Lal Sahni Avatar answered Nov 02 '22 16:11

Dhanik Lal Sahni