如何将数字放入PDF页面

时间:2019-02-04 11:04:58

标签: c# pdf itext

我是编程的新手,我试图使用iTextSharp库制作一个应用程序,该库需要一个pdf文件,并在其上放置页码,然后创建一个新文件。

我试图在Internet上创建一个带有示例的WinForm应用程序。

以下代码应将页码放入给定的pdf文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace NummerierePDF
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte[] bytes = File.ReadAllBytes(@"C:\Test.pdf");
            Font blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);
            using (MemoryStream stream = new MemoryStream())
            {
                PdfReader reader = new PdfReader(bytes);
                using (PdfStamper stamper = new PdfStamper(reader, stream))
                {
                    int pages = reader.NumberOfPages;
                    for (int i = 1; i <= pages; i++)
                    {
                        ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
                    }
                }
                bytes = stream.ToArray();
            }
            File.WriteAllBytes(@"C:\Test_1.pdf", bytes);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

我收到这些错误消息:

Erorr messages

2 个答案:

答案 0 :(得分:2)

在声明局部变量blackFont时,必须指定完整类型名称iTextSharp.text.Font,因为存在不同的类,其名称为Font,并且编译器不知道哪个类型服用。

iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

另请参阅Resolving an ambiguous reference

答案 1 :(得分:2)

我只更改了1行以消除编译错误

更改

Font blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);

iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

由于名称空间相同,在System.Drawing.Font和iTextSharp.text.Font之间造成混淆。我刚刚添加了正确的命名空间

我可以看到添加了页码的新pdf文件。

相关问题