HTML使用html2canvas支持跨域图片按A4尺寸分页导出PDF

本文介绍了一种使用html2canvas和jsPDF将网页内容转换为PDF的方法。通过抓取指定区域的网页内容,将其渲染为canvas图像,再将该图像转换为PDF格式进行保存。此过程涉及跨域图片处理、canvas尺寸调整及PDF多页生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

<script type="text/javascript" src="https://cdn.bootcss.com/html2canvas/0.4.1/html2canvas.js"></script>
	<script type="text/javascript">
		function AllAreaWord() {
			var times = $('#timeP').html();
			var name = $('.prese_navlidef').text();
			//var index = layer.load(0, {shade: false}); //0代表加载的风格,支持0-2
			html2canvas($('#capture'), {
				background : "#f7f7f7",
				useCORS : true,//解决图片跨越的问题
				taintTest : false,
				height : $("#capture").outerHeight(),
				onrendered : function(canvas) {

					var contentWidth = canvas.width;
					var contentHeight = canvas.height;

					//一页pdf显示html页面生成的canvas高度;
					var pageHeight = contentWidth / 592.28 * 841.89;
					//未生成pdf的html页面高度
					var leftHeight = contentHeight;
					//页面偏移
					var position = 0;
					//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
					var imgWidth = 595.28;
					var imgHeight = 592.28 / contentWidth * contentHeight;

					var pageData = canvas.toDataURL('image/png', 1.0);
					var pdf = new jsPDF('', 'pt', 'a4');

					//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
					//当内容未超过pdf一页显示的范围,无需分页
					if (leftHeight < pageHeight) {
						pdf.addImage(pageData, 'PNG', 0, 0, imgWidth, imgHeight);
					} else {
						while (leftHeight > 0) {
							pdf.addImage(pageData, 'PNG', 0, position,
									imgWidth, imgHeight)
							leftHeight -= pageHeight;
							position -= 841.89;
							//避免添加空白页
							if (leftHeight > 0) {
								pdf.addPage();
							}
						}
					}
					pdf.save(name + '检查.pdf');
					//layer.close(index) ;
					$("#T").remove();
					turnoff('none');
				}
			})
		}
	</script>

 

<think>我们使用jsPDFhtml2canvasHTML内容转换为PDF时,添加页码是一个常见的需求。以下是实现步骤和示例代码:###实现思路1.使用html2canvasHTML元素转换为canvas图像。2.使用jsPDF创建PDF文档,并将canvas图像添加到PDF中。3.在添加每一页内容后,在页脚位置绘制页码。###关键点-页码需要在每一页的固定位置(如底部居中)绘制。-由于内容可能越多页,我们需要在每次添加新页面时绘制页码。###示例代码以下是一个完整的示例,展示如何在每一页的底部居中位置添加页码:```javascriptimportjsPDFfrom'jspdf';importhtml2canvasfrom'html2canvas';//要转换的HTML元素constelement=document.getElementById('content-to-pdf');//设置PDF的页面尺寸(这里以A4为例)constpdf=newjsPDF({orientation:'portrait',unit:'mm',format:'a4'});//获取PDF页面的尺寸constpageWidth=pdf.internal.pageSize.getWidth();constpageHeight=pdf.internal.pageSize.getHeight();//设置边距和缩放比例constmargin=10;//边距constscale=2;//提高canvas的清晰度html2canvas(element,{scale:scale,useCORS:true,//如果图片需要设置allowTaint:true}).then(canvas=>{constimgData=canvas.toDataURL('image/jpeg',1.0);constimgWidth=pageWidth-margin*2;//减去左右边距constimgHeight=(canvas.height*imgWidth)/canvas.width;letheightLeft=imgHeight;letposition=margin;//初始位置//添加第一页pdf.addImage(imgData,'JPEG',margin,position,imgWidth,imgHeight);heightLeft-=pageHeight-margin*2;//减去第一页已经使用的高度(考虑上下边距)//当前页数letpageCount=1;//在第一页底部添加页码pdf.setFontSize(10);pdf.text(`Page${pageCount}of`,pageWidth/2,pageHeight-10,{align:'center'});//如果内容超过一页,则添加新页while(heightLeft>0){position=heightLeft-imgHeight;//注意:这里的位置计算需要调整pdf.addPage();pageCount++;pdf.addImage(imgData,'JPEG',margin,position,imgWidth,imgHeight);heightLeft-=pageHeight-margin*2;//在新页底部添加页码pdf.setFontSize(10);pdf.text(`Page${pageCount}of`,pageWidth/2,pageHeight-10,{align:'center'});}//更新总页数(在所有页面生成后,需要重新遍历设置总页数)//由于我们生成时还不知道总页数,所以上面先写为'PageXof',现在我们可以更新consttotalPages=pageCount;for(leti=1;i<=totalPages;i++){pdf.setPage(i);//将当前页的页码文本替换为“PageioftotalPages”pdf.text(`Page${i}of${totalPages}`,pageWidth/2,pageHeight-10,{align:'center'});}//保存PDFpdf.save('output.pdf');});```###注意事项1.**页码位置**:我们设置在页面底部向上10个单位(这里是毫米)的位置,居中显示。2.**总页数更新**:在生成所有页面后,我们遍历每一页,将页码文本更新为当前页和总页数(例如:Page1of3)。3.**清晰度**:通过设置html2canvas的scale参数提高生成图片的清晰度。4.**图片**:如果HTML中包含图片,需要设置`useCORS:true`,并且确保服务器允许。###优化-如果内容非常长,生成多页时,上述代码可能会因为循环添加页面而出现性能问题。可以考虑分块渲染。-页码的样式(字体、大小、颜色)可以根据需求调整。###相关问题1.如何在PDF中添加页眉和页脚?2.如何控制PDF分页,避免内容被截断?3.如何处理HTML中的样式(特别是CSS)在PDF中的显示问题?希望这个示例能帮助你实现PDF页码的添加。如果有更多问题,请随时提问。</think>### 使用 jsPDFhtml2canvas 导出 PDF 添加页码的实现方案 在导出 PDF 时添加页码需要以下步骤: #### 核心实现代码 ```javascript import jsPDF from 'jspdf'; import html2canvas from 'html2canvas'; async function exportPDFWithPageNumbers() { const element = document.getElementById('content-to-export'); const pdf = new jsPDF('p', 'mm', 'a4'); const pageWidth = pdf.internal.pageSize.getWidth(); const pageHeight = pdf.internal.pageSize.getHeight(); const canvas = await html2canvas(element, { scale: 2 }); const imgData = canvas.toDataURL('image/jpeg', 1.0); const imgProps = pdf.getImageProperties(imgData); const imgHeight = (imgProps.height * pageWidth) / imgProps.width; let position = 0; let pageCount = 1; // 添加首页内容 pdf.addImage(imgData, 'JPEG', 0, position, pageWidth, imgHeight); // 添加首页页码 pdf.setFontSize(10); pdf.text(`Page ${pageCount}`, pageWidth / 2, pageHeight - 10, { align: 'center' }); position -= pageHeight; // 处理分页 while (position > -imgHeight) { pdf.addPage(); pageCount++; pdf.addImage(imgData, 'JPEG', 0, position, pageWidth, imgHeight); // 添加每页页码 pdf.setFontSize(10); pdf.text(`Page ${pageCount}`, pageWidth / 2, pageHeight - 10, { align: 'center' }); position -= pageHeight; } pdf.save('document-with-pages.pdf'); } ``` #### 关键实现要点 1. **页码位置计算**: - 使用 `pdf.internal.pageSize.getHeight()` 获取页面高度 - 页码位置:`Y = 页面高度 - 10mm`(距底部10mm) - 水平居中:`X = 页面宽度 / 2` 2. **动态页码计数**: ```javascript let pageCount = 1; // 每添加新页时递增 pdf.addPage(); pageCount++; ``` 3. **页码样式控制**: ```javascript pdf.setFontSize(10); // 字体大小 pdf.text(`Page ${pageCount}`, x, y, { align: 'center' }); ``` 4. **页内容处理**: - 通过 `position` 变量跟踪内容偏移量 - 循环添加新页直到所有内容渲染完成 #### 优化建议 1. **自定义页码格式**: ```javascript // 示例:第X页/共Y页 const totalPages = pdf.internal.getNumberOfPages(); pdf.text(`第${pageCount}页/共${totalPages}页`, ...) ``` 2. **样式增强**: ```javascript pdf.setTextColor(100, 100, 100); // 灰色文字 pdf.setFont("helvetica", "normal"); // 字体类型 ``` 3. **防止内容覆盖**: - 在原始HTML中添加底部留白: ```css #content-to-export { padding-bottom: 30px; /* 避免内容被页码遮挡 */ } ``` #### 注意事项 1. **分页精度问题**: - 多页内容需要精确计算内容高度 - 建议使用 `scale: 2` 提高渲染精度 2. **性能优化**: - 复杂内容分页时考虑分段渲染 - 使用 `window.requestAnimationFrame` 防止UI阻塞 3. **浏览器兼容**: - 测试不同浏览器的canvas渲染差异 - 添加`useCORS: true`参数处理资源 ### 实现效果 最终生成的PDF将在每页底部中心位置显示页码,格式为 "Page 1"、"Page 2" 等,可根据需求自定义显示格式和样式。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值