怎样保留pdf里的水印(给PDF所有页加上文字水印)
给一个PDF的所有页加上文字水印,效果如下
新建一个项目,直接上代码了:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.IO;
using System.Windows.Forms;
namespace _111
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string p = Application.StartupPath "\\";
string r = AddTextShuiYin(p "test.pdf", p "test1.pdf", 0.5f, "HELLO");
MessageBox.Show(r);
}
public static string AddTextShuiYin(string PdfPath, string OutPdfPath, float toumingdu, string ShuiYinText)
{
if (File.Exists(OutPdfPath))
{
File.Delete(OutPdfPath);
}
PdfReader reader = null;
PdfStamper ShuiYinOBJ = null;
PdfContentByte ShuiYinQu;
try
{
reader = new PdfReader(PdfPath);
//得到原PDF的页数和宽高
PDFATT att = new PDFATT(PdfPath);
int n = att.PageCount();
float w = att.Width();
float h = att.Height();
//从第0页开始
int i = 0;
ShuiYinOBJ = new PdfStamper(reader, new FileStream(OutPdfPath, FileMode.Create));
PdfGState gs = new PdfGState();
//设置透明度
gs.FillOpacity = toumingdu;
BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
while (i < n)
{
i ;
//在正文内容下加水印,不挡内容
ShuiYinQu = ShuiYinOBJ.GetUnderContent(i);
//在正文内容上加水印,挡内容
//ShuiYinQu = ShuiYinOBJ.GetOverContent(i);
ShuiYinQu.SetGState(gs);
for (float left = 0; left < w; left = 200)
{
for (float top = 0; top < h; top = 100)
{
//透明度
gs.FillOpacity = toumingdu;
ShuiYinQu.SetGState(gs);
//开始写入文本
ShuiYinQu.BeginText();
ShuiYinQu.SetColorFill(iTextSharp.text.Color.RED);
ShuiYinQu.SetFontAndSize(font, 180);
ShuiYinQu.SetTextMatrix(2, 2);
ShuiYinQu.ShowTextAligned(Element.ALIGN_CENTER, ShuiYinText, w / 2, h / 2, 30);
//ShuiYinQu.AddImage(im);
}
}
ShuiYinQu.EndText();
}
ShuiYinOBJ.Close();
reader.Close();
return "OK";
}
catch (Exception ex)
{
return ex.ToString();
}
}
class PDFATT
{
PdfReader reader;
public PDFATT(string iPdfFilePath)
{
reader = new PdfReader(iPdfFilePath);
}
public int PageCount()
{
return reader.NumberOfPages;
}
public float Width()
{
return reader.GetPageSize(1).Width;
}
public float Height()
{
return reader.GetPageSize(1).Height;
}
}
}
}
string p = Application.StartupPath "\\";
//参数:源文件地址,新文件地址,透明度(float型),水印文本
string r = AddTextShuiYin(p "test.pdf", p "test1.pdf", 0.5f, "HELLO");
MessageBox.Show(r);
水印位置//这里我是w/2和h/2,大概在页中间,当然这里我为了演示没有精确计算,
//30 是旋转角度
ShuiYinQu.ShowTextAligned(Element.ALIGN_CENTER, ShuiYinText, w / 2, h / 2, 30);
下次研究下加图片水印,免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com