在程序中操作PDF,给一个没有加页码的PDF文件加上自定义的页码
还是一样,没有DLL的或者下载不到的可以联系我。
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.IO;
using System.Windows.Forms;
namespace Pic2PDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = Application.StartupPath;
string pdffilename = path + "\test.pdf";
string pdffilename1 = path + "\test1.pdf";
//执行操作,加上页码
string r = AddTexts(pdffilename, pdffilename1);
MessageBox.Show(r);
}
public static string AddTexts(string PdfPath, string oPdfPath)
{
try
{
PdfReader pdfReader = new PdfReader(PdfPath);
FileStream stream = new FileStream(oPdfPath, FileMode.OpenOrCreate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, stream);
iTextSharp.text.Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(1);
float w = pageRectangle.Width;
float h = pageRectangle.Height;
float locationx;
float locationy;
locationx = w - 50;
locationy = 30;
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
{
PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);
pdfData.SetFontAndSize(BaseFont.CreateFont(@"C:windowsfontsSIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 10);
PdfGState graphicsState = new PdfGState();
pdfData.SetGState(graphicsState);
pdfData.BeginText();
pdfData.ShowTextAligned(Element.ALIGN_CENTER, "第 " + pageIndex.ToString() + " 页", locationx, locationy, 1);
pdfData.EndText();
}
pdfStamper.Close();
stream.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return "ok";
}
}
}