为什么用这段代码给pdf文件添加的水印只有第一页有using (PdfReader reader = new PdfReader(path)) { int pageCount = reader.NumberOfPages; // 添加水印 PdfStamper stamper = new PdfStamper(reader, new FileStream("temp.pdf", FileMode.Create)); for (int i = 1; i <= pageCount; i++) { // 水印文本 string watermarkText = "LUDA LUDA LUDA LUDA LUDA"; // 水印字体 BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font font = new Font("Black", 80, FontStyle.Bold); //Brush brush = new SolidBrush(Color.FromArgb(128, Color.LightGray)); // 水印位置 iTextSharp.text.Rectangle rect = reader.GetPageSize(i); float x = rect.Width / 2; float y = rect.Height / 2; // 添加水印 PdfContentByte over = stamper.GetOverContent(i); over.SaveState(); over.SetGState(new PdfGState() { FillOpacity = 0.5f, StrokeOpacity = 0.5f }); over.BeginText(); over.SetFontAndSize(bf, font.Size); over.SetColorFill(BaseColor.GRAY); over.ShowTextAligned(Element.ALIGN_CENTER, watermarkText, x, y, 45); over.EndText(); over.RestoreState(); stamper.Close(); }
时间: 2023-12-08 15:03:02 浏览: 139
这是因为你在循环中每次都调用了 `PdfStamper stamper = new PdfStamper(reader, new FileStream("temp.pdf", FileMode.Create));` 来创建一个新的 `PdfStamper`,这会导致每次都重新创建一份新的 PDF 文件,并且只添加了当前页的水印。
你应该将 `PdfStamper stamper = new PdfStamper(reader, new FileStream("temp.pdf", FileMode.Create));` 放在循环外部,只创建一次,然后在循环内部通过 `stamper.GetOverContent(i)` 来获取当前页的 `PdfContentByte`,从而实现将水印添加到所有页。修改后的代码如下:
```
using (PdfReader reader = new PdfReader(path))
{
int pageCount = reader.NumberOfPages;
// 创建 PdfStamper
PdfStamper stamper = new PdfStamper(reader, new FileStream("temp.pdf", FileMode.Create));
for (int i = 1; i <= pageCount; i++)
{
// 水印文本
string watermarkText = "LUDA LUDA LUDA LUDA LUDA";
// 水印字体
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
Font font = new Font("Black", 80, FontStyle.Bold);
// 水印位置
iTextSharp.text.Rectangle rect = reader.GetPageSize(i);
float x = rect.Width / 2;
float y = rect.Height / 2;
// 添加水印
PdfContentByte over = stamper.GetOverContent(i);
over.SaveState();
over.SetGState(new PdfGState() { FillOpacity = 0.5f, StrokeOpacity = 0.5f });
over.BeginText();
over.SetFontAndSize(bf, font.Size);
over.SetColorFill(BaseColor.GRAY);
over.ShowTextAligned(Element.ALIGN_CENTER, watermarkText, x, y, 45);
over.EndText();
over.RestoreState();
}
// 关闭 PdfStamper
stamper.Close();
}
```
阅读全文