最近笔者因工作原因需要对一些pdf进行加水印处理,于是百度了几款pdf软件,好开心可以加水印了!
一顿操作下来,发现软件名称也作为水印加到了pdf页面底端,这也太好(e)看(xin)了吧!!!果断打码,不能帮你打广告。
于是我想自己写个吧,也不难,不就画几个字在上面嘛。
说做就做。
本文总结了两种实现方式:
—Spire.Pdf (免费版只支持10页以下的PDF)
—iTextSharp (无限制)
首先,新建名为watermark的winform窗体项目。
一、Spire.Pdf
· 将Spire.License.dll和Spire.Pdf.dll导入项目。
· 核心代码:
Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
pdf.LoadFromFile(fileName);//pdf超出10页此处会报错。
for (int i = 0; i < pdf.Pages.Count; i++)
{
PdfPageBase page = pdf.Pages[i];
PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));
brush.Graphics.SetTransparency(0.3f);
brush.Graphics.Save();
brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
brush.Graphics.RotateTransform(-45);
brush.Graphics.DrawString("A few lines of code.",
new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica,36),
PdfBrushes.Blue, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
brush.Graphics.Restore();
brush.Graphics.SetTransparency(1);
page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
}
if (safeFileName != "")
{
pdf.SaveToFile(tbSavePos.Text + @"\" + safeFileName.Substring(0, safeFileName.IndexOf(".pdf"))+"_WaterMark.pdf");
MessageBox.Show("ok.");
}
· 运行效果:
二、iTextSharp
· 将iTextSharp.dll导入项目。
· 核心代码:
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
try
{
pdfReader = new PdfReader(filePath);
pdfStamper = new PdfStamper(pdfReader, new FileStream(savepath, FileMode.Create));
int total = pdfReader.NumberOfPages + 1;
iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
PdfContentByte content;
BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
PdfGState gs = new PdfGState();
for (int i = 1; i < total; i++)
{
content = pdfStamper.GetOverContent(i);//在内容上方加水印
gs.FillOpacity = 0.3f; //透明度
content.SetGState(gs); //写入文本
content.BeginText();
content.SetColorFill(BaseColor.BLUE);
content.SetFontAndSize(font, 36);
content.SetTextMatrix(0, 0);
content.ShowTextAligned(Element.ALIGN_CENTER, text, width - 200, height - 200, -45);
content.EndText();
}
MessageBox.Show("ok.");
}
catch (Exception ex)
{ throw ex; }
finally
{
if (pdfStamper != null)
pdfStamper.Close();
if (pdfReader != null)
pdfReader.Close();
}
· 运行效果:
总结:因Spire.Pdf受限,推荐使用iTextSharp的方式实现,当然动态库可以实现更多的pdf操作方法,读者可以继续深入挖掘,笔者因为需(tou)求(lan)的关系不再深究。
源码下载:点击此处
或关注公众号【几行简码】(ID:few_codes)回复【加水印】获取免费下载链接。
原创文章,转载请按公众号内【转载须知】操作。