Ejemplo n.º 1
0
        private static Font FontAndSize(string font_name, int size, int style, Color baseColor)
        {
            BaseFont baseFont; BaseFont.AddToResourceSearch("iTextAsian.dll");

            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
            Font font = null; string file_name = "";
            int  fontStyle; switch (font_name)

            {
            case "黑体": file_name = "SIMHEI.TTF"; break;

            case "华文中宋": file_name = "STZHONGS.TTF"; break;

            case "宋体": file_name = "SIMYOU.TTF"; break;

            default: file_name = "SIMYOU.TTF"; break;
            }
            baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + file_name, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            if (style < -1)
            {
                fontStyle = Font.NORMAL;
            }
            else
            {
                fontStyle = style;
            }
            font = new Font(baseFont, size, fontStyle, baseColor);
            return(font);
        }
Ejemplo n.º 2
0
        private static BaseFont BaseFontAndSize(string font_name)
        {
            BaseFont baseFont;

            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
            string file_name = "";

            switch (font_name)
            {
            case "黑体":
                file_name = "SIMHEI.TTF";
                break;

            case "华文中宋":
                file_name = "STZHONGS.TTF";
                break;

            case "宋体":
                file_name = "SIMYOU.TTF";
                break;

            default:
                file_name = "SIMYOU.TTF";
                break;
            }
            baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + file_name, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            return(baseFont);
        }
Ejemplo n.º 3
0
/* ---------------------------------------------------------------------------
 * static contructor => initialize member(s)
 */
        static Utility()
        {
            HttpContext hc = HttpContext.Current;

            if (hc != null)
            {
                BaseDirectory     = hc.Server.MapPath("~/iTextInAction2Ed/");
                ResourceDirectory = Path.Combine(BaseDirectory, "resources");
            }
            else
            {
                BaseDirectory = Path.GetDirectoryName(
                    Assembly.GetEntryAssembly().Location
                    );
                ResultDirectory = new Uri(
                    new Uri(BaseDirectory), "results"
                    ).LocalPath;
                ResourceDirectory = new Uri(
                    new Uri(BaseDirectory), "iTextInAction2Ed/resources"
                    ).LocalPath;
                BaseFont.AddToResourceSearch(Path.Combine(
                                                 BaseDirectory, "iTextAsian.dll"
                                                 ));
            }
        }
Ejemplo n.º 4
0
 static PdfArchiver()
 {
     BaseFont.AddToResourceSearch("iTextAsian.dll");
     _font = new Font(
         BaseFont.CreateFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", BaseFont.NOT_EMBEDDED)
         , 16);
 }
Ejemplo n.º 5
0
        private BaseFont CreateChineseFont()
        {
            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll"); //"STSong-Light", "UniGB-UCS2-H",
            BaseFont baseFT = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

            return(baseFT);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 转化PDF格式加文字水印
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="toPath"></param>
        /// <param name="txt"></param>
        /// <param name="url"></param>
        public static void ConvertPDFToPDFByText2(string filePath, string toPath, string txt, string url)
        {
            ////文字水印
            PdfReader pdfReader = new PdfReader(filePath);
            int       n         = pdfReader.NumberOfPages;

            iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
            float      width      = psize.Width;
            float      height     = psize.Height;
            Document   document   = new Document(psize, 50f, 50f, 0f, 50f);
            FileStream fileStream = new FileStream(toPath, FileMode.OpenOrCreate);
            PdfWriter  writer     = PdfWriter.GetInstance(document, fileStream);

            document.Open();
            try
            {
                PdfContentByte cb = writer.DirectContentUnder;
                int            i  = 0;
                int            p  = 0;
                while (i < n)
                {
                    document.NewPage();
                    p++;
                    i++;
                    if (i == 1) // 就第一页加链接地址
                    {
                        Paragraph paragraph = new Paragraph("");
                        BaseFont.AddToResourceSearch("iTextAsian.dll");
                        BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");

                        Font   font    = new Font(BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", true), 8f, 4, new Color(0, 0, 0xff));
                        Anchor anchor1 = new Anchor(txt, font);
                        anchor1.Reference = url;

                        paragraph.Add(anchor1);
                        paragraph.IndentationLeft  = 10f;
                        paragraph.IndentationRight = 10f;
                        paragraph.Alignment        = 2; //右对齐
                        document.Add(paragraph);
                    }

                    PdfImportedPage page1 = writer.GetImportedPage(pdfReader, i);
                    cb.AddTemplate(page1, 0f, 0f);
                }
                document.Close();
                pdfReader.Close();
                fileStream.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                fileStream.Dispose();
                fileStream.Close();
            }
        }
Ejemplo n.º 7
0
    /// <summary>
    /// 设置字体
    /// </summary>
    /// <param name="size">字体大小</param>
    public void SetFont(float size)
    {
        BaseFont.AddToResourceSearch("iTextAsian.dll");
        BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
        //"UniGB-UCS2-H" "UniGB-UCS2-V"是简体中文,分别表示横向字和纵向字
        //"STSong-Light"是字体名称
        BaseFont baseFT = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

        font = new iTextSharp.text.Font(baseFT, size);
    }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            //中文字体包iTextAsianCmaps.dll与iTextAsian.dll
            BaseFont.AddToResourceSearch(Path.Combine(AppContext.BaseDirectory, "iTextAsian4Core.dll"));
            BaseFont.AddToResourceSearch(Path.Combine(AppContext.BaseDirectory, "iTextAsianCmaps4Core.dll"));

            //取全部列表
            List <People> peopleList = PeopleReporitory.GetPeoples().Result;

            foreach (var item in peopleList)
            {
                //读取和解析PDF文档
                PdfReader reader = new PdfReader("people.pdf");

                //创建文件流用来保存填充模板后的文件,为系统内存提供流式的读写操作。常作为其他流数据交换时的中间对象操作
                MemoryStream ms = new MemoryStream();

                //向现有PDF文档添加额外内容
                PdfStamper stamp = new PdfStamper(reader, ms);

                //获取AcroFields对象,该对象允许获取和设置字段值并合并FDF表单
                AcroFields form = stamp.AcroFields;

                //表单文本框是否锁定
                stamp.FormFlattening = true;

                Dictionary <string, string> keyValues = new Dictionary <string, string>();
                keyValues.Add("1", item.Id.ToString());
                keyValues.Add("2", item.Name);
                keyValues.Add("3", GenderConverter.Instance.GetString(item.Gender));
                keyValues.Add("4", item.Age.ToString());

                //填充表单,para为表单的一个(属性-值)字典
                foreach (KeyValuePair <string, string> parameter in keyValues)
                {
                    //要输入中文就要设置域的字体;
                    //form.SetFieldProperty(parameter.Key, "textfont", baseFont, null);
                    //为需要赋值的域设置值;
                    form.SetField(parameter.Key, parameter.Value);
                }

                stamp.Close();
                reader.Close();
                var        now  = DateTime.Now;
                string     path = string.Format("\\ID{0}", item.Id);
                FileStream fs   = new FileStream(@"E:\hxj\PDF" + path + "myData.pdf", FileMode.Create);
                fs.Write(ms.GetBuffer(), 0, (int)ms.Position);

                ms.Close();
                fs.Close();
            }

            Console.WriteLine("Hello World!");
        }
Ejemplo n.º 9
0
 private void StartPageSet(OrgInfo o)
 {
     pageSetStarted = true;
     if (altnames == true)
     {
         BaseFont.AddToResourceSearch(HttpContext.Current.Server.MapPath("/iTextAsian.dll"));
         var bfchina = BaseFont.CreateFont("MHei-Medium",
                                           "UniCNS-UCS2-H", BaseFont.EMBEDDED);
         china = new Font(bfchina, 12, Font.NORMAL);
     }
     pageEvents.StartPageSet(
         "{0}: {1}, {2} ({3})".Fmt(o.Division, o.Name, o.Location, o.Teacher),
         "{0:f} ({1})".Fmt(dt, o.OrgId),
         "M.{0}.{1:MMddyyHHmm}".Fmt(o.OrgId, dt));
 }
Ejemplo n.º 10
0
        /// <summary>
        /// 创建PDF的文字水印
        /// </summary>
        /// <param name="iTextAsian_Path">iTextAsian.dll所在路径</param>
        /// <param name="iTextAsianCmaps_Path">iTextAsianCmaps.dll所在路径</param>
        /// <param name="inputfilepath">源PDF文件</param>
        /// <param name="outputfilepath">加水印后PDF文件</param>
        /// <param name="waterMarkText">文字水印文本</param>
        public static void PDFTextWatermark(string iTextAsian_Path, string iTextAsianCmaps_Path, string inputfilepath, string outputfilepath, string waterMarkText)
        {
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            pdfReader = new PdfReader(inputfilepath);
            //pdf总的页数
            int numberOfPages = pdfReader.NumberOfPages;

            iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
            float width  = psize.Width;
            float height = psize.Height;

            pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));

            PdfContentByte content;

            //设置字体,载入亚洲字体资源,无此操作的话,不能显示包括中文、日文、韩文等内容
            BaseFont.AddToResourceSearch(iTextAsianCmaps_Path);
            BaseFont.AddToResourceSearch(iTextAsian_Path);
            BaseFont bf = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);


            //水印文字,文字长度
            int j = waterMarkText.Length;

            //循环对每页插入水印
            for (int i = 1; i <= numberOfPages; i++)
            {
                content = pdfStamper.GetUnderContent(i);
                //开始
                content.BeginText();
                //设置颜色
                content.SetColorFill(iTextSharp.text.BaseColor.GRAY);
                //设置字体及字号
                content.SetFontAndSize(bf, 18);
                //设置起始位置
                content.SetTextMatrix(20, 25);
                //设置对齐以及倾斜方式等
                content.ShowTextAligned((int)(Element.ALIGN_CENTER), waterMarkText, content.PdfDocument.PageSize.Width / 2, content.PdfDocument.PageSize.Height / 2 + 100, 60f);
                //关闭
                content.EndText();
            }
            pdfStamper.Close();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 根据填充内容获得一页的PDF文件内容
        /// </summary>
        /// <param name="pdf1">模板文件</param>
        /// <param name="lfi">数据LIST</param>
        /// <param name="buf">返回的BUFFER</param>
        /// <returns>0为不成功</returns>
        public static int Get1PageBuf(string pdf1, List <FieldInfo> lfi, out byte[] buf)
        {
            int          iret = 0;
            MemoryStream ms   = new MemoryStream();

            PdfReader  reader = new PdfReader(pdf1);
            PdfStamper stamp1 = new PdfStamper(reader, ms);

            //不关闭流
            stamp1.Writer.CloseStream = false;

            AcroFields form1 = stamp1.AcroFields;

            //BaseFont.AddToResourceSearch("iTextAsian.dll");
            //BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
            BaseFont.AddToResourceSearch(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\bin\\iTextAsian.dll");
            BaseFont.AddToResourceSearch(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\bin\\iTextAsianCmaps.dll");


            BaseFont font = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

            //以下为填写表单部分
            for (int i = 0; i < lfi.Count; i++)
            {
                form1.SetFieldProperty(lfi[i].FieldName, "textfont", font, null);
                form1.SetField(lfi[i].FieldName, lfi[i].FieldValue);
            }

            //一下仅用于进度条start
            CProcessInfo info = HttpContext.Current.Session["ProcessInfo"] as CProcessInfo;

            info.Message = lfi[0].FieldValue + "创建打印文件完成";
            info.Current++;
            //一下仅用于进度条end

            stamp1.FormFlattening = true;
            stamp1.Close();

            buf  = ms.GetBuffer();
            iret = 1;
            return(iret);
        }
Ejemplo n.º 12
0
        public ExportReport()
        {
            xdoc   = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "\\AppTemplate\\report.xml");
            pdfDoc = new Document(PageSize.A4, 0, 0, 0, 0);
            Rectangle rect = new Rectangle(794, 1123);

            pdfDoc.SetPageSize(rect);
            pdfDoc.SetMargins(0, 0, 20, 0);

            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
            BaseFont bsFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            fontTitle       = new Font(bsFont, 20);
            fontContent     = new Font(bsFont, 12);
            fontLabel       = new Font(bsFont, 12);
            fontTableRemark = new Font(bsFont, 14);
            fontLabel.SetStyle(Font.BOLD);
            fontTitle.SetStyle(Font.BOLD);
            fontTableRemark.SetStyle(Font.BOLD);
        }
Ejemplo n.º 13
0
        protected Font fontTableRemark = new Font(); //表格备注字体

        /// <summary>
        /// 用report.xml的xdocument实例化
        /// </summary>
        /// <param name="doc">report内容</param>
        public AbsExportPDF(XDocument doc)
        {
            xdoc = doc;

            pdfDoc = new Document(PageSize.A4, 0, 0, 0, 0);
            Rectangle rect = new Rectangle(794, 1123);

            pdfDoc.SetPageSize(rect);
            pdfDoc.SetMargins(0, 0, 20, 0);

            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
            BaseFont bsFont;

            bsFont = BaseFont.CreateFont(@"c:\WINDOWS\fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            fontTitle       = new Font(bsFont, 20);
            fontContent     = new Font(bsFont, 12);
            fontLabel       = new Font(bsFont, 12);
            fontTableRemark = new Font(bsFont, 14);
            fontLabel.SetStyle(Font.BOLD);
            fontTitle.SetStyle(Font.BOLD);
            fontTableRemark.SetStyle(Font.BOLD);
        }
Ejemplo n.º 14
0
        public static void LoadFontResource()
        {
            var resourcePath = System.IO.Path.Combine(GetExecutingFolder(), "iTextAsian.dll");

            BaseFont.AddToResourceSearch(resourcePath);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 通过模板生成PDF文件流
        /// </summary>
        /// <param name="tempPath"></param>
        /// <param name="para"></param>
        /// <returns></returns>
        public static string ConvertToPDF(string tempPath, Dictionary <string, string> para)
        {
            //获取中文字体,第三个参数表示为是否潜入字体,但只要是编码字体就都会嵌入。
            //BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            //字体设置
            var dllPath1 = Lib.IOHelper.GetFileFullPath(@"DLL\iTextAsian4Core.dll");

            BaseFont.AddToResourceSearch(dllPath1);
            var dllPath2 = Lib.IOHelper.GetFileFullPath(@"DLL\iTextAsianCmaps4Core.dll");

            BaseFont.AddToResourceSearch(dllPath2);
            BaseFont baseFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            //读取模板文件
            PdfReader reader = new PdfReader(tempPath);

            //创建文件流用来保存填充模板后的文件
            System.IO.MemoryStream stream = new System.IO.MemoryStream();

            PdfStamper stamp = new PdfStamper(reader, stream);
            //设置表单字体,在高版本有用,高版本加入这句话就不会插入字体,低版本无用
            //stamp.AcroFields.AddSubstitutionFont(baseFont);

            AcroFields form = stamp.AcroFields;

            //表单文本框是否锁定
            stamp.FormFlattening = true;

            //填充表单,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();

            //保存到磁盘
            var fileName     = RandomHelper.GetRandomString(13, 3);
            var path         = $@"Resources\Templates\PDFTemplates\{fileName}.pdf";
            var saveFullPath = Lib.IOHelper.GetFileFullPath(path);
            var fullPath     = Path.GetDirectoryName(saveFullPath);

            //如果没有此文件夹,则新建
            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
            }
            var bytes = stream.ToArray();

            //创建文件,返回一个 FileStream,它提供对 path 中指定的文件的读/写访问。
            using (FileStream s = File.Create(saveFullPath))
            {
                //将字节数组写入流
                s.Write(bytes, 0, bytes.Length);
                s.Close();
            }
            return(fileName + ".pdf");
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 文字水印和图片水印 获取页数
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="toPath"></param>
        /// <param name="txt"></param>
        /// <param name="url"></param>
        /// <param name="pages"></param>
        public static void ConvertPDFAll2(string filePath, string toPath, string txt, string url, ref int pages)
        {
            //文字水印
            if (!Directory.Exists("PDFTemp"))
            {
                Directory.CreateDirectory("PDFTemp");
            }
            string    tempPath  = @"PDFTemp\" + Path.GetFileNameWithoutExtension(toPath) + ".pdf";
            PdfReader pdfReader = new PdfReader(filePath);
            int       n         = pdfReader.NumberOfPages;

            pages = n;
            iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
            float      width      = psize.Width;
            float      height     = psize.Height;
            Document   document   = new Document(psize, 50f, 50f, 50f, 50f);
            FileStream fileStream = new FileStream(tempPath, FileMode.OpenOrCreate);
            PdfWriter  writer     = PdfWriter.GetInstance(document, fileStream);

            document.Open();
            PdfContentByte cb = writer.DirectContentUnder;
            int            i  = 0;
            int            p  = 0;

            while (i < n)
            {
                document.NewPage();
                p++;
                i++;

                Paragraph paragraph = new Paragraph("");
                BaseFont.AddToResourceSearch("iTextAsian.dll");
                BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
                if (i == 1) // 就第一页加链接地址
                {
                    Font   font    = new Font(BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", true), 12f, 4, new Color(0, 0, 0xff));
                    Anchor anchor1 = new Anchor(txt, font);
                    anchor1.Reference = url;
                    paragraph.Add(anchor1);
                }
                paragraph.IndentationLeft  = 10f;
                paragraph.IndentationRight = 10f;
                document.Add(paragraph);

                PdfImportedPage page1 = writer.GetImportedPage(pdfReader, i);
                cb.AddTemplate(page1, 0f, -40f);
            }
            document.Close();
            pdfReader.Close();
            fileStream.Close();

            //图片水印
            PdfReader reader = new PdfReader(tempPath);
            //获取保存目录名
            string toPathName = Path.GetDirectoryName(toPath);

            if (!Directory.Exists(toPathName))
            {
                Directory.CreateDirectory(toPathName);
            }
            FileStream fs    = new FileStream(toPath, FileMode.Create);
            PdfStamper stamp = null;

            try
            {
                stamp = new PdfStamper(reader, fs);
                //aku
                System.Drawing.Image    img         = new System.Drawing.Bitmap("aku.gif");
                System.Drawing.Bitmap   waterBitmap = new System.Drawing.Bitmap(img.Width, img.Height);
                System.Drawing.Graphics gr          = System.Drawing.Graphics.FromImage(waterBitmap);
                float[][] ptsArray =
                {
                    new float[] { 1, 0, 0,    0, 0 },
                    new float[] { 0, 1, 0,    0, 0 },
                    new float[] { 0, 0, 1,    0, 0 },
                    new float[] { 0, 0, 0, 0.6f, 0 },
                    new float[] { 0, 0, 0,    0, 1 }
                };
                ColorMatrix     clrMatrix     = new ColorMatrix(ptsArray);
                ImageAttributes imgAttributes = new ImageAttributes();
                //设置图像的颜色属性
                imgAttributes.SetColorMatrix(clrMatrix, ColorMatrixFlag.Default,
                                             ColorAdjustType.Bitmap);
                //画图像
                gr.DrawImage(img, new System.Drawing.Rectangle(0, 0, img.Width, img.Height),
                             0, 0, img.Width, img.Height,
                             System.Drawing.GraphicsUnit.Pixel, imgAttributes);

                Image mm = Image.GetInstance(waterBitmap, System.Drawing.Imaging.ImageFormat.Png);

                mm.SetAbsolutePosition(5, 5);
                mm.ScaleAbsolute(108, 63);
                mm.Annotation = new Annotation(0f, 0f, 0f, 0f, "http://pdf.dzsc.com/");

                stamp.GetOverContent(1).AddImage(mm);

                //wku
                System.Drawing.Image    imgW         = new System.Drawing.Bitmap("wku.jpg");
                System.Drawing.Bitmap   waterBitmapW = new System.Drawing.Bitmap(imgW.Width, imgW.Height);
                System.Drawing.Graphics grW          = System.Drawing.Graphics.FromImage(waterBitmapW);
                float[][] ptsArrayW =
                {
                    new float[] { 1, 0, 0,    0, 0 },
                    new float[] { 0, 1, 0,    0, 0 },
                    new float[] { 0, 0, 1,    0, 0 },
                    new float[] { 0, 0, 0, 0.1f, 0 },
                    new float[] { 0, 0, 0,    0, 1 }
                };
                ColorMatrix     clrMatrixW     = new ColorMatrix(ptsArrayW);
                ImageAttributes imgAttributesW = new ImageAttributes();
                //设置图像的颜色属性
                imgAttributesW.SetColorMatrix(clrMatrixW, ColorMatrixFlag.Default,
                                              ColorAdjustType.Bitmap);
                //画图像
                grW.DrawImage(imgW, new System.Drawing.Rectangle(0, 0, imgW.Width, imgW.Height),
                              0, 0, imgW.Width, imgW.Height,
                              System.Drawing.GraphicsUnit.Pixel, imgAttributesW);

                Image mmW = Image.GetInstance(waterBitmapW, System.Drawing.Imaging.ImageFormat.Png);

                mmW.SetAbsolutePosition(48, 65);
                mmW.ScaleAbsolute(500, 680);
                stamp.GetOverContent(1).AddImage(mmW);

                stamp.Close();
                reader.Close();
                gr.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                fs.Dispose();
                fs.Close();

                FileInfo fi = new FileInfo(tempPath);
                fi.Delete();
            }
        }
Ejemplo n.º 17
0
        public static void AddPdfTable <T>(Document doc, string[] title, string[] tableFoot, List <T> entitys, List <string> remarks)
        {
            //字体设置
            var dllPath1 = Lib.IOHelper.GetFileFullPath(@"DLL\iTextAsian4Core.dll");

            BaseFont.AddToResourceSearch(dllPath1);
            var dllPath2 = Lib.IOHelper.GetFileFullPath(@"DLL\iTextAsianCmaps4Core.dll");

            BaseFont.AddToResourceSearch(dllPath2);
            BaseFont baseFont   = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font     font_title = new Font(baseFont, 8, iTextSharp.text.Font.COURIER);

            //填充标题
            PdfPTable newTitle = new PdfPTable(title.Length);

            for (int index = 0; index < title.Length; index++)
            {
                PdfPCell newCell = new PdfPCell(new Paragraph(1, title[index], font_title));
                newCell.BackgroundColor = BaseColor.White;
                newTitle.AddCell(newCell);
            }
            doc.Add(newTitle);

            //填充表格内容
            for (int index = 0; index < entitys.Count; index++)
            {
                Type entityType       = entitys[0].GetType();
                var  entityProperties = entityType.GetProperties();

                PdfPTable newTable = new PdfPTable(entityProperties.Length);
                for (int columnIndex = 0; columnIndex < entityProperties.Length; columnIndex++)
                {
                    var      entityValue = entityProperties[columnIndex].GetValue(entitys[index]);
                    PdfPCell newCell     = new PdfPCell(new Paragraph(1, entityValue.ToString(), font_title));
                    newTable.AddCell(newCell);
                }
                doc.Add(newTable);
            }

            //填充表格统计内容
            if (tableFoot != null && tableFoot.Length > 0)
            {
                PdfPTable newFoot = new PdfPTable(tableFoot.Length);
                for (int index = 0; index < tableFoot.Length; index++)
                {
                    PdfPCell newCell = new PdfPCell(new Paragraph(1, tableFoot[index], font_title));
                    newFoot.AddCell(newCell);
                }
                doc.Add(newFoot);
            }

            //添加备注
            doc.Add(new Paragraph("", new Font(baseFont, 8, Font.COURIER)));
            var space = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";//空格

            foreach (var item in remarks)
            {
                doc.Add(new Paragraph(space + item, new Font(baseFont, 8, Font.COURIER)));
            }



            //byte[] b = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAKEAAAChAgMAAADSPzclAAAADFBMVEUAAAACAgIBAQECAgJfmUP0AAAABHRSTlMADAYJlQ+A3AAAA3ZJREFUWMPtmDtu20AQhikaAWIZKnkBAypsw6WQVsgJWGi4hEEELFOqNFIYW/oCquMyUGqXQYTcgb3LIH2aAIENyRJ/zsw+SLjVVCT34878s+9Njna0wbZerx/6cOP/RGT+xMEzerUvPcE4mjbUWh0kpwQzNubb/Fuvt6qoDJCPRHS3q+pqi26CVd7gOVDpjOhT+3JBRNYnnIgeWCi+Sq+JbvmPxkOuRGKmvpyetFWi0tKXdSu/GI/zUnup3c43oZ9hEyqC32CZ4//U2aL4yNwv1bcRHF2u17Z1Xyny3cH5tSWi/IPdyzSOMOt92cctmZV79zqmZp/20Z6sDsmvVTaLxEWesozgiyZTkVF4AdnmSQmybnImJbVOJDkRklKqBIn3UgjKPWRCC9FC8zZdGyJaZm1NKyOk204o5+dJ2hnalklnP2p3sGbhJU+Z+JQJbIiW3XbOWedcso7OCqnkHvzkasGi3vjJrGBJSgTpK5yZhCuqmUPLQwmkad6ppQqQI6p1IjCKWdxL/gwTipLO2wlvMEk2ZSeSuSaZXqjbhMgM5IRsKM5p0cmt3AlYRhrxqE1XNCu8FIJDyLCfz89PvDlBVklI0QipWTEy1eS8JUs3qZuwyYNkqknEufSQKOCmytMBZB0EER1IPYeggyILWvtwEvkeDSDnrCBG6r4UJ2FvJ/Uc8nZF8SzFMz+0NXUPCZJh7U0+uCcn/UkR1le0e3xs5oIcOjPESbRh1nteyhbusYllIDLTgrSY8mOzNx57k5FVxohAtHbIADnvucaNwivsquq9apdsBffPISlK0f1hsoMM37FkReBUPqGN3jxBkdqbopH8WZoZHoqfXBW9d5WV3qnq1RDpdG7F39/fW+0PsfhsAg16Ky438J6t+Hg34i7hzogWw3L7a3eaWEKC6AWlPnegJH7qgTfYijzkFArwwXM6szJrefTEdwAqJ3mmj7tknORUCMKxVp9256rRDoE+2h35dOiBjnFVOEbxKS1cx3/rup/Jg8d/GCHMbqCFIyTjnAC0+xmyyReCWxU7Jprw3cs13Ej3tfAC56JAaJpo5+77pLSBc33HYyyLspQIkk837KINU7PWRJ/hGxdtzkrp9yv4l4QeXSndfUvG3xtClb7rQthTiByDQ9u67aIFfb6RRdx+xuyq2ckCGIj1x/bq92hH29kLE7KiTARdgn4AAAAASUVORK5CYII=");
            //MemoryStream ms = new MemoryStream(b);
            //System.Drawing.Image imgSignature = System.Drawing.Image.FromStream(ms);
            //doc.Add(imgSignature);
        }
Ejemplo n.º 18
0
        /************************************************
        * Function name : generatePDF
        * Description : 生成小票
        * Variables : string filePath
        ************************************************/
        public void generatePDF(string filePath, double receive)
        {
            // 判断路径是否存在
            this.filePath = filePath;
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            // 结算
            analyse(receive);

            // 生成条码
            EncodingOptions encodeOption = new EncodingOptions();

            encodeOption.Height = 40;
            encodeOption.Width  = 180;
            ZXing.BarcodeWriter wr = new BarcodeWriter();
            wr.Options = encodeOption;
            wr.Format  = BarcodeFormat.CODE_39;
            Bitmap img = wr.Write(ticketID);

            img.Save(filePath + "\\" + ticketID + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

            // 生成PDF小票
            time = System.DateTime.Now.ToString();
            iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(width, height);
            Document document = new Document(pageSize, border_left, border_right, border_head, border_tail);

            PdfWriter.GetInstance(document, new FileStream(filePath + "\\" + ticketID + ".pdf", FileMode.Create));
            document.Open();
            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont baseFT = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFT, fontSize);

            document.Add(new Paragraph(seperator, font));
            document.Add(new Paragraph(storeName, font));
            document.Add(new Paragraph("票号:" + ticketID + " 机号:" + casherID + " 工号:" + employeeID, font));
            document.Add(new Paragraph("交易时间:" + time, font));
            document.Add(new Paragraph("合计金额:" + deal + " 卡券:" + card, font));
            document.Add(new Paragraph("据此联购物一个月内开发票!", font));
            document.Add(new Paragraph(seperator, font));
            document.Add(new Paragraph(storeName, font));
            document.Add(new Paragraph("票号:" + ticketID + " 机号:" + casherID + " 工号:" + employeeID, font));
            document.Add(new Paragraph("交易时间:" + time, font));
            document.Add(new Paragraph("*#" + casherID + ticketID + " #*", font));
            document.Add(new Paragraph(seperator, font));
            document.Add(new Paragraph("序号   商品编码(名称)   数量   金额", font));
            string str = "          ";

            for (int i = 0; i < overallAmount; i++)
            {
                document.Add(new Paragraph((i + 1) + str + gname[i] + str + amount[i] + str + price[i], font));
            }
            document.Add(new Paragraph(seperator, font));
            document.Add(new Paragraph("金额: " + deal + " 找零: " + refund, font));
            document.Add(new Paragraph("支付宝单号:" + AlipayID, font));
            if (AlipayID != "")
            {
                document.Add(new Paragraph("支付宝接口:" + deal, font));
            }
            else
            {
                document.Add(new Paragraph("支付宝接口:", font));
            }
            document.Add(new Paragraph(seperator, font));
            for (int i = 0; i < noteAmount; i++)
            {
                document.Add(new Paragraph(notes[i], font));
            }
            document.Add(new Paragraph(seperator, font));
            if (codeCreatorOpened)
            {
                iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(filePath + "\\" + ticketID + ".jpg");
                img2.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
                document.Add(img2);
            }

            document.Close();
        }