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

使用iTextSharp叠加两份PDF时如何让内容显示在信头页眉页脚之间

你当前的问题是原有PDF内容本身的排版覆盖了页眉/页脚区域,仅把信头放在内容下层无法解决覆盖问题,需要先将原有内容整体向下偏移,预留出页眉高度,同时限制内容不向下溢出到页脚区域,再叠加信头模板即可。

修改后的代码如下:

string originalPdfPath = @"C:\Users\BiberEmr\Downloads\testPdf\ThreePageContent.pdf";
string letterHeadPath = @"C:\Users\BiberEmr\Downloads\testPdf\letterhead_lorenzo.pdf";
string outputPath = @"C:\Users\BiberEmr\Downloads\testPdf\result2.pdf";

// 可根据你的信头实际尺寸调整这两个值,单位是PDF默认的用户单位(约1/72英寸)
float headerHeight = 80f; // 信头页眉占用高度
float footerHeight = 50f; // 信头页脚占用高度

PdfReader contentReader = new PdfReader(originalPdfPath);
PdfStamper stamper = new PdfStamper(contentReader, new FileStream(outputPath, FileMode.Create));
PdfReader templateReader = new PdfReader(letterHeadPath);
PdfImportedPage templatePage = stamper.GetImportedPage(templateReader, 1);

for (int i = 1; i <= contentReader.NumberOfPages; i++)
{
    Rectangle pageSize = contentReader.GetPageSize(i);
    // 1. 处理内容层:将原有内容整体下移,预留页眉空间,同时裁剪掉溢出页眉页脚的内容
    PdfContentByte overContent = stamper.GetOverContent(i);
    overContent.SaveState();
    // 设置裁剪区域:仅保留页眉以下、页脚以上的区域可显示内容
    Rectangle contentArea = new Rectangle(0, footerHeight, pageSize.Width, pageSize.Height - headerHeight);
    overContent.Rectangle(contentArea);
    overContent.Clip();
    overContent.NewPath();
    // 将内容整体向下偏移headerHeight,避免顶部内容覆盖页眉
    overContent.ConcatCTM(1, 0, 0, 1, 0, -headerHeight);
    overContent.RestoreState();

    // 2. 把信头模板加到内容底层
    PdfContentByte underContent = stamper.GetUnderContent(i);
    underContent.AddTemplate(templatePage, 0, 50);
}

stamper.Close();
templateReader.Close();
contentReader.Close();

调整说明

  • 代码中的headerHeight和footerHeight需要根据你自己的信头模板实际尺寸调整,多次测试输出直到内容刚好完全显示在页眉页脚之间即可。
  • 如果你需要调整信头的垂直显示位置,可修改AddTemplate方法的最后一个坐标参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:27:04