zoukankan      html  css  js  c++  java
  • .NET Core 使用PDF打印

    第一种方式  套打 (先做好PDF模版  在程序中只是填充数据)

    1.先用word制作好模版  然后另存为pdf格式

    2.下载adobe acrobat pro   

    3.选择工具    准备表单   会自动把没有内容的td单元格   还有___  这种可以填的地方设置key值

    4.需要导入iTextsharp这个包  如果没有就导入  iTextSharp.LGPLv2.Core

            public FileResult DemoViewAsPdf()
            {
                //return null;
                //获取中文字体,第三个参数表示为是否潜入字体,但只要是编码字体就都会嵌入。
                BaseFont baseFont = BaseFont.CreateFont(@"C:WindowsFontssimsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //读取模板文件
                PdfReader reader = new PdfReader(@"C:UsersjiangchengbiaoDesktop第一个打印文档.pdf");
    
                //创建文件流用来保存填充模板后的文件
                MemoryStream stream = new MemoryStream();
    
                PdfStamper stamp = new PdfStamper(reader, stream);
                //设置表单字体,在高版本有用,高版本加入这句话就不会插入字体,低版本无用
                //stamp.AcroFields.AddSubstitutionFont(baseFont);
    
                AcroFields form = stamp.AcroFields;
    
                //表单文本框是否锁定
                stamp.FormFlattening = true;
    
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("name", "蒋承标");
                para.Add("age", "22");
                para.Add("sex", "");
                para.Add("identity", "330328");
    
                //填充表单,para为表单的一个(属性-值)字典
                foreach (KeyValuePair<string, string> parameter in para)
                {
                    //要输入中文就要设置域的字体;
                    form.SetFieldProperty(parameter.Key, "textfont", baseFont, null);
                    //为需要赋值的域设置值;
                    form.SetField(parameter.Key, parameter.Value);
                }
    
                //按顺序关闭io流
    
                stamp.Close();
                reader.Close();
                //生成文件
                FileResult fileResult = new FileContentResult(stream.ToArray(), "application/pdf");
                //设置了这个属性就是下载
                //fileResult.FileDownloadName = "4.pdf";
                return fileResult;
            }

     这个action一定要是get请求的     这样才可以直接通过windows.open()请求

    前端只需要 window.open("这个action的地址")  就可以直接显示或者下载这个pdf文档

    ***********************

    在程序中生成PDF

      添加iTextSharp.LGPLv2.Core包

    
    
                string filePath = @"D:pdf";
                //实例化在当前目录 创建 移动的实例方法
                DirectoryInfo dirTime = new DirectoryInfo(filePath);
    
                //如果目录不存在  则创建
                if (!dirTime.Exists)
                {
                    dirTime.Create();
                }
                //获取当前目录中文件的数量
                string name = dirTime.GetFiles().Length + 1 + ".pdf";
                filePath = filePath + name;
                //这个就是流对象  对于这种操作IO的  最后都需要清空流对象
                var stream = new FileStream(filePath, FileMode.Create);
                Document document = new Document(PageSize.A4, 5f, 5f, 30f, 0f);
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
    try
                {
                    document.Open();
    
                    PdfPTable table = new PdfPTable(5);
                    table.TotalWidth = 550;
                    table.LockedWidth = true;
                    table.SetWidths(new int[] { 65, 55, 60, 45, 170 });
                    PdfPCell cell;
                    BaseFont bfChinese = BaseFont.CreateFont(@"C:WindowsFontssimsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    iTextSharp.text.Font fontChinese_11 = new iTextSharp.text.Font(bfChinese, 15, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(0, 0, 0));
                    iTextSharp.text.Font fontChinese_10 = new iTextSharp.text.Font(bfChinese, 10, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 0));
                    iTextSharp.text.Font fontChinese_bold = new iTextSharp.text.Font(bfChinese, 8, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(0, 0, 0));
                    iTextSharp.text.Font fontChinese_8 = new iTextSharp.text.Font(bfChinese, 8, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 0));
                    iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 0));
                    //黑体
                    BaseFont bf_ht = BaseFont.CreateFont(@"C:WindowsFontssimsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    iTextSharp.text.Font ht_7 = new iTextSharp.text.Font(bf_ht, 7, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 0));
    
                    //公司名称
                    cell = new PdfPCell(new Phrase("XXXXXXXX设备有限公司", fontChinese_11));
                    cell.Colspan = 5;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Border = Rectangle.NO_BORDER;
                    table.AddCell(cell);
                    //document.Add(table);
    
                    //订单类型
                    cell = new PdfPCell(new Phrase("发货单", fontChinese_11));
                    cell.Colspan = 5;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Border = Rectangle.NO_BORDER;
                    table.AddCell(cell);
                    //document.Add(table);
    
                    //单据信息
                    var salesorder = GetSalesOrder();
    
                    string str = " 客户:" + salesorder.CustomerName + "  电话:" + salesorder.Phone +"  时间:"+salesorder.OrderDate;
                    cell = new PdfPCell(new Phrase(str, fontChinese));
                    cell.Colspan = 6;
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Border = Rectangle.NO_BORDER;
                    cell.Padding = 5;
                    cell.PaddingLeft = 0;
                    table.AddCell(cell);
                    document.Add(table);
                    //str = "出货:" + todate + " 开单:" + model.Osaleh.osaleh_mkdateString + " ECMS单号:" + model.Osaleh.osaleh_osalehID + "";
                    //cell = new PdfPCell(new Phrase(str, fontChinese));
                    //cell.Colspan = 2;
                    //cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    //cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    //cell.Border = Rectangle.NO_BORDER;
                    //cell.Padding = 5;
                    //table.AddCell(cell);
    
    
                    table = new PdfPTable(3);
                    table.TotalWidth = 550;
                    table.LockedWidth = true;
                    table.SetWidths(new int[] { 250, 150, 150 });
    
                    cell = new PdfPCell(new Phrase("送货地址:" + salesorder.Address, fontChinese));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 5;
                    table.AddCell(cell);
    
                    cell = new PdfPCell(new Phrase("订单号:" + salesorder.Name, fontChinese));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 5;
                    table.AddCell(cell);
    
                    cell = new PdfPCell(new Phrase("付款方式:" + salesorder.PayMethonText, fontChinese));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 5;
                    table.AddCell(cell);
    
                    document.Add(table);
    
    
    
                    table = new PdfPTable(6);
                    table.TotalWidth = 550;
                    table.LockedWidth = true;
                    table.SetWidths(new int[] { 65, 55,100, 60, 45, 70 });
    
                    cell = new PdfPCell(new Phrase("序号", fontChinese));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 5;
                    table.AddCell(cell);
    
                    cell = new PdfPCell(new Phrase("物料号", fontChinese));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 5;
                    table.AddCell(cell);
    
                    cell = new PdfPCell(new Phrase("物料名称", fontChinese));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 5;
                    table.AddCell(cell);
    
                    cell = new PdfPCell(new Phrase("单位", fontChinese));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 5;
                    table.AddCell(cell);
    
                    cell = new PdfPCell(new Phrase("数量", fontChinese));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 5;
                    table.AddCell(cell);
    
                    cell = new PdfPCell(new Phrase("订单号", fontChinese));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 5;
                    table.AddCell(cell);
                    document.Add(table);
    
                    List<SalesOrderLine> sendLineList = GetOrderLineList();
    
                    foreach (var item in sendLineList)
                    {
                        table = new PdfPTable(6);
                        table.TotalWidth = 550;
                        table.LockedWidth = true;
                        table.SetWidths(new int[] { 65, 55,100, 60, 45, 70 });
    
                        cell = new PdfPCell(new Phrase(item.LineNumber.ToString(), fontChinese));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                        cell.Padding = 5;
                        table.AddCell(cell);
    
                        cell = new PdfPCell(new Phrase(item.ProductNumber, fontChinese));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                        cell.Padding = 5;
                        table.AddCell(cell);
    
                        cell = new PdfPCell(new Phrase(item.ProductName, fontChinese));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                        cell.Padding = 5;
                        table.AddCell(cell);
    
                        cell = new PdfPCell(new Phrase(item.ProductUnit, fontChinese));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                        cell.Padding = 5;
                        table.AddCell(cell);
    
                        cell = new PdfPCell(new Phrase(item.Quantity.ToString(), fontChinese));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                        cell.Padding = 5;
                        table.AddCell(cell);
    
                        cell = new PdfPCell(new Phrase(item.SalesOrderName, fontChinese));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                        cell.Padding = 5;
                        table.AddCell(cell);
                        document.Add(table);
                    }
    
    
    
                    string accumamtToUpper = salesorder.Money.ToString();
                    Phrase phrase = new Phrase();
                    phrase.Add(new Chunk("  实收金额:", fontChinese));
                    phrase.Add(new Chunk(accumamtToUpper, fontChinese));
                    cell = new PdfPCell(phrase);
                    cell.Colspan = 6;
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.Padding = 8;
                    table.AddCell(cell);
                    document.Add(table);
                    //iTextSharp.text.Rectangle pageSize = document.PageSize;
                    //document.SetPageSize(pageSize);
                    //document.NewPage();
                    document.Close();
                    stream.Dispose();
    
                    return new  JsonResult("1123") { };
                }
                catch (Exception)
                {
    
                    throw;
                }
                finally
                {
                    document.Close();
                    stream.Dispose();
                }
            private List<SalesOrderLine> GetOrderLineList()
            {
                List<SalesOrderLine> sendLineList = new List<SalesOrderLine>();
                sendLineList.Add(new SalesOrderLine() { LineNumber=1,ProductNumber ="P147",ProductUnit = "PCS",Quantity =5,SalesOrderName = "S123",ProductName = "净水器1"});
                sendLineList.Add(new SalesOrderLine() { LineNumber = 2, ProductNumber = "P148", ProductUnit = "PCS", Quantity = 20, SalesOrderName = "S123", ProductName = "饮水机" });
                sendLineList.Add(new SalesOrderLine() { LineNumber = 3, ProductNumber = "P178", ProductUnit = "PCS", Quantity = 5, SalesOrderName = "S123", ProductName = "笔记本" });
                sendLineList.Add(new SalesOrderLine() { LineNumber = 4, ProductNumber = "P897", ProductUnit = "PCS", Quantity = 8, SalesOrderName = "S123", ProductName = "化妆品" });
                sendLineList.Add(new SalesOrderLine() { LineNumber = 5, ProductNumber = "P698", ProductUnit = "PCS", Quantity = 1, SalesOrderName = "S123", ProductName = "净水器1" });
                return sendLineList;
    
            }
    
            private SalesOrder GetSalesOrder()
            {
                SalesOrder salesOrder = new SalesOrder();
                salesOrder  = (new SalesOrder() { OrderDate = DateTime.Now, Name = "S123456789", Money = 1999, CustomerName = "蒋承标",Phone = "15068271465",PayMethonText = "支付宝",Address="浙江省温州市白鹭屿" });
                return salesOrder;
    
            }

    ***************用第二种方式在程序中动态生成PDF后   如果出现下面这种问题 IO流没有关闭  看看上面的stream流对象有没有调用Dispose()

      

    具体案例可以在github上找

    https://www.jianshu.com/p/d518d0988621

  • 相关阅读:
    "Data truncated for column"错误
    PHP连接mysql数据库的代码
    JQuery使用手册
    Search does not work with Anonymous Access(匿名访问搜索无任何结果)
    完美解决MySQL中文乱码
    转:大型高性能ASP.NET系统架构设计
    团队作业8第二次项目冲刺(Beta阶段) 第一天
    团队作业5——测试与发布(Alpha版本)
    2pc和3pc区别
    在linux下使用百度ueditor编辑器上传图片
  • 原文地址:https://www.cnblogs.com/jiangchengbiao/p/10605290.html
Copyright © 2011-2022 走看看