Javascript jsPDF addHTML将低质量图像导出为PDF

Javascript jsPDF addHTML将低质量图像导出为PDF,javascript,pdf,jspdf,Javascript,Pdf,Jspdf,过去2天的简单问题搜索,但未找到解决方案 我正在使用jsPDF的addHTML api将html转换为pdf $('#loadPdf').on('click', function() { var pdf = new jsPDF('p', 'in', 'a4'); pdf.addHTML($('#complete')[0], function() { pdf.save('new.pdf'); pdf.output('d

过去2天的简单问题搜索,但未找到解决方案 我正在使用jsPDF的addHTML api将html转换为pdf

$('#loadPdf').on('click', function() {
        var pdf = new jsPDF('p', 'in', 'a4');
        pdf.addHTML($('#complete')[0], function() {
            pdf.save('new.pdf');
            pdf.output('datauri');
        });
    });
这是产生模糊图像的pdf文本显示模糊。我搜索了很多,找到了一些链接(在下面分享),但没有得到答案


是否有任何方法可以获得高质量的图像pdf。若我并没有使用AddHTMLAPI和任何其他api,那个么图像不会以pdf格式显示。帮助请查看此解决方案:

发件人:


某品牌
  • 伪造页面内容
  • 酷导出测试页面! Lorem ipsum dolor sit amet,是一位杰出的献身者。刚从老鼠身上取下的元素。根据康努比亚·诺斯特拉(conubia nostra)和希梅纳奥斯(inceptos himenaeos)的规定,社会责任和责任等级为:。这是一辆汽车。在《老街日报》中,康莫多·普莱克托斯(commodo Placelat lectus)。Sed ac ullamcorper直径。库拉比图尔是利奥。非口述马萨。对价和对价

    出口1 出口2

    又一个头球! Lorem ipsum dolor sit amet,是一位杰出的献身者。刚从老鼠身上取下的元素

    小组标题 苹果 香蕉 胡萝卜 甜甜圈 炸薯条 葡萄 火腿 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 100% 同侧阴唇 0.2245 $1.25 1231235 asdf 11/11/12 好的,这可能是足够的数据了 最后用一些lorem ipsum来结束

    这是一个页脚
    这很好用

              var ctx = onePageCanvas.getContext('2d');
              //set the image quality
                ctx.webkitImageSmoothingEnabled = true;
                ctx.mozImageSmoothingEnabled = true;
                ctx.imageSmoothingEnabled = true;
                ctx.imageSmoothingQuality = "high";
    
                ctx.drawImage(srcImg,0,0); //this gives good img quality 
    
                var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0); //set png image with quality
    
                var width         = onePageCanvas.width;
                var height        = onePageCanvas.height;
    
               pdf.addImage(canvasDataURL, 'PNG', 10, 10, (width*.62), (height*.62),undefined,'FAST'); //addimage to jspdf
    

    我从这次讨论中找到了答案: 并以这种方式实施,适用于我的用例:

        var A4_width = 595; //pixels
        var A4_height = 842; //pixels
        var ratio = 2; // scale for higher image's dpi
    
        var oldCanvas = document.createElement('canvas');
        oldCanvas.width = A4_width;
        oldCanvas.height = A4_height;
        var oldContext = oldCanvas.getContext('2d');
        var oldImg = new Image();
        oldImg.src = oldCanvas.toDataURL();
        oldContext.drawImage(oldImg, 0, 0, A4_width, A4_height);
    
        var newImg = new Image();
        newImg.onload = function () {
            var newCanvas = document.createElement('canvas');
            newCanvas.width = A4_width * ratio;
            newCanvas.height = A4_height * ratio;
            var newContext = newCanvas.getContext('2d');
    
            // Scale and draw the source image to the canvas
            newContext.drawImage(newImg, 0, 0, A4_width * ratio, A4_height * ratio);
            newImg.src = newCanvas.toDataURL();
            var pdfDoc = new jsPDF({
                unit: 'mm'
            });
            pdfDoc.addImage(newImg, 'png', 0, 0, 210, 297); // imageData, format, x, y, w, h
            pdfDoc.save('testFile.pdf'); //save file
            newImg.onload = undefined; // kill the func
        }
        newImg.src = oldImg.src; //set source to the old image
    

    这个问题与缩放有关。在我的例子中,在角度应用程序中,我在运行时将高度和宽度增加了一倍。这解决了我的问题。你也可以尝试增加身高和体重。它将解决这个问题

    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();
            });
        }
    }
    
    从“jsPDF”导入*为jsPDF;
    从“html2canvas”导入*作为html2canvas;
    从“jquery”导入*为$;
    导出类打印{
    静态导出2(元素:任意,进度:任意){
    var canvasToImage=函数(画布:任意){
    var img=新图像();
    var dataURL=canvas.toDataURL('image/png',0.92);
    img.src=数据URL;
    返回img;
    };
    瓦坎瓦
    
    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();
            });
        }
    }
    
    <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>
    
    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');