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

如何使用iTextSharp的PdfWriter实现PDF页面旋转

你可以在生成PDF阶段直接通过设置Document的页面属性实现旋转,不需要依赖PdfReader,两种常用实现方案如下:

全局所有页面统一旋转

初始化Document时直接对页面大小对象设置旋转参数即可:

  • 常用的90度横屏可以直接调用Rotate()方法:
// 替换原初始化Document的代码即可
Document document = new Document(PageSize.A4.Rotate(), 45, 45, 80, 80);
  • 自定义其他角度(支持0/90/180/270四个取值):
Rectangle customPage = PageSize.A4;
customPage.Rotation = 180; // 页面倒置
Document document = new Document(customPage, 45, 45, 80, 80);

单页单独设置旋转

如果只需要指定页面旋转,其余页面保持默认,可以在调用NewPage()生成新页面前修改Document的页面大小参数:
修改后的完整示例代码如下:

private void CreatePdf(string strPdfPath)
{
    using (FileStream fs = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None))
    using (Document document = new Document(PageSize.A4, 45, 45, 80, 80))
    {
        PdfWriter writer = PdfWriter.GetInstance(document, fs);
        document.Open();
        document.AddTitle("This is Title");
        document.AddCreationDate();
        // 第一页默认无旋转
        Paragraph content1 = new Paragraph("This is first Page");
        document.Add(content1);

        // 设置第二页旋转180度
        var rotatedPage = PageSize.A4;
        rotatedPage.Rotation = 180;
        document.SetPageSize(rotatedPage);

        document.NewPage();
        Paragraph content2 = new Paragraph("This is second Page");
        document.Add(content2);
        
        // 后续页面如需恢复默认旋转,重新设置页面大小即可
        // document.SetPageSize(PageSize.A4);
        // document.NewPage();
    }
}

提示:建议用using语法管理IO流、Document、PdfWriter对象的生命周期,无需手动调用Close()方法即可自动释放资源,避免资源泄漏。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:24:03