C#基于ItextSharp 生成PDF文档(包含源码实例)

需要引入的依赖包,在这里我用的是下面两个版本的依赖包

iTextSharp 版本为5.5.13.3

QRCoder 版本为1.4.3 

生成的效果

image.png

以下是核心代码

PdfUtils类

public class PdfUtils
{
    const string ITextExamplesFolder = "iTextExamples";
    const string ResourcesFolder = "resources";


    public static string Author => "haogm";


    public static string GetBaseDir()
    {

        return Environment.CurrentDirectory;
    }
    /// <summary>
    /// 创建列 插入文本内容
    /// </summary>
    /// <param name="table"></param>
    /// <param name="content"></param>
    /// <param name="font"></param>
    /// <param name="minimumHeight"></param>
    /// <param name="colspan"></param>
    /// <param name="rowspan"></param>
    public static void CreateCell(PdfPTable table, string content, Font font, int minimumHeight = 20, int colspan = 0, int rowspan = 0)
    {
        var cell = new PdfPCell(new Phrase(content, font));
        cell.UseAscender = true;// 设置可以居中
        cell.MinimumHeight = minimumHeight;// 设置单元格高度
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;// 设置水平居中
        cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;// 设置垂直居中
        if (rowspan != 0)
        {
            cell.Rowspan = rowspan; //行合并
        }
        if (colspan != 0)
        {
            cell.Colspan = colspan; //列合并
        }
        table.AddCell(cell);
    }
    /// <summary>
    /// 创建列 插入图片
    /// </summary>
    /// <param name="table"></param>
    /// <param name="image"></param>
    /// <param name="minimumHeight"></param>
    /// <param name="colspan"></param>
    /// <param name="rowspan"></param>
    public static void CreateCell(PdfPTable table, Image image, int minimumHeight = 3, int colspan = 0, int rowspan = 0)
    {
        var cell = new PdfPCell(image, true);// 是否填充
        cell.Padding = 5.5f; // 设置二维码在单元格中的边距
        cell.UseAscender = true;// 设置可以居中
        cell.MinimumHeight = minimumHeight;// 设置单元格高度
        cell.HorizontalAlignment = Element.ALIGN_CENTER;// 设置水平居中
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;// 设置垂直居中
        if (rowspan != 0)
        {
            cell.Rowspan = rowspan; //行合并
        }
        if (colspan != 0)
        {
            cell.Colspan = colspan; //列合并
        }
        table.AddCell(cell);
    }


    //生成二维码的路径
    public static string GetQRFileName()
    {
        return Path.Combine(GetOutputFolder(), $"Qr.jpg");
    }


    public static string GetOutputFolder()
    {
        var dir = Path.Combine(GetBaseDir(), "bin", "out");
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        return dir;
    }



    public static string GetOutputFolderPdf()
    {
        var dir = Path.Combine(GetBaseDir(), "bin", "outpdf\\");
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        return dir;
    }


    /// <summary>
    /// 验证pdf文件
    /// </summary>
    /// <param name="file"></param>
    public static void VerifyPdfFileIsReadable(byte[] file)
    {
        PdfReader reader = null;
        try
        {
            reader = new PdfReader(file);
            var author = reader.Info["Author"] as string;
            if (string.IsNullOrWhiteSpace(author) || !author.Equals(Author))
            {
                throw new InvalidPdfException("This is not a valid PDF file.");
            }
        }
        finally
        {
            reader?.Close();
        }
    }


    public static void VerifyPdfFileIsReadable(string filePath)
    {
        VerifyPdfFileIsReadable(File.ReadAllBytes(filePath));
    }


}

调用PdfUtils类,生成PDF文档

/// <summary>
/// 导出生成标签
/// </summary>
/// <returns></returns>
public bool ExportReceipt()
{
    try
    {
        // 生成二维码的内容
        QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();
        QRCodeData qrCodeData = qrGenerator.CreateQrCode("本代码来自www.luofenming.com", QRCodeGenerator.ECCLevel.Q);
        QRCode qrcode = new QRCode(qrCodeData);


        // GetGraphic 第一个参数设置图形的大小
        Bitmap qrCodeImage = qrcode.GetGraphic(3, Color.Black, Color.White, null, 15, 1, false);


        MemoryStream ms = new MemoryStream();
        qrCodeImage.Save(ms, ImageFormat.Jpeg);


        // 保存图片
        var ImgPath = PdfUtils.GetQRFileName();
        qrCodeImage.Save(ImgPath);


        // 保存pdf文件
        var pdfFilePath = PdfUtils.GetOutputFolderPdf() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
        if (File.Exists(Path.GetFullPath(pdfFilePath)))
        {
            File.Delete(Path.GetFullPath(pdfFilePath));
        }
        var fileStream = new FileStream(pdfFilePath, FileMode.Create);
        //var pdfDoc = new Document(PageSize.A4);
        var pdfDoc = new Document(new iTextSharp.text.Rectangle(226.4f, 169.8f)); // 80*60 mm
        var pdfWriter = PdfWriter.GetInstance(pdfDoc, fileStream);
        pdfDoc.SetMargins(0.2f, 0.2f, 3.2f, 0.2f);
        pdfDoc.AddAuthor(PdfUtils.Author);
        pdfDoc.Open();


        // 中文字体,解决中文不能显示问题
        BaseFont bfChinese = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\SIMSUN.TTC,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 五号
        iTextSharp.text.Font fiveFont = new iTextSharp.text.Font(bfChinese, 8f);   // 五号 10.5f 小三号 15
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ImgPath);
        // 新建表格 3列.
        PdfPTable table0 = new PdfPTable(3)
        {
            WidthPercentage = 98,// 宽度100%填充,
        };
        table0.DefaultCell.VerticalAlignment = Element.ALIGN_CENTER;


        // 设置列宽
        float[] columnWidths0 = { 0.4f, 0.8f, 0.8f };
        table0.SetWidths(columnWidths0);
        //正文第1行
        PdfUtils.CreateCell(table0, "姓名", fiveFont);
        PdfUtils.CreateCell(table0, "小明", fiveFont);
        PdfUtils.CreateCell(table0, image, 30, 0, 5);
        PdfUtils.CreateCell(table0, "学历", fiveFont);
        PdfUtils.CreateCell(table0, "大学", fiveFont);



        PdfUtils.CreateCell(table0, "年龄", fiveFont);
        PdfUtils.CreateCell(table0, "18", fiveFont);


        PdfUtils.CreateCell(table0, "地址", fiveFont);
        PdfUtils.CreateCell(table0, "江西九江", fiveFont);


        PdfUtils.CreateCell(table0, "民族", fiveFont);
        PdfUtils.CreateCell(table0, "汉", fiveFont);


        PdfUtils.CreateCell(table0, "个人网址", fiveFont);
        PdfUtils.CreateCell(table0, "www.luofenming.com", fiveFont, 0, 2);
        pdfDoc.Add(table0);
        pdfDoc.Close();
        fileStream.Dispose();


        PdfUtils.VerifyPdfFileIsReadable(pdfFilePath);
        //直接打开pdf文件
        System.Diagnostics.Process.Start(pdfFilePath);
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

源码下载链接: https://pan.baidu.com/s/1H6uJSB6EPnB2MtAwaQjVZg?pwd=abdp 提取码: abdp