我正在从事一个涉及将 PDF 手册转换为 html 的项目。 我试图在打印时保留 PDF 的价值,同时在不受页面概念约束的设备上为它们提供更好的用户界面。 我遇到的问题是这些手册有一个目录,其中包含每个章节开始的页码。 在设备上查看时,该列表只是页内锚链接,但在打印时我想获取元素的页码(例如第 3 章的标题位于哪一页)并将其添加到表格中内容,特别是在应用像
page-break-after:avoid;
这样的打印样式之后。
举个例子,我想知道在打印时如何将页码准确添加到以下维基百科文章的目录中。 http://en.wikipedia.org/wiki/Character_mask
编辑: 我的想法是使用打印样式表在打印时添加页码:
@page {
@bottom {
content: "Page " counter(page) " of " counter(pages)
}
}
然后使用javascript使用matchMedia/onbeforeprint(http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/)检测打印,然后从内容中获取页码,但我不确定如何找到动态添加的内容。 这可能吗?还有其他解决办法吗?
这里有一个技巧:
@media screen
模式下无用)const HEIGHT = ...; // in pixels; use toPx below to convert from physical units
const element = ...; // the element you want; adapt this code to loop over e.g. <h1>s
// h/t: https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/
const mql = matchMedia('print');
mql.addListener(m => {
if (!m.matches) return; // not in @media print mode
const page = Math.floor(element.getBoundingClientRect().top / HEIGHT) + 1
console.log(element, 'is on page', page);
})
function toPx(unit) {
// create temporary element, give it a font size of 1 of the unit, and add it to the body
const elem = document.createElement('test');
elem.style.fontSize = '1' + unit;
document.body.appendChild(elem);
// get the computed font size (in px) and remove the element from the body
const value = +getComputedStyle(elem).fontSize.slice(0, -2);
document.body.removeChild(elem);
return value;
}