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

如何让html2canvas与jsPDF适配全屏幕实现响应式打印?

解决移动端/平板打印PDF时图片尺寸偏小、空白过多的问题

核心问题在于你当前代码使用了固定的图片宽高参数,没有适配不同设备的渲染差异,也没有结合A4纸的实际尺寸(纵向A4纸的pt单位宽度为595,高度为842)进行动态计算。以下是调整后的解决方案:

关键优化点

  • 基于设备像素比(devicePixelRatio)渲染canvas,避免移动端尺寸偏差和模糊
  • 动态计算PDF页面可用空间,按比例适配图片尺寸,填满页面同时预留文本空间
  • 文本位置不再固定,基于页面尺寸动态定位,保证一致性

完整调整代码

const handlePrint = async () => {
  const grid = document.getElementById("image-grid");
  // 用设备像素比渲染,适配移动端高清屏幕
  const scale = window.devicePixelRatio || 1;

  const canvas = await html2canvas(grid, {
    scale: scale,
    useCORS: true, // 若包含跨域图片需开启
    logging: false
  });

  const imgData = canvas.toDataURL("image/png");

  const pdf = new jsPDF({
    orientation: "portrait",
    unit: "pt",
    format: "a4",
  });

  // 获取PDF页面实际宽高
  const pageWidth = pdf.internal.pageSize.getWidth();
  const pageHeight = pdf.internal.pageSize.getHeight();
  const textBottomMargin = 40; // 文本距离页面底部的边距
  const imgSideMargin = 10; // 图片左右边距

  // 计算图片最大可用尺寸,预留文本空间
  const maxImgWidth = pageWidth - imgSideMargin * 2;
  const maxImgHeight = pageHeight - textBottomMargin - 40; // 额外预留空间避免文本重叠
  const imgAspectRatio = canvas.width / canvas.height;

  // 按比例计算最终图片尺寸,优先适配宽度,若高度超出则适配高度
  let finalImgWidth = maxImgWidth;
  let finalImgHeight = finalImgWidth / imgAspectRatio;

  if (finalImgHeight > maxImgHeight) {
    finalImgHeight = maxImgHeight;
    finalImgWidth = finalImgHeight * imgAspectRatio;
  }

  // 让图片在页面中居中
  const imgXPos = (pageWidth - finalImgWidth) / 2;
  const imgYPos = (pageHeight - finalImgHeight - textBottomMargin) / 2;

  pdf.addImage(imgData, "PNG", imgXPos, imgYPos, finalImgWidth, finalImgHeight);

  // 动态计算文本位置,左对齐和右对齐
  const text = "Special One";
  const secondtext = "Second One";
  pdf.setFont("Helvetica", "normal");
  pdf.setFontSize(18);

  const firstTextWidth = pdf.getTextWidth(text);
  const secondTextWidth = pdf.getTextWidth(secondtext);

  // 左文本距离左边缘20pt,右文本距离右边缘20pt
  pdf.text(text, 20, pageHeight - textBottomMargin);
  pdf.text(secondtext, pageWidth - 20 - secondTextWidth, pageHeight - textBottomMargin);

  pdf.save();
};

说明

  1. 设备像素比适配:移动端屏幕的devicePixelRatio通常大于1,用它作为html2canvas的scale参数,能保证渲染出的canvas清晰度足够,避免因缩放导致的尺寸偏差。
  2. 动态尺寸计算:不再固定addImage的宽高,而是根据A4页面的实际尺寸和图片的宽高比,自动计算出最合适的显示尺寸,确保图片填满可用空间且不超出页面。
  3. 文本位置优化:通过getTextWidth获取文本宽度,再结合页面宽度定位,避免固定坐标在不同设备上的错位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:04:59