C#操作pdf之使用itext实现01-生成一个简单的table

本文介绍了如何在.NET8的控制台项目中安装iText库及其依赖,解决中文显示问题,通过设置字体和嵌入策略创建包含中文的简单PDF表格。
摘要由CSDN通过智能技术生成

创建.net 8控制台项目

在这里插入图片描述

安装itext

 <PackageReference Include="itext" Version="8.0.2" />
 <PackageReference Include="itext.bouncy-castle-adapter" Version="8.0.2" />
 <PackageReference Include="itext.bouncy-castle-fips-adapter" Version="8.0.2" />

在这里插入图片描述

代码

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;

namespace ITextStu01
{
    internal class Program
    {
        /// <summary>
        /// 程序入口
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string basePath = System.AppDomain.CurrentDomain.BaseDirectory;
            string savePath = Path.Combine(basePath, "simple_table.pdf");
            ManipulatePdf(savePath);
        }

        /// <summary>
        /// 处理PDF
        /// </summary>
        /// <param name="dest"></param>
        static void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);

            Table table = new Table(UnitValue.CreatePercentArray(8)).UseAllAvailableWidth();

            for (int i = 0; i < 16; i++)
            {
                if (i % 2 == 0)
                    table.AddCell("hello");
                else
                    table.AddCell("你好");

            }
            doc.Add(table);

            doc.Close();
        }
    }
}

结果

在这里插入图片描述
可以看到中文没有显示,经过了解是缺少字体导致中文没有显示,下面的地址是字体地址,仅供学习使用
https://github.com/Haixing-Hu/latex-chinese-fonts
这里下载的宋体,添加到项目中,并且设置为始终复制
在这里插入图片描述
修改代码

/// <summary>
/// 处理PDF
/// </summary>
/// <param name="dest"></param>
static void ManipulatePdf(string dest)
{
    var sontFont = PdfFontFactory.CreateFont("Fonts/STSong.ttf", EmbeddingStrategy.PREFER_EMBEDDED);
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);
    doc.SetFont(sontFont).SetFontSize(14);//设置字体大小
    Table table = new Table(UnitValue.CreatePercentArray(8)).UseAllAvailableWidth();

    for (int i = 0; i < 16; i++)
    {
        if (i % 2 == 0)
            table.AddCell("hello");
        else
            table.AddCell("你好");

    }
    doc.Add(table);

    doc.Close();
}

在这里插入图片描述

参考地址

https://kb.itextpdf.com/itext/101-a-very-simple-table

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

假装我不帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值