.NET C# 使用 iText 生成PDF

2024-07-19 1436阅读

.NET C# 使用 iText 生成PDF

文章目录

  • .NET C# 使用 iText 生成PDF
    • 1 安装 iText 7 库:
    • 2 变量定义
    • 3 创建一个PDF
    • 4 段落
    • 5 旋转文本
    • 6 代码块
    • 7 外部链接
    • 8 内部链接
    • 9 表格
    • 10 注释
    • 11 线条
    • 12 二维码
    • 13 嵌入图像
    • 14 列表
    • 15 设置背景
    • 16 页眉
    • 17 页脚
    • 18 事件
    • 19 水印
    • 20 分栏
    • 21 源码

      本文章代码PDF生成样例:example.pdf

      .NET C# 使用 iText 生成PDF
      (图片来源网络,侵删)

      1 安装 iText 7 库:

      Install-Package itext7
      
      Install-Package itext7.bouncy-castle-adapter
      

      环境:itext7 8.0.4 | itext7.bouncy-castle-adapter 8.0.4

      2 变量定义

      // 定义PDF文件路径
      const string pdfPath = "example.pdf";
      // 定义字体文件路径
      const string sunFontPath = @"C:\Windows\Fonts\simsun.ttc,0";
      const string heiFontPath = @"C:\Windows\Fonts\simhei.ttf";
      // 定义图片路径
      const string imagePath = @"res\image.png";
      const string cover1Path = @"res\c1.png";
      const string cover2Path = @"res\c2.png";
      const string cover3Path = @"res\c3.png";
      // 定义PDF背景路径
      const string backgroundPath = @"res\background.jpg";
      // 创建字体
      static PdfFont heiFont = PdfFontFactory.CreateFont(heiFontPath, PdfEncodings.IDENTITY_H);
      static PdfFont sunFont = PdfFontFactory.CreateFont(sunFontPath, PdfEncodings.IDENTITY_H);
      

      3 创建一个PDF

      // 创建一个PDF writer
      PdfWriter writer = new PdfWriter(pdfPath);
      // 创建一个PDF document
      PdfDocument pdf = new PdfDocument(writer);
      // 创建一个Document
      Document document = new Document(pdf, PageSize.A4);
      

      4 段落

      Paragraph paragraph = new Paragraph("这是一个段落。")
          .SetFont(heiFont)
          .SetFontSize(12)
          .SetTextAlignment(TextAlignment.LEFT);
      document.Add(paragraph);
      

      5 旋转文本

      Paragraph rotatedText = new Paragraph("旋转的文本")
          .SetRotationAngle(Math.PI / 4)
          .SetFont(heiFont)
          .SetFontSize(12);
      document.Add(rotatedText);
      

      6 代码块

      Paragraph codeBlock = new Paragraph()
          .Add(new Text("public static void main(String[] args)\n{\n"))
          .Add(new Tab())
          .Add(new Text("System.out.println(\"Hello, World!\");"))
          .Add(new Text("\n}"))
          .SetFont(PdfFontFactory.CreateFont(StandardFonts.COURIER))
          .SetFontSize(12)
          .SetBackgroundColor(new DeviceRgb(0xEE, 0xF0, 0xF4))
          .SetPadding(10)
          .SetBorderRadius(new BorderRadius(5));
      document.Add(codeBlock);
      

      7 外部链接

      Text externalLink = new Link("访问网站", PdfAction.CreateURI("https://www.example.com")).SetFontColor(ColorConstants.BLUE).SetUnderline();
      Paragraph linkParagraph = new Paragraph("这是一个带有外部链接的段落: ").SetFont(heiFont).Add(externalLink);
      document.Add(linkParagraph);
      

      8 内部链接

      Paragraph paragraph = new Paragraph("内部链接")
          .SetTextAlignment(TextAlignment.LEFT)
          .SetFontSize(22)
          .SetBold()
          .SetFont(heiFont)
          .SetMarginBottom(20)
          .SetDestination("externalLink");
      document.Add(paragraph);
      // 添加标签
      PdfOutline rootOutline = document.GetPdfDocument().GetOutlines(false);
      PdfOutline firstSection = rootOutline.AddOutline(title);
      firstSection.AddDestination(PdfDestination.MakeDestination(new PdfString(destination)));
      PdfAction action = PdfAction.CreateGoTo("externalLink");
      Text internalLink = new Link("跳转到 -> 外部连接", action).SetFontColor(ColorConstants.BLUE).SetUnderline();
      Paragraph internalLinkParagraph = new Paragraph("这是一个带有内部链接的段落: ").SetFont(heiFont).Add(internalLink);
      document.Add(internalLinkParagraph);
      

      9 表格

      // 创建表格(3 列)
      Table table = new Table(UnitValue.CreatePercentArray(new float[] { 1, 1, 1 }))
          .UseAllAvailableWidth();
      // 添加表头
      table.AddHeaderCell(new Cell().Add(new Paragraph("表头 1").SetFont(heiFont)));
      table.AddHeaderCell(new Cell().Add(new Paragraph("表头 2").SetFont(heiFont)));
      table.AddHeaderCell(new Cell().Add(new Paragraph("表头 3").SetFont(heiFont)));
      // 添加五行数据
      for (int i = 1; i 
          table.AddCell(new Cell().Add(new Paragraph("单元格 " + i + ", 1").SetFont(heiFont)));
          table.AddCell(new Cell().Add(new Paragraph("单元格 " + i + ", 2").SetFont(heiFont)));
          table.AddCell(new Cell().Add(new Paragraph("单元格 " + i + ", 3").SetFont(heiFont)));
      }
      document.Add(table);
      
          ListItem listItem = new ListItem($"条目 {i}");
          Paragraph paragraph = new Paragraph($"这里是条目 {i} 的内容。\n这里是条目 {i} 的内容。")
              .SetFont(heiFont)
              .SetFontSize(12)
              .SetBackgroundColor(new DeviceRgb(0xEE, 0xF0, 0xF4))
              .SetPadding(10)
              .SetBorderRadius(new BorderRadius(5));
          listItem.Add(paragraph);
          list.Add(listItem);
      }
      document.Add(list);
      
          public void HandleEvent(Event @event)
          {
              PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
              PdfDocument pdfDoc = docEvent.GetDocument();
              PdfPage page = docEvent.GetPage();
              Rectangle pageSize = page.GetPageSize();
              // 添加页脚文本
              Canvas canvas = new Canvas(page, pageSize);
              int pageNumber = pdfDoc.GetPageNumber(page);
              Paragraph footer = new Paragraph($"第 {pageNumber} 页")
                  .SetFont(heiFont)
                  .SetFontSize(10)
                  .SetTextAlignment(TextAlignment.RIGHT);
              canvas.ShowTextAligned(footer,
                  pageSize.GetWidth() - 20, pageSize.GetBottom() + 20, TextAlignment.RIGHT);
              canvas.Close();
          }
      }
      
          for (float y = yStep / 2; y 
VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]