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

如何使用Tailwind修改react-pdf中PDF显示的宽高?

使用Tailwind让react-pdf的PDF适配指定组件尺寸

react-pdf的Page组件默认会按PDF原始尺寸渲染,直接加Tailwind宽高类可能不生效,你可以试试下面几种方案:

方案1:外层容器约束(推荐)

用一个外层div设置目标组件的尺寸,让Page组件占满容器,同时通过scale属性调整适配比例:

<>
  {/* 外层div设置和目标组件一致的尺寸,添加overflow-hidden防止内容溢出 */}
  <div className="h-24 w-10 border-solid border-2 border-sky-500 overflow-hidden">
    <Document file={pdfUrl}>
      <Page
        pageNumber={1}
        className="w-full h-full"
        scale={0.2} // 根据你的PDF实际尺寸调整数值,直到适配容器
      />
    </Document>
  </div>
</>

方案2:直接设置Page的宽高属性

如果你清楚目标尺寸对应的像素值(比如Tailwind的w-10对应32px,h-24对应96px),可以直接给Page指定宽高:

<>
  <Document file={pdfUrl}>
    <Page
      pageNumber={1}
      width={32} // 对应Tailwind w-10
      height={96} // 对应Tailwind h-24
      className="border-solid border-2 border-sky-500"
    />
  </Document>
</>

方案3:动态计算适配比例(自动适配)

如果需要自动适配容器比例,避免手动调整scale,可以通过useRef和useEffect动态计算:

import { useRef, useEffect, useState } from 'react';
import { Document, Page } from 'react-pdf';

const PdfViewer = ({ pdfUrl }) => {
  const containerRef = useRef(null);
  const [scale, setScale] = useState(1);

  useEffect(() => {
    if (!containerRef.current) return;
    const { width, height } = containerRef.current.getBoundingClientRect();
    // 这里替换成你的PDF原始宽高比,比如A4纸是841/592≈1.42
    const pdfRatio = 841 / 592;
    const containerRatio = width / height;

    // 计算合适的缩放比例,让PDF完整适配容器且不变形
    const newScale = containerRatio > pdfRatio 
      ? height / (841 / pdfRatio) 
      : width / 841;
    setScale(newScale);
  }, []);

  return (
    <div ref={containerRef} className="h-24 w-10 border-solid border-2 border-sky-500 overflow-hidden">
      <Document file={pdfUrl}>
        <Page pageNumber={1} scale={scale} className="w-full h-full" />
      </Document>
    </div>
  );
};

注意事项

  • overflow-hidden必须加,否则PDF内容可能会超出容器范围
  • 如果你需要保持PDF的宽高比,优先用方案1或3,避免直接拉伸变形
  • scale的数值需要根据你的PDF实际尺寸调整,方案3可以实现自动适配,不用手动试值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:53:11