首页 > 其他分享 >CSharp: iText 8.0 in donet 4.8.1

CSharp: iText 8.0 in donet 4.8.1

时间:2024-01-30 18:15:05浏览次数:28  
标签:SetTextAlignment 8.0 4.8 iText Add Paragraph new TextAlignment

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
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;



namespace WebAppPdfDemo
{


    /// <summary>
    /// iText 8.0
    /// 
    /// </summary>
    public partial class WebForm1 : System.Web.UI.Page
    {


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {


            try
            {

                //字体设定,c:\windows\fonts\kaiu.ttf,中文楷体
                string filePath = Server.MapPath(@"sRGB_CS_profile.icm");
                string fontFile = @"c:\windows\fonts\kaiu.ttf";
                string fontFile2 = Server.MapPath(@"font\\MHeiHK-Light.TTF");
                string fileName = Server.MapPath(@"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));     


                //中文 字體和文字要相適應
                //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(Server.MapPath("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("Mumbai, Maharashtra India").SetTextAlignment(TextAlignment.LEFT);
                Paragraph sellerContact = new Paragraph("+91 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("R783, Rose Apartments, Santacruz (E)").SetTextAlignment(TextAlignment.RIGHT);
                Paragraph customerAddress2 = new Paragraph("Mumbai 400054, Maharashtra India").SetTextAlignment(TextAlignment.RIGHT);

                Paragraph customerContact = new Paragraph("+91 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: 30/05/2021 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(Server.MapPath("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();
                Response.Charset = "utf-8";//设置输出流的字符集-中文
                Response.ContentType = "application/pdf";
                // Response.Write(fileName);

                MemoryStream m = new MemoryStream();
                FileStream fs = new FileStream(fileName, FileMode.Open);
                fs.CopyTo(m);
                Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
                Response.OutputStream.Flush();
                Response.OutputStream.Close();

                //自动下载
                //Response.Clear();
                //Response.ContentType = "application/pdf";
                //Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
                //Response.TransmitFile(fileName);
                //Response.End();


            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                Response.Write(ex.Message.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,4.8,iText,Add,Paragraph,new,TextAlignment
From: https://www.cnblogs.com/geovindu/p/17997684

相关文章

  • .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目录重命名,解压新的程序目录软链接到......
  • 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......
  • 【18.0】MySQL进阶知识之函数
    【一】什么是函数跟存储过程是有区别的,存储过程是自定义函数,函数就类似于内置函数注意与存储过程的区别,mysql内置的函数只能在sql语句中使用!【二】字符串函数【0】介绍CONCAT(str1,str2,...):将多个字符串连接成一个字符串。SUBSTRING(str,start,length):返回字符......
  • 【亲测管用】Linux环境下MySQL 8.0重置密码
    这个问题折磨了我有两三个小时了,看了一大堆博客,大多数都不好用,真的怀疑有没有亲自试用过。本文使用的服务器为阿里云的服务器Linux系统,MySQL的版本为8.0。修改密码操作如下,供大家参考:在/etc/my.cnf中添加如下代码,使其支持免密登录[mysqld]skip-grant-tables重启MySQL服......
  • Mysql数据库更新RedHat/CentOS 从 8.0.14 到 8.0.33,又从8.0.33更新到8.0.35
    sudosystemctlstartmysqldFirstlyweneedbackupalldatabasedataintonewfile,IuseTestPortal.sql/data/VMs_Share/Homes/bell-bash-4.2$mysqldump-uroot-p--databasesTestPortal>TestPortal.sqlEnterpassword:-bash-4.2$2.downloadtheve......
  • MySQL 8.0.26 新增参数 group_replication_view_change_uuid
    MySQL8.0.26新增参数group_replication_view_change_uuidGreatSQL[root@localhost][test]>showglobalvariableslike'group_replication_view_change_uuid';+------------------------------------+-----------+|Variable_name|V......
  • ES 8.0 服务安装
     文章目录1、开发环境操作系统1.1选择Windows、MacorLinux1.2选择虚拟机还是本地安装2、学习ES8Java版本如何选择2.1ES与JDK兼容性2.2Java下载2.3不同系统下Java环境的安装3、下载和安装ES3.1SDK下载地址3.2Elasticsearch目录结构4、单节......
  • The artifact mysql:mysql-connector-java:jar:8.0.33 has been relocated to com.mys
    Theartifactmysql:mysql-connector-java:jar:8.0.33hasbeenrelocatedtocom.mysql:mysql-connector-j:jar:8.0.33:MySQLConnector/Jartifactsmovedtoreverse-DNScompliantMaven2+coordinates.1.异常信息Theartifactmysql:mysql-connector-java:jar:8.0.33hasb......