通过 iTextSharp 实现PDF 审核盖章2014-04-14 cnblogs 夕照毓秀最近需要做一个PDF自动审核盖章的工作,其实就是读取PDF,然后再最后一页加入一个审核章印图 片上去。看起来很简单,不过在开发过程中,还是遇到了一些问题,在这里记录一下。主要遇到的问题是页面的旋转 和 内容的旋转 的分开的,需要分别操作。准备工作需要下载 iTextSharp.dll 然后加入引用using iTextSharp.text;using iTextSharp.text.pdf;
string path = @"D:28727_LOG001_FOLIOLE COMPANY LIMITED_STOCK_PI";// 创建一个PdfReader对象PdfReader reader = new PdfReader(path + ".pdf");// 获得文档页数int n = reader.NumberOfPages;// 获得第一页的大小Rectangle psize = reader.GetPageSize(1);float width = psize.Width;float height = psize.Height;// 创建一个文档变量Document document = new Document(psize);// 创建该文档 生成物理文件PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path + "_APPROVE.pdf", FileMode.OpenOrCreate));// 打开文档document.Open();// 添加内容PdfContentByte cb = writer.DirectContent;for (int i = 0; i < n; ){i++;//设置指定页的PagSize 包含Rotation(页面旋转度)document.SetPageSize(reader.GetPageSizeWithRotation(i));//创建一个新的页面,需要注意的调用NewPage() ,PdfContentByte cb 对象会默认清空document.NewPage();//获取指定页面的旋转度int rotation = reader.GetPageRotation(i);//获取加载PDF的指定页内容PdfImportedPage page1 = writer.GetImportedPage(reader, i);//添加内容页到新的页面,并更加旋转度设置对应的旋转switch (rotation){case 90:cb.AddTemplate(page1, 0, -1, 1, 0, 0, reader.GetPageSizeWithRotation(i).Height);break;case 180:cb.AddTemplate(page1, -1, 0, 0, -1, reader.GetPageSizeWithRotation(i).Width, reader.GetPageSizeWithRotation(i).Height); break;case 270:cb.AddTemplate(page1, 0, 1, -1, 0, reader.GetPageSizeWithRotation(i).Width, 0);break;default:cb.AddTemplate(page1, 1, 0, 0, 1, 0, 0);//等同于 cb.AddTemplate(page1, 0,0)break;}if (i == n)//如果是最后一页加入指定的图片{ //不同旋转度的页面 图片位置left距离的调整 int imgLeft = 350; if(rotation==90 || rotation==270) {imgLeft = 550;} //创建一个图片对象iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(new Uri(@"d:Lock-icon.png"));//设置图片的指定大小//img.ScaleToFit(140F, 320F);//按比例缩放//img.ScalePercent(50); //把图片增加到内容页的指定位子b width c heighte bottom f leftcb.AddImage(img, 0, 32F, 32F, 0, 50F, imgLeft);//开始增加文本cb.BeginText();BaseFont 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(); }}// 关闭文档document.Close();}catch (Exception de){Console.Error.WriteLine(de.Message);Console.Error.WriteLine(de.StackTrace);}