首页 > 其他分享 >CSharp: create pdf file using iText 8.0 in donet 8.0

CSharp: create pdf file using iText 8.0 in donet 8.0

时间:2024-01-31 18:12:08浏览次数:29  
标签:SetTextAlignment 8.0 donet create iText Add Paragraph new TextAlignment

 

/*
 IDE: VS 2022 17.5
 OS: windows 10
 .net 8.0
 iText 8.0
System.Text.Encoding.CodePages 
 */

namespace ConsoleAppPdfdemo
{

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.IO;
    using System.Text;
    using iText.IO.Font;
    using iText.IO.Image;
    using iText.Kernel.Font;
    using iText.Kernel.Pdf;
    using iText.Kernel.Pdf.Canvas.Draw;
    using iText.Layout;
    using iText.Layout.Element;
    using iText.Layout.Properties;
    using iText.Pdfa;
    using iText.IO;
    using iText.Kernel.Pdf.Xobject;
    using iText.Kernel.Utils;
    using iText.Kernel.Events;
    using iText.Kernel.Colors;
    using iText.Kernel.Geom;
    using iText.Kernel.Pdf.Canvas;
    using iText.Layout.Borders;



    /// <summary>
    /// 
    /// </summary>
    internal class Program
    {


        /// <summary>
        /// geovindu, Geovin Du, 涂聚文
        /// 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            try
            {




                Console.WriteLine("Hello,CSharp World!");

                string baseurl = Environment.CurrentDirectory.ToString() + "\\";
                Console.WriteLine(baseurl);
                //字体设定,c:\windows\fonts\kaiu.ttf,中文楷体
                string filePath = baseurl + @"sRGB_CS_profile.icm";
                string fontFile = @"c:\windows\fonts\kaiu.ttf";
                string fontFile2 = baseurl + @"font\\MHeiHK-Light.TTF";
                string fileName = baseurl+@"sample\\" + DateTime.Now.ToString("yyyyMMHHmmss") + ".pdf";


                List<Orders> orders = new List<Orders>();
                Orders order = new Orders();
                order.productId = 1;
                order.product = "中國電器";
                order.qty = 50;
                order.price = 52.0;
                orders.Add(order);

                order = new Orders();
                order.productId = 2;
                order.product = "日本電器";
                order.qty = 150;
                order.price = 252.0;
                orders.Add(order);

        
                //PdfADocument pdf = new PdfADocument(
                //new PdfWriter(fileName),
                //PdfAConformanceLevel.PDF_A_1B,
                //new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1",
                // new FileStream(filePath, FileMode.Open, FileAccess.Read)));

                PdfDocument pdf = new PdfDocument(new PdfWriter(new FileStream(fileName, FileMode.Create, FileAccess.Write)));


                //FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                //PdfReader reader=new PdfReader(stream);
                //PdfADocument pdf = new PdfADocument(reader, new PdfWriter(fileName));     
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //必须加这一行

                //中文 字體和文字要相適應
                //FontProgramFactory.CreateFont(fontFile);
                PdfFont font = PdfFontFactory.CreateFont(fontFile2, PdfEncodings.IDENTITY_H);//PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED
                Document document = new Document(pdf, iText.Kernel.Geom.PageSize.A4);

                document.SetFont(font);


                //指定位置添加图片  images\luflog20180410145504.png
                //PdfContentByte pcb1 = writer.DirectContent;

                //image1.SetAbsolutePosition(12, 18); //底部
                PdfImageXObject xObject = new PdfImageXObject(ImageDataFactory.Create(baseurl + "images/luflog20180410145504.png"));
                iText.Layout.Element.Image image1 = new iText.Layout.Element.Image(xObject, 200);
                // ColumnText ct = new ColumnText(pcb1);
                image1.ScaleAbsolute(148, 50);
                //pcb1.AddImage(image1);     
                //Resize image depend upon your need
                image1.ScaleToFit(140f, 120f);

                //p = new Paragraph(new Chunk(image1, 10f, 10f));
                iText.Layout.Element.Table datatable = new iText.Layout.Element.Table(5, true); //5列                

                Cell pCTitle = new Cell(1, 5).SetBorder(iText.Layout.Borders.Border.NO_BORDER);//无边
                Paragraph p = new Paragraph().SetTextAlignment(TextAlignment.CENTER);
                p.Add(image1.SetTextAlignment(TextAlignment.CENTER));
                pCTitle.Add(p);
                datatable.AddCell(pCTitle);
                document.Add(datatable);




                Paragraph header = new Paragraph("ORDER DETAIL 顧客塗聚文訂單詳情").SetTextAlignment(TextAlignment.CENTER).SetFontSize(20);
                document.Add(header);

                Paragraph subheader = new Paragraph("C# WINDOWS FORM CREATE PDF DOCUMENT USING iTEXT7 LIBRARY").SetTextAlignment(TextAlignment.CENTER).SetFontSize(10);
                document.Add(subheader);

                LineSeparator ls = new LineSeparator(new SolidLine());
                document.Add(ls);

                Paragraph sellerHeader = new Paragraph("Sold by:").SetBold().SetTextAlignment(TextAlignment.LEFT);
                Paragraph sellerDetail = new Paragraph("Seller Company").SetTextAlignment(TextAlignment.LEFT);
                Paragraph sellerAddress = new Paragraph("Shenzhen city, Guangdong China").SetTextAlignment(TextAlignment.LEFT);
                Paragraph sellerContact = new Paragraph("+86 1000000000").SetTextAlignment(TextAlignment.LEFT);

                document.Add(sellerHeader);
                document.Add(sellerDetail);
                document.Add(sellerAddress);
                document.Add(sellerContact);

                Paragraph customerHeader = new Paragraph("Customer details:").SetBold().SetTextAlignment(TextAlignment.RIGHT);
                Paragraph customerDetail = new Paragraph("Customer ABC").SetTextAlignment(TextAlignment.RIGHT);
                Paragraph customerAddress1 = new Paragraph("Buxin 1008, shuibei Jewellery Builder").SetTextAlignment(TextAlignment.RIGHT);
                Paragraph customerAddress2 = new Paragraph("Shenzhen 518019, Guangdong China").SetTextAlignment(TextAlignment.RIGHT);

                Paragraph customerContact = new Paragraph("+85 0000000000").SetTextAlignment(TextAlignment.RIGHT);

                document.Add(customerHeader);
                document.Add(customerDetail);
                document.Add(customerAddress1);
                document.Add(customerAddress2);
                document.Add(customerContact);

                Paragraph orderNo = new Paragraph("Order No:15484659").SetBold().SetTextAlignment(TextAlignment.LEFT);
                Paragraph invoiceNo = new Paragraph("Invoice No:MH-MU-1077").SetTextAlignment(TextAlignment.LEFT);
                Paragraph invoiceTimestamp = new Paragraph("Date: 01/01/2024 04:25:37 PM").SetTextAlignment(TextAlignment.LEFT);

                document.Add(orderNo);
                document.Add(invoiceNo);
                document.Add(invoiceTimestamp);

                iText.Layout.Element.Table table = new iText.Layout.Element.Table(5, true);

                table.SetFontSize(9);
                Cell headerProductId = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("ID"));
                Cell headerProduct = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("產品名稱"));
                Cell headerProductPrice = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("價格"));
                Cell headerProductQty = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("數量"));
                Cell headerTotal = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("合計"));

                table.AddCell(headerProductId);
                table.AddCell(headerProduct);
                table.AddCell(headerProductPrice);
                table.AddCell(headerProductQty);
                table.AddCell(headerTotal);

                double grandTotalVal = 0;
                foreach (Orders c in orders)
                {
                    Cell productid = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.productId.ToString()));
                    Cell product = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.product));
                    Cell price = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.price.ToString()));
                    Cell qty = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.qty.ToString()));
                    var value = c.price * c.qty;
                    Cell total = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(value.ToString()));

                    grandTotalVal += value;
                    table.AddCell(productid);
                    table.AddCell(product);
                    table.AddCell(price);
                    table.AddCell(qty);
                    table.AddCell(total);
                }

                Cell grandTotalHeader = new Cell(1, 4).SetTextAlignment(TextAlignment.RIGHT).Add(new Paragraph("合計: "));
                Cell grandTotal = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(" " + grandTotalVal.ToString()));

                table.AddCell(grandTotalHeader);
                table.AddCell(grandTotal);

                document.Add(table);


                //底部
                float[] tableWidth = { 445, 50F };
                iText.Layout.Element.Table footerTable = new iText.Layout.Element.Table(5).SetFixedPosition(20F, 25F, 780F).SetBorder(iText.Layout.Borders.Border.NO_BORDER);

                PdfImageXObject xObject2 = new PdfImageXObject(ImageDataFactory.Create(baseurl + "images/lufaddress_20180410145531.png"));
                iText.Layout.Element.Image image2 = new iText.Layout.Element.Image(xObject2, 500);
                //image2.SetMarginBottom(18); //底部
                //image2.ScaleAbsolute(585, 40);
                image2.SetTextAlignment(TextAlignment.LEFT);
                Paragraph p2 = new Paragraph().SetTextAlignment(TextAlignment.LEFT);
                p2.Add(image2.SetTextAlignment(TextAlignment.LEFT));

                Cell cfoot = new Cell(1, 5).SetBorder(iText.Layout.Borders.Border.NO_BORDER); //离得远
                cfoot.Add(p2);
                footerTable.AddCell(cfoot).SetTextAlignment(TextAlignment.LEFT);
                document.Add(footerTable);


                // document.Add(image2);

                table.Flush();
                table.Complete();
                document.Close();

                Console.WriteLine(fileName);




            }
            catch(Exception ex)
            { 
                Console.WriteLine(ex.ToString());
            }
           





        }
    }

    /// <summary>
    /// 订单实体类
    /// </summary>
    public class Orders
    {
        /// <summary>
        /// ID
        /// </summary>
        public int productId { get; set; }
        /// <summary>
        /// 产品名称
        /// </summary>
        public string product { get; set; }
        /// <summary>
        /// 数量
        /// </summary>
        public int qty { get; set; }
        /// <summary>
        /// 价格
        /// </summary>
        public double price { get; set; }
    }


}

  

 

标签:SetTextAlignment,8.0,donet,create,iText,Add,Paragraph,new,TextAlignment
From: https://www.cnblogs.com/geovindu/p/17999859

相关文章

  • 数据库研发人员必看的MySQL 8.0新特性
    本文汇总了MySQL8.0面向开发的新特性,总共有12个新特性,有想快速了解8.0新特性的朋友,可以看一下哈文章目录:1.公用表达式支持-CTE2.窗口函数3.表达式作为默认值:4.CHECK支持5.隐藏列-MySQL8.0.236.隐藏索引、降序索引、函数索引(MySQL-8.0.19)7.VALUES语法8.INTERSECT和EXC......
  • MySQL Shell 8.0.32 for GreatSQL编译二进制包
    MySQLShell8.0.32forGreatSQL编译二进制包构建MySQLShell8.0.32forGreatSQL0.写在前面之前已经写过一篇前传MySQLShell8.0.32forGreatSQL编译安装,最近再次编译MySQLShell二进制包时,发现了一些新问题,因此重新整理更新本文档。1.几处新问题这次编译MySQLShe......
  • createDelegatingPasswordEncoder只有在spring 5.1.13才能用吗?
    springboot和spring版本对应关系:SpringBoot1.x支持SpringFramework4.x系列,包括4.0、4.1、4.2和4.3等版本。SpringBoot2.x支持SpringFramework5.x系列,包括5.0、5.1和5.2等版本。 下载springboot会一并下载 ......
  • epoll_create函数
    目录函数简介低层实现逻辑epoll_create与epoll_create1函数的区别函数简介/*Createsanepollinstance.Returnsanfdforthenewinstance.The"size"parameterisahintspecifyingthenumberoffiledescriptorstobeassociatedwiththenewinstance.......
  • CSharp: iText 8.0 in donet 4.8.1
     usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.IO;usingSystem.Text;usingiText.IO.Font;usingiText.IO.Image;usingiText.Kernel.Font;usingiTe......
  • .Net Core3.1 升级到8.0(3.1升级到更高版本)
    NETCore3.1已经用了很长一段时间,其实在2022年的年底微软已经不提供支持了,后面的一个 LTS 版本.NET6也会在2024年11月终止支持,所以直接升级到.NET8是最好的选择。微软官方推出了升级工具:UpgradeAssistant,链接地址如下:https://dotnet.microsoft.com/zh-cn/plat......
  • MySQL-8.0.30升级MySQL-8.0.34
    记录一次MySQL漏洞升级操作升级背景:OracleMySQL官方发布MySQL-8.0.30版本高危漏洞CVE-2022-32221、CVE-2022-37434等,受影响版本涉及到8.0.32,官方建议升级至8.0.33,最好使用8.0.34,这里我们将MySQL-8.0.30升级至MySQL-8.0.34版本方案:将原mysql目录重命名,解压新的程序目录软链接到......
  • 【极简】conda同一个服务器上迁移环境 export / create
    导出直接看conda的document:https://docs.conda.io/projects/conda/en/latest/commands/env/export.htmlcondaenvexportcondaenvexport--fileSOME_FILE重建condadocumentation:https://docs.conda.io/projects/conda/en/latest/commands/env/create.htmlcondaenvc......
  • ubuntu18.04 局域网配置git server步骤
    1.安装ssh2.安装gitsudoapt-getupdatesudoaptinstallvimsudoaptinstallopenssh-serversudoaptinstallgit3.cdhome目录mkdircodecdcodegitinit--baretest.git#创建git-server仓库远程服务器远程地址:/home/joker/code/test.git4.本地电脑目录操作......
  • ubuntu18.04 配置1920 1080
    添加/etc/X11/xorg.conf文件,将此模式保存为默认分辨率。1、$sudovim/etc/X11/xorg.conf(如果没有安装vim,可以使用“sudogedit/etc/X11/xorg.conf”)粘贴以下内容:Section"Monitor"Identifier"ConfiguredMonitor"Modeline"1920x1080_60.00"173.0019202......