vue页面生成PDF

通过 html2canvas 将 HTML 页面转换成图片,然后再通过 jspdf 将图片的 base64 生成为 pdf 文件。

1、安装依赖
// 将页面 html 转换成图片
npm install html2canvas --save  
// 将图片生成 pdf
npm install jspdf --save
2、封装方法
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

export default {
	methods: {
		getPdf() {
	      html2Canvas('需生成pdf节点', {
	        allowTaint: true,
	        useCORS: true,
	      }).then(function (canvas) {
	        let contentWidth = canvas.width
	        let contentHeight = canvas.height
	        let pageHeight = (contentWidth / 592.28) * 841.89
	        let leftHeight = contentHeight
	        let position = 0
	        // html页面生成的canvas在pdf中图片的宽高(本例为:横向a4纸[841.89,592.28],纵向需调换尺寸)
	        let imgWidth = 595.28
	        let imgHeight = (592.28 / contentWidth) * contentHeight
	        let pageData = canvas.toDataURL('image/jpeg', 1.0)
	        let PDF = new JsPDF('', 'pt', 'a4')
	        // 两个高度需要区分: 一个是html页面的实际高度,和生成pdf的页面高度
	        // 当内容未超过pdf一页显示的范围,无需分页
	        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
	            // 避免添加空白页
	            if (leftHeight > 0) {
	              PDF.addPage()
	            }
	          }
	        }
	        PDF.save(' 导出文件名' + '.pdf')
	      })
		},
	}
}
html2canvas 配置参数
名称默认描述
useCORSfalse是否尝试使用CORS从服务器加载图像
allowTaintfalse是否允许跨域图像。会污染画布,导致无法使用canvas.toDataURL 方法
proxynull代理将用于加载跨域图像的网址。如果保留为空,则不会加载跨域图像。
backgroundColor#ffffff画布背景色(如果未在DOM中指定)。设置null为透明
canvasnull现有canvas元素用作绘图的基础
foreignObjectRenderingfalse如果浏览器支持,是否使用ForeignObject渲染
imageTimeout15000加载图像的超时时间(以毫秒为单位)。设置0为禁用超时。
ignoreElements(element) => false谓词功能,可从渲染中删除匹配的元素。
removeContainertrue是否清除html2canvas临时创建的克隆DOM元素
scalewindow.devicePixelRatio用于渲染的比例。默认为浏览器设备像素比率。
JavaScript HTML renderer The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page. How does it work? The script renders the current page as a canvas image, by reading the DOM and the different styles applied to the elements. It does not require any rendering from the server, as the whole image is created on the clients browser. However, as it is heavily dependent on the browser, this library is not suitable to be used in nodejs. It doesn't magically circumvent any browser content policy restrictions either, so rendering cross-origin content will require a proxy to get the content to the same origin. The script is still in a very experimental state, so I don't recommend using it in a production environment nor start building applications with it yet, as there will be still major changes made. Browser compatibility The script should work fine on the following browsers: Firefox 3.5+ Google Chrome Opera 12+ IE9+ Safari 6+ As each CSS property needs to be manually built to be supported, there are a number of properties that are not yet supported. Usage Note! These instructions are for using the current dev version of 0.5, for the latest release version (0.4.1), checkout the old readme. To render an element with html2canvas, simply call: html2canvas(element[, options]); The function returns a Promise containing the <canvas> element. Simply add a promise fullfillment handler to the promise using then: html2canvas(document.body).then(function(canvas) { document.body.appendChild(canvas); }); Building The library uses grunt for building. Alternatively, you can download the latest build from here. Clone git repository with submodules: $ git clone --recursive git://github.com/niklasvh/html2canvas.git Install Grunt and uglifyjs: $ npm install -g grunt-cli uglify-js Run the full build process (including lint, qunit and webdriver tests): $ grunt Skip lint and tests and simply build from source: $ grunt build Running tests The library has two sets of tests. The first set is a number of qunit tests that check that different values parsed by browsers are correctly converted in html2canvas. To run these tests with grunt you'll need phantomjs. The other set of tests run Firefox, Chrome and Internet Explorer with webdriver. The selenium standalone server (runs on Java) is required for these tests and can be downloaded from here. They capture an actual screenshot from the test pages and compare the image to the screenshot created by html2canvas and calculate the percentage differences. These tests generally aren't expected to provide 100% matches, but while commiting changes, these should generally not go decrease from the baseline values. Start by downloading the dependencies: $ npm install Run qunit tests: $ grunt test Examples For more information and examples, please visit the homepage or try the test console. Contributing If you wish to contribute to the project, please send the pull requests to the develop branch. Before submitting any changes, try and test that the changes work with all the support browsers. If some CSS property isn't supported or is incomplete, please create appropriate tests for it as well before submitting any code changes.
Vue移动端生成PDF文件可以通过多种方式实现,主要依赖于一些第三方库和工具。以下是一个常见的实现步骤: ### 1. 使用jsPDFjsPDF一个流行的JavaScript库,可以用来生成PDF文件。你可以通过npm安装它: ```bash npm install jspdf --save ``` ### 2. 创建PDF生成逻辑 在你的Vue组件中,引入jsPDF并编写生成PDF的逻辑。例如: ```javascript import jsPDF from 'jspdf'; export default { methods: { generatePDF() { const doc = new jsPDF(); // 添加文本 doc.text('Hello world!', 10, 10); // 添加图片 const img = new Image(); img.src = 'path/to/image.png'; img.onload = () => { doc.addImage(img, 'PNG', 10, 20, 50, 50); doc.save('test.pdf'); }; } } } ``` ### 3. 处理HTML内容 如果你想将HTML内容转换为PDF,可以使用html2canvas和jsPDF结合使用。首先安装html2canvas: ```bash npm install html2canvas --save ``` 然后在组件中使用: ```javascript import jsPDF from 'jspdf'; import html2canvas from 'html2canvas'; export default { methods: { generatePDF() { const element = document.getElementById('content'); html2canvas(element).then(canvas => { const imgData = canvas.toDataURL('image/png'); const doc = new jsPDF(); const imgWidth = 210; const pageHeight = 295; const imgHeight = canvas.height * imgWidth / canvas.width; let heightLeft = imgHeight; doc.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight); heightLeft -= pageHeight; while (heightLeft >= 0) { doc.addPage(); doc.addImage(imgData, 'PNG', 0, heightLeft, imgWidth, imgHeight); heightLeft -= pageHeight; } doc.save('test.pdf'); }); } } } ``` ### 4. 处理移动端兼容性 在移动端生成PDF时,确保处理不同设备的兼容性问题。例如,调整图片大小和页面布局以适应不同屏幕尺寸。 ### 5. 优化用户体验 为了提高用户体验,可以在生成PDF时添加加载动画,并在生成完成后提示用户。 ```javascript methods: { generatePDF() { this.isLoading = true; const element = document.getElementById('content'); html2canvas(element).then(canvas => { const imgData = canvas.toDataURL('image/png'); const doc = new jsPDF(); const imgWidth = 210; const pageHeight = 295; const imgHeight = canvas.height * imgWidth / canvas.width; let heightLeft = imgHeight; doc.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight); heightLeft -= pageHeight; while (heightLeft >= 0) { doc.addPage(); doc.addImage(imgData, 'PNG', 0, heightLeft, imgWidth, imgHeight); heightLeft -= pageHeight; } doc.save('test.pdf'); this.isLoading = false; this.$toast('PDF生成成功'); }); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值