C#使用iTextSharp操作PDF文件

    技术2022-07-16  72

    参加: https://www.cnblogs.com/lingxin/p/9233767.html

    由于最近项目中要生成比较复杂的PDF文件,所以对于iTextSharp组建研究了一下,最终成功实现了想要的效果,发现这个组件功能非常强大,刚开始不熟悉该组件的代码所以遇到很多问题(基本都是内容格式上的问题),借由这篇博客记录一下。

    1.首先下载该组件并添加引用,这里是使用VS自带的NuGet来进行安装的,键项目选择管理NuGet程序包,搜索iTextSharp选择合适版本安装即可,安装完成会自动添加引用。

    2.在使用的文件里面引入命名空间

    using iTextSharp.text; using iTextSharp.text.pdf;

    3.简单的生成PDF文件,其中Fname为生成文件存放的路径。

    简单说一下:

    Rectangle对象是用来设置PDF页面尺寸的。

    Document对象为页面对象,就像是HTML里面的页面对象一样,用于操作页面内容和格式。

    PdfWriter对象是用于将Document对象写入PDF文件。

    Rectangle pageSize = new Rectangle(1000, 500); Document document = new Document(pageSize, 10, 10, 120, 80); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Fname, FileMode.Create)); document.Open(); document.Add(new iTextSharp.text.Paragraph("Hello World! Hello People! " + "Hello Sky! Hello Sun! Hello Moon! Hello Stars!")); document.Close(); writer.Close();

    4.设置PDF文档信息,利用Document对象。

    document.AddTitle("这里是标题"); document.AddSubject("主题"); document.AddKeywords("关键字"); document.AddCreator("创建者"); document.AddAuthor("作者");

    5.向PDF里面添加图片,Fimg为图片路径,创建一个iTextSharp.text.Image对象,将该对象添加到文档里面,SetAbsolutePosition方法是设置图片出现的位置。

    string imgurl = @System.Web.HttpContext.Current.Server.MapPath(Fimg); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgurl); img.SetAbsolutePosition(0, 0); writer.DirectContent.AddImage(img);

     

     

     

     

     

     

    Processed: 0.010, SQL: 10