programing

jsPDF 라이브러리를 올바르게 사용하는 방법

codeshow 2023. 8. 20. 12:57
반응형

jsPDF 라이브러리를 올바르게 사용하는 방법

저는 제 div 중 일부를 PDF로 변환하고 싶고 jsPDF 라이브러리를 시도했지만 성공하지 못했습니다.도서관을 작동시키기 위해 무엇을 가져와야 하는지 이해할 수가 없는 것 같습니다.저는 그 예들을 살펴보았지만 아직도 그것을 이해할 수 없습니다.다음을 시도해 보았습니다.

<script type="text/javascript" src="js/jspdf.min.js"></script>

jQuery 이후 및 다음:

$("#html2pdf").on('click', function(){
    var doc = new jsPDF();
    doc.fromHTML($('body').get(0), 15, 15, {
        'width': 170
    });
    console.log(doc);
});

테스트용이지만 다음과 같은 정보를 받습니다.

"Cannot read property '#smdadminbar' of undefined"

어디에#smdadminbar몸에서 첫 번째 디브입니다.

당신은 html에서 pdf를 다음과 같이 사용할 수 있습니다.

1단계: 헤더에 다음 스크립트 추가

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>

또는 로컬로 다운로드합니다.

2단계: HTML 스크립트를 추가하여 jsPDF 코드 실행

이것을 사용자 지정하여 식별자를 전달하거나 #content를 필요한 식별자로 변경합니다.

 <script>
    function demoFromHTML() {
        var pdf = new jsPDF('p', 'pt', 'letter');
        // source can be HTML-formatted string, or a reference
        // to an actual DOM element from which the text will be scraped.
        source = $('#content')[0];

        // we support special element handlers. Register them with jQuery-style 
        // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
        // There is no support for any other type of selectors 
        // (class, of compound) at this time.
        specialElementHandlers = {
            // element with id of "bypass" - jQuery style selector
            '#bypassme': function (element, renderer) {
                // true = "handled elsewhere, bypass text extraction"
                return true
            }
        };
        margins = {
            top: 80,
            bottom: 60,
            left: 40,
            width: 522
        };
        // all coords and widths are in jsPDF instance's declared units
        // 'inches' in this case
        pdf.fromHTML(
            source, // HTML string or DOM elem ref.
            margins.left, // x coord
            margins.top, { // y coord
                'width': margins.width, // max width of content on PDF
                'elementHandlers': specialElementHandlers
            },

            function (dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }, margins
        );
    }
</script>

3단계: 본문 내용 추가

<a href="javascript:demoFromHTML()" class="button">Run Code</a>
<div id="content">
    <h1>  
        We support special element handlers. Register them with jQuery-style.
    </h1>
</div>

원본 자습서 참조

작동 중인 피들 보기

이 링크는 jspdf.min.js만 필요합니다.

모든 것이 들어 있습니다.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>

최신 버전(1.5.3)에 따르면 다음과 같은 것은 없습니다.fromHTML()더 이상 방법이 없습니다.대신 jsPDF HTML 플러그인을 사용해야 합니다. 자세한 내용은 https://rawgit.com/MrRio/jsPDF/master/docs/module-html.html #~http://# 를 참조하십시오.

제대로 작동하려면 html2dll 라이브러리도 추가해야 합니다. https://github.com/niklasvh/html2canvas

JS(API 문서에서):

var doc = new jsPDF();   

doc.html(document.body, {
   callback: function (doc) {
     doc.save();
   }
});

DOM 요소를 참조하는 대신 HTML 문자열을 제공할 수도 있습니다.

이것이 마침내 저에게 도움이 되었습니다(그리고 처분을 유발합니다).

function onClick() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  pdf.canvas.height = 72 * 11;
  pdf.canvas.width = 72 * 8.5;

  pdf.fromHTML(document.body);

  pdf.save('test.pdf');
};

var element = document.getElementById("clickbind");
element.addEventListener("click", onClick);
<h1>Dsdas</h1>

<a id="clickbind" href="#">Click</a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>

그리고 녹아웃의 사람들을 위하여.JS 성향, 약간 구속력 있음:

ko.bindingHandlers.generatePDF = {
    init: function(element) {

        function onClick() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            pdf.canvas.height = 72 * 11;
            pdf.canvas.width = 72 * 8.5;

            pdf.fromHTML(document.body);

            pdf.save('test.pdf');                    
        };

        element.addEventListener("click", onClick);
    }
};

vuejs에서 어떻게 적용할 수 있습니까?

function onClick() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  pdf.canvas.height = 72 * 11;
  pdf.canvas.width = 72 * 8.5;

  pdf.fromHTML(document.body);

  pdf.save('test.pdf');
};

var element = document.getElementById("clickbind");
element.addEventListener("click", onClick);
<h1>Dsdas</h1>

<a id="clickbind" href="#">Click</a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>

당신도 jspdf를 사용해야 하지 않나요?플러그인_backets.js 라이브러리에서?기본 라이브러리(jspdf.js) 외에도 "특수 작업"(예: jspdf)을 위해 다른 라이브러리를 사용해야 합니다.이미지 사용을 위한 plugin.addimage.js).https://github.com/MrRio/jsPDF 을 확인하십시오.

먼저 핸들러를 생성해야 합니다.

var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;
    }
};

클릭 이벤트에 이 코드를 기록합니다.

doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
    'elementHandlers': specialElementHandlers
        });

var pdfOutput = doc.output();
            console.log(">>>"+pdfOutput );

문서 변수를 이미 선언했다고 가정합니다.그런 다음 파일 플러그인을 사용하여 이 PDF 파일을 저장합니다.

언급URL : https://stackoverflow.com/questions/16858954/how-to-properly-use-jspdf-library

반응형