首页 > 其他分享 >.netcore 使用iTextSharp生成pdf文件

.netcore 使用iTextSharp生成pdf文件

时间:2023-09-07 21:55:04浏览次数:34  
标签:stream using netcore new iTextSharp table pdf document

 

  • 使用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

 

标签:stream,using,netcore,new,iTextSharp,table,pdf,document
From: https://www.cnblogs.com/personblog/p/17686159.html

相关文章

  • 原创软件 | 第3期:PDF合并分割助手V1.0(个人免费)
    这是一个短的“发布会”。 01基本介绍近期开发了一个【PDF合并分割助手】。它是一个实现pdf快速合并、分割的免费软件。你拥有以下7种选项设置。>>合并选项<<1保留书签,顶层书签以pdf文件名(不含“.pdf”)构建2保留原始书签,顶层书签与源文档相同3纯合并内容,丢弃所有源文......
  • 在uniapp中如何将PDF或者XML文件转化成base64?
    场景:如何将获取到的内网服务器的文件,传给我们的后台,把文件保存下来?1.使用uni.downloadFile()获取到文件的临时路径2.uniapp导入安装的的插件“image-tools”,把临时路径转化成base64传给后台。注意点:如果同时解析多个xml文件,后台可能会接收到乱码的情况,此时需要将base64使用enc......
  • 多个word转化成PDF文件后再合并成一个PDF文件
    """**将多个word文档转化成PDF文件,最后合并成一个PDF文件**"""`importosfromwin32comimportclientfromPyPDF2importPdfMerger#使用PdfMergerdefwordToPdf(folder):#将多个word文档转化成PDF文件os.chdir(folder)file_type='docx&#......
  • AspNetCore依赖注入在控制台的应用
    ①安装包:Microsoft.Extensions.DependencyInjection②应用主方法里面://接口IService,实现:Service,方法:Execute();varserviceProvider=newServiceCollection().AddSingleton<IService,Service>().BuildServiceProvider();var......
  • 基于Swing实现的PDFViewer
    最近因项目需求,需要使用Swing实现PDFViewer,并且需要鼠标拖动,放大缩小等操作,一开始在网上也找到了PDF-Renderer,但是一看原理,不也就是将PDF文件转化为image而已,目前解决掉了拖动以及放大缩小的BUG问题。如下使用apache-pdfbox转换的PDF,当然也可以替换为iText或者别的依赖代码如下:......
  • PDF 补丁丁 1.0 正式版
    经过了一年多的测试和完善,PDF补丁丁发布第一个开放源代码的正式版本了。PDF补丁丁也是国内首先开放源代码、带有修改和阅读PDF的功能的 PDF处理程序之一。源代码网址:https://github.com/wmjordan/PDFPatcher软件简介及下载连接。 新增功能:第一个开放源代码版本。修......
  • .NetCore——全局异常过滤器ExceptionFilterAttribute
    .NetCore——全局异常过滤器ExceptionFilterAttribute一、介绍在我们的项目运行中,当程序出现异常的时候就会弹窗大黄页,所以为了更方便的解决这个问题,我们采用全局过滤器ExceptionFilterAttribute。通过它主动捕获程序中的异常,然后经过处理再抛出信息。下面咱们直接上干货,撸起来......
  • 【专题】2023AIGC应用与实践展望报告PDF合集分享(附原数据表)
    原文链接:https://tecdat.cn/?p=33544自2022年11月ChatGPT发布以来,其超出预期的“涌现”能力彻底点燃了AIGC赛道。从人力资源角度来看,AIGC相关职位数量明显增加,并且人才对于这些职位的投递也更加积极。阅读原文,获取专题报告合集全文,解锁文末190份AIGC行业相关报告。值得注意的是,A......
  • 【专题】AIGC技术给教育数字化转型带来的机遇与挑战报告PDF合集分享(附原数据表)
    原文链接:https://tecdat.cn/?p=33544自2022年11月ChatGPT发布以来,其超出预期的“涌现”能力彻底点燃了AIGC赛道。从人力资源角度来看,AIGC相关职位数量明显增加,并且人才对于这些职位的投递也更加积极。阅读原文,获取专题报告合集全文,解锁文末190份AIGC行业相关报告。值得注意的是,A......
  • 【专题】2023年AIGC行业调研报告PDF合集分享(附原数据表)
    原文链接:https://tecdat.cn/?p=33544自2022年11月ChatGPT发布以来,其超出预期的“涌现”能力彻底点燃了AIGC赛道。从人力资源角度来看,AIGC相关职位数量明显增加,并且人才对于这些职位的投递也更加积极。阅读原文,获取专题报告合集全文,解锁文末190份AIGC行业相关报告。值得注意的是,A......