本文介绍了带有html2Canvas的多页pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用react-typescript,并且在此ref的帮助下,我已经成功地从html页面创建了PDF文件从React组件生成PDF文件

I am using react-typescript and I have successfully created a PDF file from an html page with the help of this refGenerating a PDF file from React Components

但是,如果我们要创建包含多个页面的PDF,该怎么办?尺寸为a4的页面,所有面均应留有适当的边距,在每个新页面中均应应用边距.

But if we want to create a PDF with multiple pages then what to do?with a4 size page with appropriate margins at all sides and in each new page that margin should be applied.

这是我的代码.

private printDocument() {
        const input = document.getElementById("pdf");

        html2canvas(input)
            .then((canvas) => {
                const pdf = new jsPDF("p", "px", "a4");
                pdf.addHTML(input, 0, 0, {
                    pagesplit: true,
                    background: "#ffffff",
                }, () => {
                    pdf.save("download.pdf");
                });
            });
    }

请帮助我它的银色.预先谢谢你

please help me its argent.Thank you in advance

推荐答案

我尝试使用jsPDF解决此问题,但未成功. jsPDF管理将内容拆分为页面的方式对我来说还不清楚.因此,我决定使用另一个令人惊奇的js库pdfMake.我在以下问题中得到了这些信息:使用JavaScript生成PDF文件

I tried to use jsPDF to workaround this problem, but i did not succeed. The way that jsPDF manage the content to split in paged are not clear to me.So i decided to use pdfMake, another amazing js library.I got these infos in this question: Generating PDF files with JavaScript

在提及的问题中(从React Components生成PDF文件),最好的答案就是处理分页的好方法.您为每个页面制作一个div.但就我而言,我的内容可以动态增加您的垂直大小,因此我无法固定div的垂直大小.所以,我确实是这样的:

In the question that you metioned (Generating a PDF file from React Components), the best answer sugest a good way to handle the pagination. You make a div for each page. But in my case, my content can dinamically increase your vertical size, so i can't fix the div's vertical sizes.So, i did like this:

printDocument() {
  const divs = document.getElementsByClassName('example');
  const newList = [].slice.call(inputs);
  var contentArray = []
  var docDefinition = {
            pageSize: {width: 800, height: 1173},
            content: [
                {
                    text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Confectum ponit legam, perferendis nomine miserum, animi. Moveat nesciunt triari naturam.'
                }
            ]

        }

  Promise.map(newList, async (element, index) => {
            let canvas = await html2canvas(element);
            const imgData = await canvas.toDataURL('image/png');
            // console.log("imgData URL => ", imgData)
            // margin horizontal -40 = removing white spaces
            return contentArray[`${index}`] = [{ image: imgData, width: canvas.width, height: canvas.height, margin: [-40, 0] }, {
                text: ` ${index} - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Confectum ponit legam, perferendis nomine miserum, animi.`
}];

        }).then(
            () => ( docDefinition.content.push(contentArray))
        ).then(
            () => {
                console.log("... starting download ...")
                pdfMake.createPdf(docDefinition).download('examplePdf.pdf')
            }
        )
}

// In your react's component constructor ...

constructor(props) {
        super(props);
        this.printDocument = this.printDocument.bind(this)
}

// the imports below ...
import Promise from 'bluebird';
import html2canvas from 'html2canvas';
import pdfMake from 'pdfmake/build/pdfmake.js';
import pdfFonts from "pdfmake/build/vfs_fonts.js";
pdfMake.vfs = pdfFonts.pdfMake.vfs;

// i'm using these middlewares
import promise from 'redux-promise'
import multi from 'redux-multi'
import thunk from 'redux-thunk'
<div>
  The approach here is: a div it's not a page. Because if the image generated by the canvas element it's bigger than the page vertical size, we'll need to control the pagination by ourselves. So, we broke our content in small elements to the pdf generator handle the pagination to us. This way we garantee that the pagination will occurs without cuts.
  <div className="example" style={{ backgroundColor: '#ffffff', maxWidth: '800px', maxHeight: '1173px', borderStyle: 'groove', borderColor: 'red', margin: '0px' }} >

  // any content or component here, we need maxHeight to be sure that the div's height size it's not bigger than the your PDF doc's height dimension, else your div may never be rendered inside it.

  </div>
  <div className="example" style={{ backgroundColor: '#ffffff', maxWidth: '800px', maxHeight: '1173px', borderStyle: 'groove', borderColor: 'red', margin: '0px' }} >

  // any content or component here, we need maxHeight to be sure that the div's height size it's not bigger than the your PDF doc's height dimension, else your div may never be rendered inside it.

  </div>
  <div className="example" style={{ backgroundColor: '#ffffff', maxWidth: '800px', maxHeight: '1173px', borderStyle: 'groove', borderColor: 'red', margin: '0px' }} >

  // any content or component here, we need maxHeight to be sure that the div's height size it's not bigger than the your PDF doc's height dimension, else your div may never be rendered inside it.

  </div>

</div>

<div>
 <button onClick={this.printDocument}> print using PDFMake  </button>
</div>

使用bluebird的Promise.map和async/await资源,我们可以确保等到画布上所有图像的生成结束.此过程可能需要一段时间,具体取决于图像的大小.

Using the Promise.map by bluebird with the async/await resources, we can ensure that we'll wait till the end of generation of all images from canvas. This process can take a while depending of your image's size.

http://bluebirdjs.com/docs/api/promise.map.html

看看pdfMake的github: https://github.com/bpampuch/pdfmake

Take a look at pdfMake's github:https://github.com/bpampuch/pdfmake

他的操场上有出色的范例以及操作方法: http://pdfmake.org/playground.html

And his playground with excelent examples and how tos:http://pdfmake.org/playground.html

我仍将尝试升级此方法以解决分页问题,​​但这是解决问题的最快方法,希望对某人有用.

I'll still trying to upgrade this way to solve this problem with the pagination, but it was the quickest way that i solved the problem and i hope to be useful for somebody.

这篇关于带有html2Canvas的多页pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:12