文档详情

.net core利用PdfSharpCore操作PDF实例教程.docx

发布:2025-05-25约3.67千字共5页下载文档
文本预览下载声明

.net?core利用PdfSharpCore操作PDF实例教程

目录前序1.设置PDF拥有者的密码,让PDF防篡改。2.PDF添加页眉和页脚(2)添加页眉(3)添加页脚3.PDF添加水印文字4.PDF添加图片总结

前序

使用PdfSharpCore请注意使用XGraphics基类,与System.Drawing的Graphics类似,XGraphics提供XColor(颜色)、XPen(画笔)、XBrush(画刷)、XFont(字体)、XPoint(位置)等对象。提供很多画线,矩形,圆,扇形,多边形,图,文本等方法。源码请查看/ststeiger/PdfSharpCore/blob/master/PdfSharpCore/Drawing/XGraphics.cs

1.设置PDF拥有者的密码,让PDF防篡改。

代码很简单设置PdfDocument.SecuritySettings.OwnerPassword

PdfDocumentdoc=PdfReader.Open(@a.pdf,PdfDocumentOpenMode.Modify);

doc.SecuritySettings.OwnerPassword=123;

varfilePath=$b.pdf;

doc.Save(filePath);

2.PDF添加页眉和页脚

(1)添加页码显示

XStringFormats指定文本的位置:详请查看/ststeiger/PdfSharpCore/blob/master/PdfSharpCore/Drawing/XStringFormats.cs

XFontfont=newXFont(SimHei,8);

XBrushbrush=XBrushes.Black;

PdfDocumentdoc=PdfReader.Open(@a.pdf,PdfDocumentOpenMode.Modify);

for(inti=0;idoc.Pages.Count;i++)

PdfPagepage=doc.Pages[i];

XRectlayoutRectangle=newXRect(0,page.Height-font.Height,page.Width,font.Height);

using(XGraphicsgfx=XGraphics.FromPdfPage(page))

gfx.DrawString(

$第{(i+1).ToString()}页/共{doc.Pages.Count}页,

font,

brush,

layoutRectangle,

XStringFormats.BottomLeft);

}

(2)添加页眉

XFontfont=newXFont(SimHei,8);

XBrushbrush=newXSolidBrush(XColor.FromArgb(128,255,0,0));

XPointpoint=newXPoint(90,20);

PdfDocumentdoc=PdfReader.Open(@a.pdf,PdfDocumentOpenMode.Modify);

for(inti=0;idoc.Pages.Count;i++)

varrenderer=XGraphics.FromPdfPage(doc.Pages[i]);

XSizepageSize=renderer.PageSize;

renderer.DrawString(xxx有限公司,font,brush,point);

XPenpen=newXPen(XBrushes.Gray,0.5f);

renderer.DrawLine(pen,point.X,point.Y,pageSize.Width-point.X,point.Y);

doc.Save(b.pdf);

(3)添加页脚

XFontfont=newXFont(SimHei,8);

XBrushbrush=newXSolidBrush(XColor.FromArgb(128,255,0,0));

PdfDocumentdoc=PdfReader.Open(@a.pdf,PdfDocumentOpenMode.Modi

显示全部
相似文档