一种方法可能是在客户端浏览器中重新填充 html 页面呈现,以便完全按照您希望在 pdf 中打印的方式显示它(然后只需使用您刚刚在上面创建的函数),因此以组合的格式通过一系列垂直元素,如 h、p1、f、h、p2、f、h、p3、f 等(其中 h=header,p1 ... pn 是页面,f=footer)而不是包含只是 h, p1, p2, p3, ... , pn, f(现在这样)。
这意味着您可能可以访问 html 页面的源代码(因此它不仅仅是从互联网上获取的页面),因为如果它是外部资源,则页眉和页脚的尺寸可能会以编程方式构造为还填充与页面其他元素相关的空间(我认为这里的 flex / 垂直应用 / 或网格技术在呈现网页时)。
另一方面,如果要执行此方法,则内容拆分可能并不总是可能的(我在这里并没有考虑销毁表格或其他仅在使用滚动时可见的多页元素),但是渲染也可能会考虑页面的垂直显示(与桌面中的横向模式相反),以便重新绘制页面中的元素。这有时会使页脚和页眉可能更大,所以我不确定你为什么要通过这样做来花费最终打印页面的部分宝贵空间。 (解决方案可能是打开一个新窗口,从而以新格式重新呈现页面,甚至可能在现有页面之后,然后在关闭相应页面之前启动打印确认/或下载文件。)
另一种方法是更改函数,以便使用页面的虚拟渲染(不显示页面) - 通过对函数进行更改而不是在渲染本身中进行更改。
不过,第二种方法也存在一些挑战。最初,在声明变量 'var pdf' 时,它被创建为唯一的数据存储容器,然后为它分配构造函数( var pdf = new jsPDF('p','px'); )。但是,在下一步中,您将向其中添加 HTML 内容 (pdf.addHTML),它是单个元素,而不是多个实体。您应该更改函数以使其打印一个数组,您首先在其中根据所呈现页面的尺寸计算元素。
也许代码会变成这样:
var fullpage, onepage, headd, foott, edges, contentt, he, fo, c, pages;
fullpage = document.body.scrollHeight; // height of all html page (not just the visible content)
onepage = 1200; // height of each single page printed in pdf - in pixels
headd = document.getElementById("header");
he = headd.offsetHeight;
foott = document.getElementById("footer");
fo = foott.offsetHeight;
edges = he + fo;
contentt = onepage - edges; // height of content of each page printed
pages = [0]; // start to work with first page which obviously is there
fullpage -= onepage; // remove height of first printed page (containg both header and footer)
pdf.addHTML( // create first page of pdf file
htmlSource, 10, 10, {pagesplit: true, margin: {top: 10, right:
10, bottom: 10, left: 10, useFor: 'page'}},
function(dispose){
pdf.save('datapdf.pdf');
}); // this is your code
var i = 0; // start the counter
while(fullpage > 0) { // start adding header + footer to remaining pages
fullpage += edges; // if there is still a page 2...n we add edges, etc.
i++;
pages[i] = content(onepage) { // here you must insert the code for harvesting the n-st page content from your source code
return htmlSource;
}
function addPages(i) {
var eachpdf = "datapdf" + i + ".pdf";
// <= here goes again your code, with a small change
// pagesplit: false - instead of true, in order to speed the process, and also
// pdf.save(eachpdf); - instead of pdf.save('datapdf.pdf');
}
}
您尝试实现的是创建一个系列 he, p1, fo, he, p2, fo, he, p3, fo 等(其中 he=header, p1 ... pn 是上面的页面/命名 datapdfi / 和 fo=footer) 而不是仅包含 h、p1、p2、p3、...、pn、f 的系列。
这意味着您必须构造一个包含单独 pdf 页面的数组,如上面代码中所述。
我还没有为您创建用于分隔每个页面内容的代码(可能返回 htmlSource),但这与您的页面呈现方式密切相关。