簡體   English   中英

JSPDF-如何將具有不同頁面大小(高度和寬度)的多個圖像導出到單個pdf文件

[英]JSPDF - How to export multiple images with various page size (height & width) to a single pdf file

我有多個大小(高度和寬度)不同的圖像,需要使用jspdf轉換為PDF,但是我很難使用addPage()函數來做到這一點。 是否可以將具有不同頁面大小的圖像導出到單個pdf?

實際上addPage([imgWidth, imgHeight])除了第一頁是由new jsPDF('l', 'pt', 'a4')定義的,我實際上可以使用addPage([imgWidth, imgHeight])添加具有不同圖像大小的多個頁面。

可以使用.deletePage(1)刪除空白的第一頁。 您也可以在首頁上添加一些文本。

<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 exportPdf(urls) {
        let pdf = new jsPDF('l', 'pt', 'a4');
        pdf.text(20, 20, 'Some text here');

        for (let i = 0; i < urls.length; i++) {
            let img = new Image();
            img.src = urls[i];
            img.onload = function () {
                const imgWidth = this.width;
                const imgHeight = this.height;
                const imgRatio = imgWidth / imgHeight;
                if (i >= 0) {
                    if (imgRatio > 0) {
                        pdf.addPage([imgWidth, imgHeight]);
                    }
                    else {
                        pdf.addPage([imgWidth, imgHeight], 'p');
                    }
                }                
                pdf.setPage(i + 2);
                pdf.addImage(img, 'JPEG', 0, 0, imgWidth, imgHeight, null, 'NONE');

                if (i == urls.length - 1) {
                    pdf.save('Photos.pdf');
                }
            }
        }
    }
</script>

一種更好但更復雜的方法是使用固定頁面格式並計算圖像尺寸和長寬比,然后相應地設置參數(並在需要時旋轉圖像),以使圖像適合紙張,即a4案件。 它可以是pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, 'NONE'); pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, -90);

有關代碼示例,請參見我對這個問題的回答

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM