c# PDFSharp 给已有的pdf文件添加文字页脚(文字水印)

使用c# PDFSharp 版本:1.50.5147 给已有的PDF文件每页添加页脚

 private void Button_Click(object sender, RoutedEventArgs e)
{
	System.Drawing.Text.PrivateFontCollection pfcFonts = new System.Drawing.Text.PrivateFontCollection();
            string strFontPath = @"C:\Windows\Fonts\simfang.ttf";//字体设置为微软雅黑
            pfcFonts.AddFontFile(strFontPath);
            XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
            XFont font = new XFont(pfcFonts.Families[0], 12, XFontStyle.Regular, options);

            // 加载PDF文件
            PdfDocument inputDocument = PdfReader.Open("C:\\Users\\36142\\Documents\\WXWork\\1688850881984293\\Cache\\File\\2023-09\\paper_test.pdf", PdfDocumentOpenMode.Modify);

            // 循环所有页面
            for (int pageNumber = 0; pageNumber < inputDocument.PageCount; pageNumber++)
            {
                // 获取页面
                PdfPage page = inputDocument.Pages[pageNumber];

                // 创建字体和格式
                //XFont font = new XFont("Verdana", 8, XFontStyle.Regular);
                XStringFormat format = new XStringFormat();
                format.Alignment = XStringAlignment.Center;

                // 添加页数和页脚
                string text = string.Format("试卷编号:31929418,第{0}页,共{1}页", pageNumber + 1, inputDocument.PageCount);
                XSize size = page.MediaBox.Size;
                XRect rect = new XRect(0, size.Height - 35, size.Width, 10);
                XGraphics gfx = XGraphics.FromPdfPage(page);
                gfx.DrawString(text, font, XBrushes.Black, rect, format);
            }
            // 保存PDF文件
            inputDocument.Save("C:\\Users\\36142\\Desktop\\pdf\\output.pdf");
}```

你可能感兴趣的:(c#,pdf,开发语言)