You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript将长网页打印为单页PDF而不拆分多页

mtlnovel章节页单页PDF打印适配方案

需求

需要将mtlnovel站点的小说章节页面打印为单页PDF,避免自动拆分多页,示例页面:https://www.mtlnovel.com/pick-up-the-invincible-world-attributes-at-the-start/chapter-1-invincible-attribute-system/

原有实现及痛点

此前借助Chrome插件Stylus添加如下固定CSS规则,可实现将单章打印为单页PDF:

@media print {
  @page {
    size: 148.5mm 1891mm;
  }
} 

但不同章节页面高度不一致,每次都需要手动修改高度参数,操作繁琐。

动态适配实现方法

高度计算逻辑

可通过Chrome插件Custom JavaScript for Websites 2运行以下代码,计算得到页面的毫米高度:

height = ((document.documentElement.offsetHeight * 0.2733)).toFixed(0);

最终可用代码

最终实现的脚本如下,按下键盘左方向键即可触发自动调整打印尺寸:

(function() {
  document.addEventListener('keydown', (e) => {
    if (e.keyCode === 37) {
      autoresize();
    }
  });
})();

function autoresize() {
  let height = ((document.documentElement.offsetHeight * 0.2733)).toFixed(0);
  var dst2 = document.getElementById("style2");
  if (dst2 != null) {
    document.getElementById("style2").remove();
  }
  var style = document.createElement('style');
  style.type = 'text/css';
  style.id = 'style2';
  style.innerHTML = '@media print {@page {size: 148.5mm ' + height + 'mm;}}';
  if (document.body != null) {
    document.body.appendChild(style);
  }
}

内容的提问来源于stack exchange,提问作者rarksoca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:15:03