首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 使用 iTextSharp 實現 PDF 審核蓋章:處理頁面旋轉與座標轉換

     編輯:關於C#

前言

自動化審核流程常需在 PDF 最後一頁加蓋印章圖片與文字。iTextSharp 操作 PDF 時,頁面旋轉 (/Rotate) 與內容流旋轉分離,若不分別處理會導致印章位置偏移、方向錯誤。本文提供完整處理邏輯。

核心程式碼


using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.IO;

public void StampApproval(string srcPath)
{
    string dstPath = Path.ChangeExtension(srcPath, "_APPROVE.pdf");

    using (var reader = new PdfReader(srcPath))
    using (var fs = new FileStream(dstPath, FileMode.Create))
    {
        var pageSize = reader.GetPageSizeWithRotation(1);
        var doc = new Document(pageSize);
        var writer = PdfWriter.GetInstance(doc, fs);
        doc.Open();

        var cb = writer.DirectContent;
        int totalPages = reader.NumberOfPages;

        for (int i = 1; i <= totalPages; i++)
        {
            doc.SetPageSize(reader.GetPageSizeWithRotation(i));
            doc.NewPage(); // 重要:NewPage 會重置 cb

            int rotation = reader.GetPageRotation(i);
            var page = writer.GetImportedPage(reader, i);

            // 依旋轉角度套用座標轉換矩陣
            switch (rotation)
            {
                case 90:
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, pageSize.Height);
                    break;
                case 180:
                    cb.AddTemplate(page, -1f, 0, 0, -1f, pageSize.Width, pageSize.Height);
                    break;
                case 270:
                    cb.AddTemplate(page, 0, 1f, -1f, 0, pageSize.Width, 0);
                    break;
                default: // 0
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    break;
            }

            // 最後一頁加蓋印章
            if (i == totalPages)
            {
                int imgLeft = 350;
                if (rotation == 90 || rotation == 270) imgLeft = 550; // 旋轉頁面調整 X

                var img = Image.GetInstance(new Uri(@"d:\Lock-icon.png"));
                // img.ScaleToFit(140f, 320f); // 按比例縮放
                // img.ScalePercent(50f);
                cb.AddImage(img, 32f, 0, 0, 32f, 50f, imgLeft); // 寬 32pt、高 32pt、座標 (50, imgLeft)

                // 加蓋文字
                cb.BeginText();
                var bf = BaseFont.CreateFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                cb.SetFontAndSize(bf, 9);
                cb.SetTextMatrix(imgLeft, 200);
                cb.ShowText("GW INDUSTRIAL LTD");
                cb.EndText();
            }
        }

        doc.Close();
    }
}

關鍵技術點解析

  1. GetPageSizeWithRotation:取得旋轉後的實際頁面尺寸 (寬高可能互換)。
  2. NewPage() 重置 DirectContent:每頁必須呼叫,否則上一頁的內容會殘留。
  3. GetPageRotation:讀取 /Rotate 鍵值 (0/90/180/270)。
  4. AddTemplate 仿射矩陣:AddTemplate(page, a, b, c, d, e, f) 對應矩陣 [a b 0; c d 0; e f 1],實現旋轉、平移、鏡像。
  5. AddImage 參數:AddImage(img, w, 0, 0, h, x, y) 直接指定寬高與左下角座標 (PDF 座標系原點在左下)。
  6. 座標系注意:PDF 預設原點左下,iTextSharp SetTextMatrix(x, y) 同樣遵循此座標系。

常見坑與解決

現象原因解決
印章出現在頁面外未處理 /Rotate,座標按原始頁面計算使用 GetPageSizeWithRotation + AddTemplate 矩陣修正
印章方向倒轉/側躺內容流未隨頁面旋轉AddTemplate 矩陣包含旋轉修正
多頁 PDF 僅第一頁正確未在迴圈中呼叫 NewPage()每頁迴圈開頭呼叫 doc.NewPage()
文字位置與圖片不對齊AddImage 使用 pt,SetTextMatrix 同為 pt,但 Y 軸方向相反統一換算:1 pt = 1/72 inch,Y 從頁面底部向上

結語

掌握 GetPageRotation、AddTemplate 仿射矩陣、NewPage 重置機制,即可正確處理任意旋轉角度的 PDF 頁面蓋章。此技術廣泛適用於電子簽章、水印、批註自動化等場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved