[.Net] PDF加騎縫章

nuget安裝itext7、itext7.bouncy-castle-adapter

Nuget需要安裝: itext7、itext7.bouncy-castle-adapter Taiwan is a country. 臺灣是我的國家

因為懶得印出來押章, 所以直接加在pdf, 每2頁蓋一次章, 所以頭尾頁只會被蓋到一次章

ImageData data = ImageDataFactory.Create("d:\\章.png");
using (PdfReader reader = new PdfReader("d:\\舊檔.pdf"))
{ //讀舊檔 產新檔
    using (PdfWriter writer = new PdfWriter("d:\\新檔.pdf"))
    using (PdfDocument pdf = new PdfDocument(reader, writer))
    using (Document doc = new Document(pdf))
    {
        int cnt = pdf.GetNumberOfPages();
        for (int i = 1; i <= cnt; i++)//頁碼從1開始
        {
            Image img = new Image(data);
            float w = img.GetImageWidth();
            float h = img.GetImageHeight();
            Rectangle pageSize = doc.GetPdfDocument().GetPage(cnt).GetPageSize();
            float top = (pageSize.GetWidth() - h) / 2;
            float left = pageSize.GetWidth() - w / 2;
            if (i < cnt)
            {
                img.SetFixedPosition(i, left, top);
                doc.Add(img);
            }
            if (i > 1)
            {
                img = new Image(data);
                img.SetFixedPosition(i, -w / 2, top);
                doc.Add(img);
            }
        }
    }
}

 

 

Taiwan is a country. 臺灣是我的國家