• 利用itextSharp(v4.1版本)导出 pdf不能打开问题


    最近项目上客户要求导出pdf报表,用一个以前写好的代码,在本地跑起来没任何问题,本地环境(WIn7)

    放在服务器上就不行了,服务器(Win2003),折腾了几天,逐个排查,发现是由于调用了字体导致的,本地环境有字体,

    而服务器是在国外,英文版的没有这个字体(SIMFANG.TTF),解决办法把这个字体拷贝到服务器上c:WINDOWSfonts下,

    不知道新版本怎么样?

    (

     public virtual Font FontBase
            {
                get
                {
                    BaseFont bf = BaseFont.CreateFont(@"c:WINDOWSfontsSIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    return new Font(bf, CONTENT_FONT_SIZE);
                }
            }

    )

    在绘制表格时调用:PdfPCell pHCustomerCode = new PdfPCell(new Paragraph("客户代码", FontBase));这句,奇怪的是生成时没有异常,

    最后排查发现是字体没有导致的。我晕。。。第三方的东西使用必须谨慎啊。

    代码实现如下:所有PDF基类,

    using System;
    using System.Collections.Generic;
    using System.Text;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using System.IO;
    
    
    namespace CommonLibrary.Report.Base
    {
        /// <summary>
        /// 名    称: PDF报表的基类
        /// 功能概要: 凡是创建PDF报表,都需要从此类继承
        /// 作    者: Lucifer
        /// 创建时间: 2013年12月2日11:22:17
        /// 修正履历: 
        /// 修正时间: 
        /// </summary>
        public abstract class ReportBase<T, U> where T :iTextSharp.text.IElement
        {
            protected const int SUBJECT_FONT_SIZE = 18;
            protected const int CONTENT_FONT_SIZE = 12;
            private string fileName;
            public virtual string FileName
            {
                get { return fileName; }
                set { fileName = value; }
            }
            private Document doc = null;
            public virtual Paragraph GetReportSubject(string subject)
            {
                BaseFont bf = BaseFont.CreateFont(@"c:WINDOWSfontsSIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font f = new Font(bf, SUBJECT_FONT_SIZE);
                Paragraph p = new Paragraph(subject, f);
                p.Font = f;
                p.Alignment = Element.ALIGN_CENTER;
                return p;
            }
    
            public virtual Font FontBase
            {
                get 
                {
                    BaseFont bf = BaseFont.CreateFont(@"c:WINDOWSfontsSIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    return new Font(bf, CONTENT_FONT_SIZE);
                }
            }
            public abstract T GetReportHeader(U u) ;
            public abstract T GetReportContent(U u);
            public abstract T GetReportFooter(U u) ;
            public abstract T GetReportObject(U u) ;
    
            public virtual void CreateReport(U u,string title,string subject)
            {
                Rectangle r = PageSize.A4;
                float left = 10;
                float right = 10;
                float top = 50;
                float bottom = 30;
                this.CreateReport(u,title,subject, r, left, right, top, bottom);
            }
            public virtual void CreateReport(U u, Rectangle r,string title,string subject)
            {
                float left = 10;
                float right = 10;
                float top = 50;
                float bottom = 30;
                this.CreateReport(u, title, subject, r, left, right, top, bottom);
            }
            public virtual void CreateReport(U u,string reportTitle,string reportSubject, Rectangle r, float marginLeft, float marginRight, float marginTop, float marginBottom)
            {
                doc = new Document(r, marginLeft, marginRight, marginTop, marginBottom);
                if(String.IsNullOrEmpty(this.FileName))
                {
                    throw new Exception ("报表名称不能为空!");
                }
                PdfWriter.GetInstance(doc,new FileStream(this.FileName,FileMode.Create));
                doc.Open();
    
                if (!String.IsNullOrEmpty(reportSubject))
                {
                    doc.Add(GetReportSubject(reportSubject));
                    Font font = new Font(1, CONTENT_FONT_SIZE);
                    Paragraph p = new Paragraph("", font);
                    doc.Add(p);
                }
    
                T tHead = this.GetReportHeader(u);
                T tContent = this.GetReportContent(u);
                T tObject = this.GetReportObject(u);
                T tFooter = this.GetReportFooter(u);
    
                if (null != tHead)
                {
                    doc.Add(tHead);
                }
                if (null != tContent)
                {
                    doc.Add(tContent);
                }
                if (null != tObject)
                {
                    doc.Add(tObject);
                }
                if (null != tFooter)
                {
                    doc.Add(tFooter);
                }
                doc.Close();
                
    
            }
        }
    }
    

     派生类:

    using System;
    using System.IO;
    using System.Collections.Generic;
    
    
    using iTextSharp;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using CommonLibrary.Report;
    using CommonLibrary.Report.Base;
    
    /// <summary>
    ///名    称:JDE销售往来账报表
    ///功能概要:实现生成PDF
    ///作    者:Lucifer
    /// </summary>
    /// <remarks>
    /// 创建时间:2013年12月2日11:29:43
    /// 修正履历:
    /// 修正时间:
    /// </remarks>
    public class ReportSellCurrentAccount : ReportBase<PdfPTable, ReportModel>
    {
        public ReportSellCurrentAccount()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        //private DateTime _generateDateTime;
        //public DateTime GenerteDateTime
        //{
        //    set { _generateDateTime = value; }
        //    get { return _generateDateTime; }
        //}
        public override void CreateReport(ReportModel u, string reportTitle, string reportSubject, Rectangle r, float marginLeft, float marginRight, float marginTop, float marginBottom)
        {
            try
            {
                Document doc = new Document(r, marginLeft, marginRight, marginTop, marginBottom);
                if (String.IsNullOrEmpty(this.FileName))
                {
                    throw new Exception("报表名称不能为空!");
                }
                FileStream fs = new FileStream(this.FileName, FileMode.Create);
                PdfWriter pdfWriter = PdfWriter.GetInstance(doc, fs);
                doc.Open();
    
                if (!String.IsNullOrEmpty(reportSubject))
                {
                    doc.Add(GetReportSubject(reportSubject));
                    Font font = new Font(1, 10);
                    Paragraph p = new Paragraph("", font);
                    doc.Add(p);
                }
                PdfPTable tHead = this.GetReportHeader(u);
                PdfPTable tOrderItem = this.GetList(u);
                doc.Add(new PdfPTable(1));
                if (null != tHead)
                {
                    doc.Add(tHead);
                }
    
                if (null != tOrderItem)
                {
                    doc.Add(tOrderItem);
                }
                //fs.Close();
                doc.Close();
                fs.Close();
                pdfWriter.Close();
    
               
            }
            catch (System.Exception ex)
            {
                CommonLibrary.LogHelper.LogWrite(ex.Message);
            }
        }
        /// <summary>
        /// 获取列标题字体
        /// </summary>
        public virtual Font FontColumn
        {
            get
            {
                Font ft = new Font(FontBase.BaseFont, 12, Font.COURIER);
                return ft;
            }
        }
        /// <summary>
        /// 获取列 内容字体
        /// </summary>
        public virtual Font FontColumnValue
        {
            get
            {
                Font ft = new Font(FontBase.BaseFont, 10, Font.COURIER);
                return ft;
            }
        }
        public virtual Font FontHeader
        {
            get
            {
                Font ft = new Font(FontBase.BaseFont, 15, Font.COURIER);
                return ft;
            }
        }
        private PdfPTable GetList(ReportModel u)
        {
    
            ///定义列标题
            ///
            float[] ColumnWidth = { 20, 15, 25, 20, 25, 20, 25, 20, 20, 20, 20, 20 };
            PdfPTable ptb = new PdfPTable(ColumnWidth);
            //ptb.SetWidths(new int[]{10,10,10,10});
    
            PdfPCell pHCustomerCode = new PdfPCell(new Paragraph("客户代码", FontColumn));
            pHCustomerCode.NoWrap = false;
            pHCustomerCode.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHCustomerCode);
    
            PdfPCell pHRAMARK = new PdfPCell(new Paragraph("交易类型", FontColumn));
            pHRAMARK.NoWrap = false;
            pHRAMARK.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHRAMARK);
    
            PdfPCell pHSDDCTO03 = new PdfPCell(new Paragraph("单据类型", FontColumn));
            pHSDDCTO03.NoWrap = false;
            pHSDDCTO03.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHSDDCTO03);
    
            PdfPCell pHSDDOCO03 = new PdfPCell(new Paragraph("系统单号", FontColumn));
            pHSDDOCO03.NoWrap = false;
            pHSDDOCO03.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHSDDOCO03);
    
            PdfPCell pHAMOUNT01 = new PdfPCell(new Paragraph("含税金额", FontColumn));
            pHAMOUNT01.NoWrap = false;
            pHAMOUNT01.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHAMOUNT01);
    
            PdfPCell pHGLDOC03 = new PdfPCell(new Paragraph("交易日期", FontColumn));
            pHGLDOC03.NoWrap = false;
            pHGLDOC03.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHGLDOC03);
    
            PdfPCell pHSDVR0103 = new PdfPCell(new Paragraph("客户订单号", FontColumn));
            pHSDVR0103.NoWrap = false;
            pHSDVR0103.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHSDVR0103);
    
            PdfPCell pHA3DS80 = new PdfPCell(new Paragraph("客户名称", FontColumn));
            pHA3DS80.NoWrap = false;
            pHA3DS80.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHA3DS80);
    
            PdfPCell pHALADD1 = new PdfPCell(new Paragraph("客户地址1", FontColumn));
            pHALADD1.NoWrap = false;
            pHALADD1.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHALADD1);
    
            PdfPCell pHALADD2 = new PdfPCell(new Paragraph("客户地址2", FontColumn));
            pHALADD2.NoWrap = false;
            pHALADD2.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHALADD2);
    
            PdfPCell pHSDDOC = new PdfPCell(new Paragraph("过620状态单号", FontColumn));
            pHSDDOC.NoWrap = false;
            pHSDDOC.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHSDDOC);
    
            PdfPCell pHSDTAX1 = new PdfPCell(new Paragraph("是否含税", FontColumn));
            pHSDTAX1.NoWrap = false;
            pHSDTAX1.HorizontalAlignment = Element.ALIGN_CENTER;
            ptb.AddCell(pHSDTAX1);
            //decimal paymentConcessionTotal = 0, moreConcessionTotal = 0;
            foreach (System.Data.DataRow dr in u.PDFDatable.Rows)
            {
                PdfPCell pcCustomerCode = new PdfPCell(new Paragraph(Convert.ToString(dr["SDAN8"]), FontColumnValue));
                pcCustomerCode.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcCustomerCode);
    
                PdfPCell pcRAMARK = new PdfPCell(new Paragraph(Convert.ToString(dr["RAMARK"]), FontColumnValue));
                pcRAMARK.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcRAMARK);
    
                PdfPCell pcSDDCTO03 = new PdfPCell(new Paragraph(Convert.ToString(dr["SDDCTO03"]), FontColumnValue));
                pcSDDCTO03.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcSDDCTO03);
    
                PdfPCell pcSDDOCO03 = new PdfPCell(new Paragraph(Convert.ToString(dr["SDDOCO03"]), FontColumnValue));
                pcSDDOCO03.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcSDDOCO03);
    
                PdfPCell pcAMOUNT01 = new PdfPCell(new Paragraph(Convert.ToString(dr["AMOUNT01"]), FontColumnValue));
                pcAMOUNT01.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcAMOUNT01);
    
                PdfPCell pcGLDOC03 = new PdfPCell(new Paragraph(Convert.ToString(dr["GLDOC03"]), FontColumnValue));
                pcGLDOC03.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcGLDOC03);
    
                PdfPCell pcSDVR0103 = new PdfPCell(new Paragraph(Convert.ToString(dr["SDVR0103"]), FontColumnValue));
                pcSDVR0103.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcSDVR0103);
    
                PdfPCell pcA3DS80 = new PdfPCell(new Paragraph(Convert.ToString(dr["A3DS80"]), FontColumnValue));
                pcA3DS80.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcA3DS80);
    
                PdfPCell pcALADD1 = new PdfPCell(new Paragraph(Convert.ToString(dr["ALADD1"]), FontColumnValue));
                pcALADD1.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcALADD1);
    
                PdfPCell pcALADD2 = new PdfPCell(new Paragraph(Convert.ToString(dr["ALADD2"]), FontColumnValue));
                pcALADD2.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcALADD2);
    
                PdfPCell pcSDDOC = new PdfPCell(new Paragraph(Convert.ToString(dr["SDDOC"]), FontColumnValue));
                pcSDDOC.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcSDDOC);
    
                PdfPCell pcSDTAX1 = new PdfPCell(new Paragraph(Convert.ToString(dr["SDTAX1"]), FontColumnValue));
                pcSDTAX1.HorizontalAlignment = Element.ALIGN_CENTER;
                ptb.AddCell(pcSDTAX1);
            }
            return ptb;
        }
    
        public override PdfPTable GetReportContent(ReportModel u)
        {
            throw new NotImplementedException();
        }
        public override PdfPTable GetReportFooter(ReportModel u)
        {
            throw new NotImplementedException();
        }
        public override PdfPTable GetReportHeader(ReportModel u)
        {
            float[] ColumnWidth = { 10, 15, 25, 20, 25, 20, 25, 20, 20, 20, 20, 20 };
            PdfPTable ptb = new PdfPTable(ColumnWidth);
    
            PdfPCell pcBlank1 = new PdfPCell(new Paragraph(" ", FontHeader));
            pcBlank1.HorizontalAlignment = 2;
            pcBlank1.Border = 0;
            pcBlank1.FixedHeight = 30;
            pcBlank1.Colspan = 12;
            pcBlank1.NoWrap = false;
            pcBlank1.HorizontalAlignment = Element.ALIGN_LEFT;
            ptb.AddCell(pcBlank1);
    
            PdfPCell pc1 = new PdfPCell(new Paragraph("", FontHeader));
            pc1.HorizontalAlignment = 2;
            pc1.Border = 0;
            pc1.NoWrap = false;
            pc1.Colspan = 5;
            pc1.HorizontalAlignment = Element.ALIGN_LEFT;
    
            PdfPCell pc2 = new PdfPCell(new Paragraph("日期:" + u.PDFCreateDate, FontHeader));
            pc2.HorizontalAlignment = 2;
            pc2.Border = 0;
            pc2.Colspan = 7;
            ptb.AddCell(pc1);
            ptb.AddCell(pc2);
    
            PdfPCell pcBlank2 = new PdfPCell(new Paragraph(" ", FontHeader));
            pcBlank2.HorizontalAlignment = 2;
            pcBlank2.Border = 0;
            pcBlank1.Colspan = 12;
            pcBlank2.NoWrap = false;
            pcBlank2.HorizontalAlignment = Element.ALIGN_LEFT;
            ptb.AddCell(pcBlank2);
            return ptb;
        }
        public override Paragraph GetReportSubject(string subject)
        {
            return base.GetReportSubject(subject);
        }
        public override PdfPTable GetReportObject(ReportModel u)
        {
            throw new NotImplementedException();
        }
    }
    

    模型类:

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    using System.Data;
    namespace CommonLibrary.Report
    {
        /// <summary>
        /// 名    称:报表数据模型类
        /// 功能概要:提供导出数据及相关信息
        /// 作    者:Lucifer
        /// 创建时间:2013年12月2日11:53:33
        /// 修正履历:
        /// 修正时间:
        /// </summary>
        public class ReportModel
        {
            /// <summary>
            /// 获取或者设置 导出PDF数据列表
            /// </summary>
            public DataTable PDFDatable
            {
                set;
                get;
            }
            /// <summary>
            /// 获取或设置 导出PDF的标题
            /// </summary>
            public string PDFTitle
            {
                set;
                get;
            }
            /// <summary>
            /// 获取或设置 导出PDF的创建日期
            /// </summary>
            public string PDFCreateDate
            {
                set;
                get;
            }
        }
        
    }
    

    调用生成:

     private void ToPDF()
        {
            try
            {
    
                if (0 == gvSellCurAccReport.Rows.Count) 
                {
                    ShowMessageBox("无记录可下载!");
                    return;
                }
                //OutPutExcel("销售往来账报表.xls", gvSellCurAccReport);
                //string sql = GetQuerySql();
                //DataTable dt = Eorder.DBUtility.DbHelperSQL.Query(sql).Tables[0];
                //ExcelHelper.ExportByWeb(dt, "销售往来账报表", "销售往来账报表.xls");
                string sql = GetQuerySql();
                DataTable dt = DbHelperSQL.Query(sql).Tables[0];
                ReportModel model = new ReportModel();
                model.PDFCreateDate =Request.Form["generatePDFDateTime"];
                model.PDFDatable = dt;
                //model.PDFTitle = "销售往来账报表";
                string reportFileName = "销售往来账报表" + DateTime.Now.Ticks.ToString() + ".pdf";
                
                ReportSellCurrentAccount reportSca = new ReportSellCurrentAccount();
                reportSca.FileName = Server.MapPath("~") + @"
    eports" + reportFileName;
                reportSca.CreateReport(model, "销售往来账报表", "销售往来账报表",iTextSharp.text.PageSize.A3, 10, 10, 10, 10);
                OutPutFile(reportFileName, reportSca.FileName);
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "pdf", "<script>showPage('../reports/" + reportFileName + "', '_blank', 1024, 1024 , false, false, null);$.unblockUI();</script>");
                //Response.Write("<script>$.unblockUI();<script>");
                
            }
            catch (Exception ex)
            {
                CommonLibrary.LogHelper.LogWrite(ex.Message);
            }
        }
    
     /// <summary>
        /// 输出文件
        /// </summary>
        protected void OutPutFile(string fileName,string filePath) 
        {
    
            //FileInfo info = new FileInfo(filePath);
            //long fileSize = info.Length;
           // Response.Clear();
           // Response.ContentType = "application/x-zip-compressed";
           // Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(fileName));
           // //不指明Content-Length用Flush的话不会显示下载进度 
           //// Response.AddHeader("Content-Length", fileSize.ToString());
           // Response.TransmitFile(filePath);
           // Response.Flush();
           // Response.Close(); 
           // string fileName = "CodeShark.zip";//客户端保存的文件名
            //string filePath = Server.MapPath("DownLoad/CodeShark.zip");//路径
            //以字符流的形式下载文件
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment;   filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    
  • 相关阅读:
    kettle imestamp : Unable to get timestamp from resultset at index 22
    ImportError: No module named setuptools 解决方案
    Tesseract-OCR
    python截图
    connect to SQL Server in python on centos
    vertica merge 优化
    kettle crontab java: command not found
    Idea 使用maven+tomcat的时候,编译指定的Profile
    Java中Vector和ArrayList的区别
    Docker入门命令
  • 原文地址:https://www.cnblogs.com/zhangxiaolin/p/itextsharp.html
Copyright © 2020-2023  润新知