.netcore 使用iTextSharp生成pdf文件

 

  • 使用Nuget添加iTextSharp引用

  • 主要代码
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using AutoMapper;
using System.Linq;
using System.Drawing;
using static iTextSharp.text.Font;
using System.Text;

namespace WebApi.Common.Service
{
    public class PdfService
    {


        private iTextSharp.text.Rectangle _pageSize = PageSize.A4;//设置pdf文档纸张大小
        string[] heads = new string[] { "标题1", "标题2", "标题3", "标题4", "标题5", "标题6" };
        string[] contents = new string[] { "内容1", "内容2", "内容3", "内容4", "内容5", "内容6" };


        private string _fontPath = @"C:\Windows\Fonts\simsun.ttc,0";//使itextsharp支持中文  "C:\\WINDOWS\\FONTS\\STSONG.TTF"
        private Font _columnHeaderFont;//标题字体
        private Font _contentFont;//内容字体
        private BaseFont _bsFont;
        private BaseColor ftColor = BaseColor.BLACK; //字体颜色
        string pdfFile = "D:\\a.pdf"; //生成pdf存放位置

        public PdfService()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            _bsFont = BaseFont.CreateFont(_fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            _columnHeaderFont = new Font(_bsFont, 12, 0, ftColor);
            _contentFont = new Font(_bsFont, 10, 0, ftColor);
        }

        public MemoryStream GeneralPdf()
        {
            // 创建新的PDF文档
            Document document = new Document(_pageSize);

            //设置距 左、右、上、下 边界 长度
            document.SetMargins(20,20,30,20);
              // 创建内存流用于存储生成的PDF
              MemoryStream stream = new MemoryStream();

            // 创建PDF写入器
            PdfWriter writer = PdfWriter.GetInstance(document, stream);
            PdfPTable table = new PdfPTable(heads.Length); // 指定标题列数

            FileStream fs = new FileStream(pdfFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            // 打开文档
            document.Open();
            // 添加内容到文档
            document.Add(new Paragraph("Hello, world!", _contentFont));
            document.Add(new Paragraph(" "));//插入换行符
            table.SplitRows = true;
            table.SplitLate = true;
            table.DefaultCell.BorderWidth = 1;
            table.DefaultCell.BorderColor = BaseColor.BLACK;
            table.WidthPercentage = 100; //显示缩放百分比
            // 添加表头
            AddRowCell(ref table, 1, heads.ToArray(), _columnHeaderFont, Element.ALIGN_CENTER, 50);
            //添加内容行
            AddRowCell(ref table, 1, contents.ToArray(), _contentFont, Element.ALIGN_CENTER, 30);

            // 将表格添加到文档
            document.Add(table);
            document.Close();

            byte[] result = stream.ToArray();
            fs.Write(result, 0, result.Length);

            stream.Close();
            fs.Close();
            writer.Close();
            return stream;
        }

        /// <summary>
        /// 向表格添加行
        /// </summary>
        /// <param name="table"></param>
        /// <param name="border"></param>
        /// <param name="content"></param>
        /// <param name="font"></param>
        /// <param name="horizontalAlignment">水平对齐方式</param>
        /// <param name="height">单元格高度</param>
        private void AddRowCell(ref PdfPTable table, int border, object[] content, Font font, int horizontalAlignment, float height)
        {
            if (content == null || content.Length == 0)
            {
                return;
            }
            foreach (var item in content)
            {
                PdfPCell pdfCell = new PdfPCell(new Phrase((string)item, font));
                if (border == 0)
                {
                    pdfCell.Border = border;
                }
                if (border > 0)
                {
                    pdfCell.BorderWidth = 1;
                }
                pdfCell.FixedHeight = height;
                pdfCell.HorizontalAlignment = horizontalAlignment;
                pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                table.AddCell(pdfCell);
            }
        }
    }
}
View Code

需要注意的是,itextsharp生成的表格中,默认是不支持中文的,需要添加中文支持,代码中已添加

  • 控制层调用
 [HttpGet("GetPdfInfo")]
        [ProducesResponseType(typeof(IActionResult), 200)]
        public IActionResult  GetPdfInfo()
        {
            try
            {
                PdfService pdfService = new PdfService();
               
                var stream = pdfService.GeneralPdf();
                if(stream != null)
                return    File(stream.ToArray(), "application/pdf", "example.pdf");
                else
                    return Ok(new WebApiResult(ApiResultCode.Fail, "参数有误",null));


            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

 

 

 

  本文生成pdf文件,支持接口方式调用或直接调用方法生成本地文件,如保存磁盘 D:\\example.pdf

 

posted @ 2023-09-07 21:50  低调码农哥!  阅读(203)  评论(0编辑  收藏  举报