.netcore 文件添加水印(pdf 图片)

使用的控件:
1.System.Drawing.Common (图片处理)
2.iTextSharp.LGPLv2.Core (pdf处理)

图片处理:
1.透明背景图片
Bitmap image=new Bitemap(width,height);
Graphics g=Graphics.FromImage(image);
g.Clear(Color.Transparent);
g.Dispose()

2.图片上添加文字
Graphics g=Graphics.FromImage(image);
FontFamily fontFamily=FontFamily.GenericSerif;
float fontSize=12;
FontStype fontStyle=FontStyle.Regular;
Color color=Color.Black;
Font font=new Font(fontFamily,fontSize,fontstyle);
SolidBrush brush=new SolidBrush(color);
string content="文字";
SizeF size=g.MesasureString(content,font);//文字显示的尺寸
var top=(image.Height-size.Height)/2;
var left=(image.Width-size.Width)/2;
g.DrawString(content,font,brush,left,top);
g.Dispose();

3.图片透明度
public Bitmap SetBitmapAlpha(int aphal,Bitmap image)
{
float[][]matrixItems={
new float[]{1,0,0,0,0},
new float[]{0,1,0,0,0},
new float[]{0,0,1,0,0},
new float[]{0,0,0,aphal/255f,0},
new float[]{0,0,0,0,1}
};
ColorMatrix colorMatrix=new ColorMatrix(matrixItems);
ImageAtrributes imageAttributes=new ImageAttributes();
imageAttributes.SetColorMatrix(colorMatrix,ColorMatrixFlag.Default,ColorAdjustType.Bitmap);
Bitmap bmp=new Bitmap(image.Width,image.Height);
Graphics /(bmp);
g.DrawImage(image,new Rectangle(0,0,image.Width,image.Height),0,0,image.Width,image.Height,GraphicsUnit.Pixel,imageAttributes);
g.Dispose();
return bmp;
}

4.旋转
public Bitmap Rotate(int rotate,Bitmap image)
{
int angle=rotate%360;
double randian=angle*Math.PI/180;
double cos=Math.Cos(radian);
double sin=Math.Sin(radian);

int w=image.Width;
int h=image.Height;
int W=(int)(Math.Max(Math.Abs(w*cos-h*sin),Math.Abs(w*cos+h*sin)));
int H=(int)(Math.Max(Math.Abs(w*sin-h*cos),Math.Abs(w*sin+h*cos)));

Bitmap dsImage=new Bitmap(W,H);
Graphics g=Graphics.FromImage(dsImage);
g.InterpolationMode=System.Drawing.Draing2D.InterpolationMode.Bilinear;
g.SmoothingMode=System.DrawinnDrawing2D.SmoothingMode.HighQuality;
Point offset=new Point((W-w)/2,(H-h)/2);
Rectangle rect=new Rectangle(offset.X,offset.Y,w,h);
Point center=new Point(rect.X+rect.Width/2,rect.Y+rect.Height/2);
g.TranslateTransform(center.X,center.Y);
g.RotateTransform(angle);
g.TranslateTranform(-center.X,-center.Y);
g.DrawImage(image,rect);
g.ResetTransform();
g.Dispose();
return dsImage;
}

PDF添加水印
using(MemoryStream outstream=new MemoryStream())
{
var pdfReader=new PdfReader(streamdata); //PDF原文件
var stapmer=new PdfStamper(pdfReader,outstream); //保存更改后的PDF
var page=stapmer.GetImportedPage(pdfReader,1);
int total=pdfReader.NumberOfPages;

MemoryStream watermemorystream=new MemoryStream();

Bitmap waterBitmap=BitmapHelper.MakeWaterImage(); //获取水印图片
for(int i=1;i<=total;i++)
{
iTextSharp.text.Image image=iTextSharp.text.Image.GetInstance(waterBitmap,System.Drawing.Imaging.ImageFormat.Png);
var top=10;
var left=0;
PdfContentByte under=stamper.GetOverContent(i);
image.SetAbsolutePositon(left,top);
under.AddImage(image);
}
}

水印设置页面:
每次修改水印属性参数,(确定)后台重新生成一个水印图片。

原文地址:https://www.cnblogs.com/zwbsoft/p/13328204.html