JSPDF-如何将具有不同页面大小(高度和宽度)的多个图像导出到单个pdf文件

时间:2018-09-12 11:58:46

标签: javascript jquery jspdf

我有多张不同大小(高度和宽度)的图像,需要使用jspdf转换为PDF,但是我很难使用int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2}; int[][] winningPositions = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}}; for (int[] winningPosition : winningPositions) { System.out.println("RST " + gameState[winningPosition[0]] ); if (gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]] && gameState[winningPosition[0]] != 2) { // Somone has won! gameActive = false; String winner = ""; if (activePlayer == 1) { winner = "Yellow"; } else { winner = "Red"; } } 函数来做到这一点。 可以将具有不同页面尺寸的图像导出到单个pdf吗?

1 个答案:

答案 0 :(得分:0)

我实际上能够使用以添加具有不同图象尺寸的多个页面addPage([imgWidth, imgHeight])除第一页,它由下式定义new jsPDF('l', 'pt', 'a4')

可以使用.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>

一种更好但更复杂的方法是使用固定页面格式并计算图像大小和纵横比,然后相应地设置参数(并在需要时旋转图像),以便图像可以适合< / strong>纸张,在这种情况下为a4。可以是pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, 'NONE');pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, -90);

有关代码示例,请参见我的answer to this question