Exemplo n.º 1
0
        // オブジェクト透明度の指定
        public static void SetOpacity(PdfContentByte pdfContentByte, float opacity)
        {
            PdfGState graphicsState = new PdfGState();

            graphicsState.FillOpacity = opacity;
            pdfContentByte.SetGState(graphicsState);
        }
Exemplo n.º 2
0
 public static void manipulatePdf(String src, String dest, string Text = DefaultWatermark)
 {
     using (var ms = new MemoryStream(10 * 1024))
     {
         using (var reader = new PdfReader(src))
             using (var stamper = new PdfStamper(reader, ms))
             {
                 PdfContentByte under  = stamper.GetUnderContent(1);
                 Font           f      = new Font(FontFamily.HELVETICA, 45);
                 Phrase         p      = new Phrase(Text, f);
                 var            gstate = new PdfGState {
                     FillOpacity = 0.35f, StrokeOpacity = 0.3f
                 };
                 under.SaveState();
                 under.SetGState(gstate);
                 under.SetColorFill(BaseColor.GRAY);
                 Rectangle realPageSize = reader.GetPageSizeWithRotation(1);
                 var       x            = (realPageSize.Right + realPageSize.Left) / 2;
                 var       y            = (realPageSize.Bottom + realPageSize.Top) / 2;
                 ColumnText.ShowTextAligned(under, Element.ALIGN_CENTER, p, x, y, 45);
                 under.RestoreState();
                 stamper.Close();
                 reader.Close();
             }
         File.WriteAllBytes(dest, ms.ToArray());
     }
 }
Exemplo n.º 3
0
        public static Stream AddPdfWaterMark(string sourceFile, string stringToWriteToPdf)
        {
            PdfReader  reader     = null;
            PdfStamper pdfStamper = null;

            try
            {
                reader = new PdfReader(System.IO.File.ReadAllBytes(sourceFile));
                iTextSharp.text.Rectangle psize = reader.GetPageSize(1);

                float     width  = psize.Width;
                float     height = psize.Height;
                int       j      = stringToWriteToPdf.Length;
                PdfGState gs     = new PdfGState();
                gs.FillOpacity = 0.15f;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int rise  = 100;
                    int total = reader.NumberOfPages + 1;
                    pdfStamper = new PdfStamper(reader, memoryStream);
                    for (int i = 1; i < total; i++)
                    {
                        PdfContentByte pdfPageContents = pdfStamper.GetOverContent(i);
                        BaseFont       baseFont        = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
                        pdfPageContents.BeginText();
                        pdfPageContents.SetFontAndSize(baseFont, 40);
                        pdfPageContents.SetRGBColorFill(255, 0, 0);
                        pdfPageContents.SetColorFill(iTextSharp.text.BaseColor.GRAY);
                        pdfPageContents.SetFontAndSize(font, 60);
                        pdfPageContents.SetTextRise(rise);
                        pdfPageContents.SetGState(gs);
                        pdfPageContents.ShowTextAligned(iTextSharp.text.Element.ALIGN_LEFT, stringToWriteToPdf, 300, 500, 45);
                        pdfPageContents.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, stringToWriteToPdf, 400, 400, 45);
                        pdfPageContents.ShowTextAligned(iTextSharp.text.Element.ALIGN_RIGHT, stringToWriteToPdf, 500, 300, 45);
                        pdfPageContents.EndText();
                    }
                    pdfStamper.FormFlattening = true;
                    pdfStamper.Close();
                    return(new System.IO.MemoryStream(memoryStream.ToArray()));
                }
            }
            catch (Exception ex)
            {
                WriteLog(string.Format("{0},{1}", ex.Message, ex.StackTrace));
                return(new System.IO.MemoryStream(File.ReadAllBytes(sourceFile)));
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Exemplo n.º 4
0
        private static MemoryStream SetWaterMark(MemoryStream ms, string filePath, string waterMarkName, string waterMarkAddr = null)
        {
            MemoryStream msWater    = new MemoryStream();
            PdfReader    pdfReader  = null;
            PdfStamper   pdfStamper = null;

            try
            {
                pdfReader  = new PdfReader(filePath);
                pdfStamper = new PdfStamper(pdfReader, msWater);

                int total = pdfReader.NumberOfPages + 1;                    //获取PDF的总页数
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1); //获取第一页
                float          width            = psize.Width;              //PDF页面的宽度,用于计算水印倾斜
                float          height           = psize.Height;
                PdfContentByte waterContent;
                BaseFont       basefont = BaseFont.CreateFont(@"C://Windows/Fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState      gs       = new PdfGState();
                for (int i = 1; i < total; i++)
                {
                    waterContent = pdfStamper.GetOverContent(i); //在内容上方加水印
                                                                 //透明度
                    waterContent.SetGState(gs);
                    //开始写入文本
                    waterContent.BeginText();

                    //waterContent.SetColorFill(BaseColor.RED);
                    waterContent.SetFontAndSize(basefont, 18);

                    waterContent.SetTextMatrix(0, 0);
                    if (waterMarkAddr == null || waterMarkAddr == "")
                    {
                        waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2, height / 2, 55);
                    }
                    else
                    {
                        waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2, height / 2 + 100, 55);
                        waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkAddr, width / 2, height / 2 - 100, 55);
                    }
                    waterContent.EndText();
                }
            }
            catch (Exception)
            {
                return(ms);
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
            return(msWater);
        }
Exemplo n.º 5
0
        public byte[] Watermark(byte[] bPdf)
        {
            PdfGState gstate = new PdfGState()
            {
                FillOpacity   = 0.1f,
                StrokeOpacity = 0.3f
            };

            using (MemoryStream stream = new MemoryStream(10 * 1024)) {
                using (PdfReader reader = new PdfReader(bPdf))
                    using (PdfStamper stamper = new PdfStamper(reader, stream)) {
                        for (int i = 1; i <= stamper.Reader.NumberOfPages; i++)
                        {
                            Rectangle pageSize = reader.GetPageSizeWithRotation(i);
                            _position = new Position()
                            {
                                X = (pageSize.Right + pageSize.Left) / 2,
                                Y = (pageSize.Bottom + pageSize.Top) / 2
                            };

                            PdfContentByte content = stamper.GetOverContent(i);
                            content.SaveState();
                            content.SetGState(gstate);

                            AddWatermark(content);
                        }
                    }

                return(stream.ToArray());
            }
        }
Exemplo n.º 6
0
        private void MarcaDAgua(PdfWriter writer)
        {
            //Permite o posicionamento exato do texto e outros elementos
            PdfContentByte canvas = writer.DirectContent;

            //Criador de fonte do iTextSharp BaseFont.CreateFont(fonte, codificação, incluir ou não a fonte ao arquivo (incluir deixa mais pesado o PDF))
            BaseFont f_tr = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            //Define a fonte e o tamanho do texto
            canvas.SetFontAndSize(f_tr, 60);

            //Define o texto da marca d'água
            string watermarkText = "Marca d'água";

            //Define a opacidade
            PdfGState gstate = new PdfGState {
                FillOpacity = 0.35f, StrokeOpacity = 0.3f
            };

            canvas.SaveState();
            canvas.SetGState(gstate);
            canvas.SetColorFill(BaseColor.BLACK);

            //Escreve um texto centralizado
            canvas.BeginText();
            canvas.ShowTextAligned(Element.ALIGN_CENTER, watermarkText, 320, 420, 20);
            canvas.EndText();
            canvas.RestoreState();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Fills out and flattens a form with the name, company and country.
        /// </summary>
        /// <param name="src"> the path to the original form </param>
        /// <param name="dest"> the path to the filled out form </param>
        public void ManipulatePdf(String src, String dest)
        {
            PdfReader  reader  = new PdfReader(src);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)); // create?
            int        n       = reader.NumberOfPages;
            Rectangle  pagesize;

            for (int i = 1; i <= n; i++)
            {
                PdfContentByte under = stamper.GetUnderContent(i);
                pagesize = reader.GetPageSize(i);
                float     x  = (pagesize.Left + pagesize.Right) / 2;
                float     y  = (pagesize.Bottom + pagesize.Top) / 2;
                PdfGState gs = new PdfGState();
                gs.FillOpacity = 0.3f;
                under.SaveState();
                under.SetGState(gs);
                under.SetRGBColorFill(200, 200, 0);
                ColumnText.ShowTextAligned(under, Element.ALIGN_CENTER,
                                           new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 120)),
                                           x, y, 45);
                under.RestoreState();
            }
            stamper.Close();
            reader.Close();
        }
Exemplo n.º 8
0
        public void SetWatermarkByWord(string inputfilepath, string outputfilepath, string waterMarkName, bool HasCover = false)
        {
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            try
            {
                pdfReader = new PdfReader(inputfilepath);

                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                int total = pdfReader.NumberOfPages + 1;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
                float          width            = psize.Width;
                float          height           = psize.Height;
                PdfContentByte content;
                BaseFont       font = BaseFont;
                PdfGState      gs   = new PdfGState();
                for (int i = 1; i < total; i++)
                {
                    if (HasCover && i == 1)
                    {
                        continue;
                    }

                    content = pdfStamper.GetOverContent(i); //在内容上方加水印
                                                            //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                                                            //透明度
                    gs.FillOpacity = 0.3f;
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);
                    //开始写入文本
                    content.BeginText();
                    content.SetColorFill(BaseColor.LIGHT_GRAY);
                    content.SetFontAndSize(font, 50);
                    content.SetTextMatrix(0, 0);
                    content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 - 50, height / 2 - 50, 55);
                    //content.SetColorFill(BaseColor.BLACK);
                    //content.SetFontAndSize(font, 8);
                    //content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);
                    content.EndText();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 添加普通偏转角度文字水印
        /// </summary>
        /// <param name="inputfilepath">需要添加水印的pdf文件</param>
        /// <param name="outputfilepath">添加水印后输出的pdf文件</param>
        /// <param name="waterMarkName">水印内容</param>
        public void setWatermark(string inputfilepath, string outputfilepath, string waterMarkName)
        {
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            try
            {
                if (File.Exists(outputfilepath))
                {
                    File.Delete(outputfilepath);
                }

                pdfReader  = new PdfReader(inputfilepath);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.OpenOrCreate));

                int total = pdfReader.NumberOfPages + 1;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
                float          width            = psize.Width;
                float          height           = psize.Height;
                PdfContentByte content;
                BaseFont       font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState      gs   = new PdfGState();
                for (int i = 1; i < total; i++)
                {
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                    //透明度
                    gs.FillOpacity = 0.3f;
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);
                    //开始写入文本
                    content.BeginText();
                    content.SetColorFill(Color.LIGHT_GRAY);
                    content.SetFontAndSize(font, 100);
                    content.SetTextMatrix(0, 0);
                    content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 - 50, height / 2 - 50, 55);
                    //content.SetColorFill(BaseColor.BLACK);
                    //content.SetFontAndSize(font, 8);
                    //content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);
                    content.EndText();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 添加普通偏转角度文字水印
        /// </summary>
        public static void AddWatermark(string inputFilePath, string text, out string outFilePath)
        {
            Console.WriteLine(inputFilePath);
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;
            string     tempPath   = Path.GetDirectoryName(inputFilePath) + "\\" + Path.GetFileNameWithoutExtension(inputFilePath) + "_temp.pdf";

            outFilePath = Path.GetDirectoryName(inputFilePath) + "\\" + Path.GetFileNameWithoutExtension(inputFilePath) + "_watermark.pdf";
            File.Copy(inputFilePath, tempPath);
            try
            {
                pdfReader  = new PdfReader(tempPath);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outFilePath, FileMode.Create));
                int       total = pdfReader.NumberOfPages + 1;
                Rectangle psize = pdfReader.GetPageSize(1);
                //float width = psize.Width;
                //float height = psize.Height;
                PdfContentByte content;
                BaseFont       font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState      gs   = new PdfGState();
                for (int i = 1; i < total; i++)
                {
                    //content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    content        = pdfStamper.GetUnderContent(i); //在内容下方加水印
                    gs.FillOpacity = 0.3f;                          //透明度
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);
                    //开始写入文本
                    content.BeginText();
                    content.SetColorFill(BaseColor.Gray);
                    content.SetFontAndSize(font, 30);
                    content.SetTextMatrix(0, 0);

                    //重复添加水印
                    for (int j = 0; j < 5; j++)
                    {
                        content.ShowTextAligned(Element.ALIGN_CENTER, text, (50.5f + i * 250), (40.0f + j * 150), (total % 2 == 1 ? -45 : 45));
                    }
                    content.EndText();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
                File.Delete(tempPath);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// pdf添加水印
        /// </summary>
        /// <param name="srcFile"></param>
        /// <param name="text"></param>
        /// <param name="dest"></param>
        public static void addWaterMark(String srcFile, String text,
                                        Stream dest)
        {
            // 待加水印的文件
            using (PdfReader reader = new PdfReader(srcFile))
            {
                //FileStream fs = new FileStream("d:/123.pdf", FileMode.OpenOrCreate);
                // 加完水印的文件
                using (PdfStamper stamper = new PdfStamper(reader, dest))
                {
                    int            total = reader.NumberOfPages + 1;
                    PdfContentByte content;
                    // 设置字体
                    BaseFont font = BaseFont.CreateFont();
                    // 循环对每页插入水印
                    for (int i = 1; i < total; i++)
                    {
                        int       textHeight = 60;
                        Rectangle pageSize   = reader.GetPageSize(i);
                        float     pageWidth  = pageSize.Width;
                        float     pageHeigth = pageSize.Height;

                        // 水印的起始
                        content = stamper.GetOverContent(i);
                        // 开始
                        content.BeginText();
                        while (textHeight < pageHeigth - 110)
                        {
                            int textWidth = 40;
                            while (textWidth < pageWidth - 60)
                            {
                                // 设置颜色 默认为蓝色
                                content.SetColorFill(BaseColor.GRAY);
                                // 设置字体及字号
                                content.SetFontAndSize(font, 15);
                                // 设置起始位置
                                // content.setTextMatrix(400, 880);
                                content.SaveState();
                                PdfGState gs1 = new PdfGState();
                                gs1.FillOpacity = 0.2f;
                                content.SetGState(gs1);
                                // 开始写入水印
                                content.ShowTextAligned(Element.ALIGN_LEFT, text, textWidth,
                                                        textHeight, 45);
                                content.RestoreState();

                                textWidth += 60;
                            }
                            textHeight += 110;
                        }
                        content.EndText();
                    }
                    dest.Flush();
                }
            }
        }
        public static byte[] WriteToPdf(string sourceFile, string stringToWriteToPdf)
        {
            PdfReader reader = new PdfReader(sourceFile);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfStamper pdfStamper = new PdfStamper(reader, memoryStream);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    Rectangle pageSize  = reader.GetPageSizeWithRotation(i);
                    float     textAngle = (float)FooTheoryMath.GetHypotenuseAngleInDegreesFrom(pageSize.Height, pageSize.Width);
                    int       rotation  = pageSize.Rotation;
                    if (rotation > 0 && rotation != 90)
                    {
                        textAngle = -textAngle;
                    }
                    PdfContentByte pdfPageContents = pdfStamper.GetOverContent(i);
                    //pageSize.Rotation = 0;
                    //PdfDictionary pageDict = reader.GetPageN(i);
                    //int desiredRot = 0; // 90 degrees clockwise from what it is now
                    //PdfNumber rotation = pageDict.GetAsNumber(PdfName.ROTATE);
                    //if (rotation != null) {
                    //    desiredRot += rotation.IntValue;
                    //    desiredRot %= 360; // must be 0, 90, 180, or 270
                    //}
                    //pageDict.Put(PdfName.ROTATE, new PdfNumber(0));


                    PdfGState gstate = new PdfGState();
                    gstate.FillOpacity   = 0.3f;
                    gstate.StrokeOpacity = 0.5f;
                    pdfPageContents.SaveState();
                    pdfPageContents.SetGState(gstate);
                    //pdfPageContents.SetColorFill(BaseColor.GRAY);
                    pdfPageContents.BeginText();

                    // BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    float size = 60;
                    if (pageSize.Width > 1600)
                    {
                        size = 150;
                    }
                    pdfPageContents.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), size);
                    // pdfPageContents.SetRGBColorFill(0, 0, 0);

                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, stringToWriteToPdf, pageSize.Width / 2, pageSize.Height / 2, textAngle);
                    pdfPageContents.EndText();
                }
                pdfStamper.RotateContents = false;
                pdfStamper.FormFlattening = true;
                pdfStamper.Close();
                //memoryStream.Close();
                reader.Close();
                return(memoryStream.ToArray());
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// 插入文字浮水印
        /// </summary>
        /// <param name="getPDFContent">PDF內容</param>
        /// <param name="textWaterMark">文字浮水印內容</param>
        /// <returns></returns>
        public byte[] InsertWaterMark(
            byte[] getPDFContent,
            string textWaterMark
            )
        {
            MemoryStream msInput = new MemoryStream();

            byte[] result = new byte[] { };

            using (PdfReader pdfReader = new PdfReader(getPDFContent))
            {
                using (PdfStamper pdfStamper = new PdfStamper(pdfReader, msInput))
                {
                    int            pageTotal = pdfReader.NumberOfPages + 1;
                    PdfContentByte content;
                    PdfGState      gs        = new PdfGState();
                    var            unicodefy = new UnicodeFontFactory();

                    // 第一頁索引起始是1
                    for (int i = 1; i < pageTotal; i++)
                    {
                        // 取得當前頁面Size
                        Rectangle psize = pdfReader.GetPageSize(1);

                        // 取得Page 寬與高
                        float width  = psize.Width;
                        float height = psize.Height;

                        content = pdfStamper.GetUnderContent(i); //在内容上方加水印

                        // 設置透明度
                        gs.FillOpacity = 0.3f;
                        content.SetGState(gs);

                        //寫入內容
                        content.BeginText();
                        content.SetColorFill(BaseColor.BLACK);
                        content.SetFontAndSize(unicodefy.KAIUFont, 30);
                        content.SetTextMatrix(0, 0);
                        content.ShowTextAligned(
                            Element.ALIGN_CENTER, // 對齊
                            textWaterMark,        // 內容
                            width / 2,            // X軸
                            height - 200,         // Y軸
                            5.56f                 // 旋轉幅度
                            );
                        content.EndText();
                    }
                }

                msInput.Close();
                result = msInput.ToArray();
            }

            return(result);
        }
Exemplo n.º 14
0
        public static byte[] WaterMarkPdf(string pathfile)
        {
            using (Stream inputPdfStream = new FileStream(@pathfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (MemoryStream outputPdfStream = new MemoryStream())
                {
                    var            reader         = new PdfReader(inputPdfStream);
                    var            stamper        = new PdfStamper(reader, outputPdfStream);
                    PdfContentByte pdfContentByte = null;

                    int c = reader.NumberOfPages;


                    float rotation = 45f;
                    float ageW     = 600;
                    float mPageH   = 842;

                    for (int i = 1; i <= c; i++)
                    {
                        string ARIALUNI_TFF = Path.Combine(HttpContext.Current.Server.MapPath("~/fonts/"), "ARIAL.ttf");
                        //Create a base font object making sure to specify IDENTITY-H
                        BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                        pdfContentByte = stamper.GetOverContent(i);
                        pdfContentByte.SetRGBColorFillF(0.8f, 0.8f, 0.8f);
                        pdfContentByte.SetFontAndSize(bf, 25);
                        float     x      = ageW / 2;
                        float     y      = mPageH / 2;
                        PdfGState gState = new PdfGState();
                        gState.FillOpacity = 0.25f;
                        pdfContentByte.SetGState(gState);
                        pdfContentByte.SetColorFill(BaseColor.BLACK);

                        pdfContentByte.BeginText();
                        pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "SỞ LAO ĐỘNG THƯƠNG BINH VÀ XÃ HỘI HẢI DƯƠNG", x, y, rotation);
                        pdfContentByte.EndText();

                        pdfContentByte.SetRGBColorFillF(0, 0, 0);
                        pdfContentByte.SetFontAndSize(bf, 10.5f);
                        x                  = 10;
                        y                  = mPageH - mPageH * 96 / 100;
                        gState             = new PdfGState();
                        gState.FillOpacity = 0.5f;
                        pdfContentByte.SetGState(gState);
                        pdfContentByte.SetColorFill(BaseColor.BLACK);

                        pdfContentByte.BeginText();
                        pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Cấm sao lưu tài liệu dưới mọi hình thức khi chưa có sự phê duyệt của Sở Lao động Thương binh và Xã hội tỉnh Hải Dương", x, y, 0);
                        pdfContentByte.EndText();
                    }


                    stamper.Close();

                    return(outputPdfStream.ToArray());
                }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 对pdf文档添加文字水印
        /// </summary>
        /// <param name="sourcefile">源文件</param>
        /// <param name="desfile">目的文件</param>
        /// <param name="watermarkText">水印文字</param>
        public static void AddPdfWaterMark(string sourcefile, string desfile, string watermarkText)
        {
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            try
            {
                pdfReader  = new PdfReader(System.IO.File.ReadAllBytes(sourcefile));
                pdfStamper = new PdfStamper(pdfReader, new FileStream(desfile, FileMode.Create));// 设置密码
                int            total = pdfReader.NumberOfPages + 1;
                PdfContentByte content;
                BaseFont       font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState      gs   = new PdfGState();
                gs.FillOpacity = 0.2f;

                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);

                float width  = psize.Width;
                float height = psize.Height;
                int   j      = watermarkText.Length;
                int   rise   = 0;

                for (int i = 1; i < total; i++)
                {
                    rise    = 100;
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    content.BeginText();
                    content.SetColorFill(iTextSharp.text.BaseColor.LIGHT_GRAY);
                    content.SetFontAndSize(font, 60);
                    content.SetTextRise(rise);
                    content.SetGState(gs);
                    content.ShowTextAligned(iTextSharp.text.Element.ALIGN_LEFT, watermarkText, 300, 500, 45);
                    content.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, watermarkText, 400, 400, 45);
                    content.ShowTextAligned(iTextSharp.text.Element.ALIGN_RIGHT, watermarkText, 500, 300, 45);
                    content.EndText();
                }
            }
            catch (Exception ex)
            {
                WriteLog(string.Format("{0},{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }
Exemplo n.º 16
0
        public static void CreatFromTemplate()
        {
            string originalFile   = "Original.pdf";
            string copyOfOriginal = "Copy.pdf";

            using (FileStream fs = new FileStream(originalFile, FileMode.Create, FileAccess.Write, FileShare.None))
                using (Document doc = new Document(PageSize.LETTER))
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
                    {
                        doc.Open();
                        doc.Add(new Paragraph("Hi! I'm Original"));
                        doc.Close();
                    }
            PdfReader reader = new PdfReader(originalFile);

            using (FileStream fs = new FileStream(copyOfOriginal, FileMode.Create, FileAccess.Write, FileShare.None))
                // Creating iTextSharp.text.pdf.PdfStamper object to write
                // Data from iTextSharp.text.pdf.PdfReader object to FileStream object

                using (PdfStamper stamper = new PdfStamper(reader, fs)) {
                    // Getting total number of pages of the Existing Document
                    int pageCount = reader.NumberOfPages;

                    // Create New Layer for Watermark
                    PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
                    // Loop through each Page
                    for (int i = 1; i <= pageCount; i++)
                    {
                        // Getting the Page Size
                        Rectangle rect = reader.GetPageSize(i);

                        // Get the ContentByte object
                        PdfContentByte cb = stamper.GetUnderContent(i);

                        // Tell the cb that the next commands should be "bound" to this new layer
                        cb.BeginLayer(layer);
                        cb.SetFontAndSize(BaseFont.CreateFont(
                                              BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);

                        PdfGState gState = new PdfGState();
                        gState.FillOpacity = 0.25f;
                        cb.SetGState(gState);

                        cb.SetColorFill(BaseColor.BLACK);
                        cb.BeginText();
                        cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "OK COOL A WATERMARK", rect.Width / 2, rect.Height / 2, 45f);
                        cb.EndText();

                        // Close the layer
                        cb.EndLayer();
                    }
                }
        }
Exemplo n.º 17
0
        private void PonerSello(string _Archivo)
        {
            string    path   = @"C:\ProyMondelez\Seguridad\IncidentesWEB\LUPs\Archivos\" + _Archivo;
            PdfReader reader = new PdfReader(path);

            PdfReader.unethicalreading = true;
            FileStream fs       = null;
            PdfStamper stamp    = null;
            Document   document = null;

            try
            {
                document = new Document();
                string outputPdf = String.Format(@"C:\ProyMondelez\Seguridad\IncidentesWEB\LUPs\Archivos\{0}.pdf",
                                                 Guid.NewGuid().ToString());
                fs = new FileStream(outputPdf,
                                    FileMode.CreateNew,
                                    FileAccess.Write);
                stamp = new PdfStamper(reader, fs);
                BaseFont bf =
                    BaseFont.CreateFont(@"c:\windows\fonts\arial.ttf",
                                        BaseFont.CP1252, true);
                PdfGState gs = new PdfGState();
                gs.FillOpacity   = 0.35F;
                gs.StrokeOpacity = 0.35F;
                for (int nPag = 1; nPag <= reader.NumberOfPages; nPag++)
                {
                    Rectangle      tamPagina = reader.GetPageSizeWithRotation(nPag);
                    PdfContentByte over      = stamp.GetOverContent(nPag);
                    over.BeginText();
                    WriteTextToDocument(bf, tamPagina, over, gs, "APROBADO");
                    over.EndText();
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                reader.Close();
                //if (stamp != null) stamp.Close();
                if (fs != null)
                {
                    fs.Close();
                }
                if (document != null)
                {
                    document.Close();
                }
            }
        }
Exemplo n.º 18
0
        // ---------------------------------------------------------------------------

        /**
         * Draws a rectangle
         * @param content the direct content layer
         * @param width the width of the rectangle
         * @param height the height of the rectangle
         */
        public static void DrawRectangle(
            PdfContentByte content, float width, float height)
        {
            content.SaveState();
            PdfGState state = new PdfGState();

            state.FillOpacity = 0.6f;
            content.SetGState(state);
            content.SetRGBColorFill(0xFF, 0xFF, 0xFF);
            content.SetLineWidth(3);
            content.Rectangle(0, 0, width, height);
            content.FillStroke();
            content.RestoreState();
        }
Exemplo n.º 19
0
        private MemoryStream ApplyVerificationStamp2(byte[] file, string stamp)
        {
            var newFile = new MemoryStream();
            // Creating watermark on a separate layer
            // Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
            PdfReader reader1 = new PdfReader(file);

            //using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
            // Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object

            using (PdfStamper stamper = new PdfStamper(reader1, newFile))
            {
                // Getting total number of pages of the Existing Document
                int pageCount = reader1.NumberOfPages;

                // Create New Layer for Watermark
                PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
                // Loop through each Page
                for (int i = 1; i <= pageCount; i++)
                {
                    // Getting the Page Size
                    Rectangle rect = reader1.GetPageSize(i);

                    // Get the ContentByte object
                    PdfContentByte cb = stamper.GetUnderContent(i);

                    // Tell the cb that the next commands should be "bound" to this new layer
                    cb.BeginLayer(layer);
                    cb.SetFontAndSize(BaseFont.CreateFont(
                                          BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 15);

                    PdfGState gState = new PdfGState();
                    gState.FillOpacity = 0.25f;
                    cb.SetGState(gState);

                    cb.SetColorFill(BaseColor.BLACK);
                    cb.BeginText();
                    cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, stamp, 5, 5, 0);
                    cb.EndText();

                    // Close the layer
                    cb.EndLayer();
                }
            }



            return(newFile);
        }
Exemplo n.º 20
0
        public void get_bg()
        {
            PdfContentByte canvas = writer.DirectContent;
            Image          image  = Image.GetInstance(bg_path());

            image.ScaleAbsolute(1200, 1500);
            image.SetAbsolutePosition(0, 0);
            canvas.SaveState();
            PdfGState state = new PdfGState();

            state.FillOpacity = 0.6f;
            canvas.SetGState(state);
            canvas.AddImage(image);
            canvas.RestoreState();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Create the overlay to write out overtop of the files actual contents.
        /// </summary>
        /// <param name="ocrText">Text returned from the LEADTools OCR engine.</param>
        /// <param name="stamper">itxtSharp object that contains file contents and allows overlays.</param>
        /// <returns>The canvas for overlay.</returns>
        private static void AddOverlayToCanvas(string ocrText, PdfStamper stamper)
        {
            var font   = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1250, false);
            var canvas = stamper.GetOverContent(1);
            var gs1    = new PdfGState
            {
                FillOpacity   = 0.0f,
                StrokeOpacity = 0.0f
            };

            canvas.SetGState(gs1);
            canvas.SetFontAndSize(font, 1);
            canvas.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ocrText, 25, 3, 0);
            canvas.ShowTextAligned(PdfContentByte.ALIGN_LEFT, @"PAGE-1", 3, 3, 0);
        }
Exemplo n.º 22
0
        public void TransparencyCheckTest()
        {
            string     filename = OUT + "TransparencyCheckTest1.pdf";
            FileStream fos      = new FileStream(filename, FileMode.Create);
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_2B);

            document.Open();

            PdfContentByte canvas = writer.DirectContent;

            canvas.SaveState();
            PdfGState gs = new PdfGState();

            gs.BlendMode = PdfGState.BM_DARKEN;
            canvas.SetGState(gs);
            canvas.Rectangle(100, 100, 100, 100);
            canvas.Fill();
            canvas.RestoreState();

            canvas.SaveState();
            gs           = new PdfGState();
            gs.BlendMode = new PdfName("Lighten");
            canvas.SetGState(gs);
            canvas.Rectangle(200, 200, 100, 100);
            canvas.Fill();
            canvas.RestoreState();

            bool exception = false;

            canvas.SaveState();
            gs           = new PdfGState();
            gs.BlendMode = new PdfName("UnknownBM");
            canvas.SetGState(gs);
            canvas.Rectangle(300, 300, 100, 100);
            canvas.Fill();
            canvas.RestoreState();
            try {
                document.Close();
            }
            catch (PdfAConformanceException e) {
                exception = true;
            }
            if (!exception)
            {
                Assert.Fail("PdfAConformance exception should be thrown on unknown blend mode.");
            }
        }
Exemplo n.º 23
0
        public void RoundRectangle(float xInit, float yInit, float width, float height, float radius = 0, float lineWidth = 1, float opacity = 0, BaseColor boarderColor = null, BaseColor insideColor = null)
        {
            var gs1 = new PdfGState
            {
                FillOpacity = opacity,
            };

            _contentByte.SetGState(gs1);
            _contentByte.SaveState();
            _contentByte.SetColorFill(insideColor ?? BaseColor.White);
            _contentByte.SetLineWidth(lineWidth);
            _contentByte.SetColorStroke(boarderColor ?? BaseColor.Black);
            _contentByte.RoundRectangle(xInit, yInit, width, height, radius);
            _contentByte.FillStroke();
            _contentByte.RestoreState();
        }
Exemplo n.º 24
0
    /// <summary>
    /// Create the overlay to write out overtop of the files actual contents.
    /// </summary>
    /// <param name="ocrText">Text returned from the LEADTools OCR engine.</param>
    /// <param name="stamper">itxtSharp object that contains file contents and allows overlays.</param>
    /// <returns>The canvas for overlay.</returns>
    private static PdfContentByte AddOverlayToCanvas(string ocrText, PdfStamper stamper)
    {
        BaseFont       font   = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1250, false);
        PdfContentByte canvas = stamper.GetOverContent(1);
        PdfGState      gs1    = new PdfGState();

        gs1.FillOpacity   = 0.0f;
        gs1.StrokeOpacity = 0.0f;

        canvas.SetGState(gs1);
        canvas.SetFontAndSize(font, 1);
        canvas.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ocrText, 25, 3, 0);
        canvas.ShowTextAligned(PdfContentByte.ALIGN_LEFT, @"PAGE-1", 3, 3, 0);

        return(canvas);
    }
Exemplo n.º 25
0
        public void FillBox(float x, float y, float width, float height, BaseColor color)
        {
            var state = new PdfGState {
                FillOpacity = 0.5f
            };

            ContentByte.SetGState(state);

            ContentByte.SetLineWidth(1.0f);
            ContentByte.Rectangle(x, y, width, height);
            ContentByte.SetColorFill(color);
            ContentByte.FillStroke();

            state.FillOpacity = 1f;
            ContentByte.SetGState(state);
        }
        private void InsertText(PdfContentByte cb, int fontSize, int x, int y, String text, float angle, int red, int green, int blue, float opacity)
        {
            // Idea from https://forums.asp.net/t/1360567.aspx?iText+Sharp+and+text+position

            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            cb.BeginText();
            cb.SetFontAndSize(bf, fontSize);
            cb.SetRGBColorFill(red, green, blue);
            PdfGState gstate = new PdfGState();

            gstate.FillOpacity = opacity;
            cb.SetGState(gstate);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, angle);
            cb.EndText();
        }
Exemplo n.º 27
0
        private static byte[] SetWatermark(WatermarkSetting waterMark, byte[] bytes)
        {
            if (waterMark == null || string.IsNullOrEmpty(waterMark.Text))
            {
                return(bytes);
            }
            var gs            = new PdfGState();
            var pdfReder      = new PdfReader(bytes);
            var fileName      = DateTime.Now.ToFileTime() + Guid.NewGuid().ToString() + ".pdf";
            var outPutPdfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs", fileName);
            var pdfStamper    = new PdfStamper(pdfReder, new FileStream(outPutPdfPath, FileMode.Create));

            try
            {
                var fontPath = AppConfig.GetFileByAbsolutePath("STCAIYUN.TTF");
                var font     = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                for (var i = 1; i <= pdfReder.NumberOfPages; i++)
                {
                    var width   = pdfReder.GetPageSize(i).Width;
                    var height  = pdfReder.GetPageSize(i).Height;
                    var content = pdfStamper.GetOverContent(i);
                    //透明度
                    gs.FillOpacity = 0.4f;
                    content.SetGState(gs);
                    //开始写入文本
                    content.BeginText();
                    content.SetColorFill(BaseColor.BLACK);
                    content.SetFontAndSize(font, waterMark.Size);
                    content.SetTextMatrix(5, 10);
                    content.ShowTextAligned(Element.ALIGN_CENTER, waterMark.Text, width / 2, height / 2 - 50, 35);
                    content.SetColorFill(BaseColor.BLACK);
                    content.EndText();
                }
            }
            catch (Exception)
            {
                return(bytes);
            }
            finally
            {
                pdfStamper.Close();
                pdfReder.Close();
            }

            return(GetFileBytes(outPutPdfPath));
        }
        // private void highlightPDFAnnotation(string readerPath, string outputFile, int pageno, string[] highlightText)
        private void highlightPDFAnnotation(string readerPath, string outputFile, string[] highlightText)
        {
            PdfReader      reader = new PdfReader(readerPath);
            PdfContentByte canvas;

            using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (PdfStamper stamper = new PdfStamper(reader, fs))
                {
                    int pageCount = reader.NumberOfPages;
                    for (int pageno = 1; pageno <= pageCount; pageno++)
                    {
                        var strategy = new HighLightTextLocation();
                        strategy.UndercontentHorizontalScaling = 100;

                        string currentText = PdfTextExtractor.GetTextFromPage(reader, pageno, strategy);
                        for (int i = 0; i < highlightText.Length; i++)
                        {
                            List <Rectangle> MatchesFound = strategy.GetTextLocations(highlightText[i].Trim(), StringComparison.CurrentCultureIgnoreCase);
                            foreach (Rectangle rect in MatchesFound)
                            {
                                float[] quad = { rect.Left - 3.0f, rect.Bottom, rect.Right, rect.Bottom, rect.Left - 3.0f, rect.Top + 1.0f, rect.Right, rect.Top + 1.0f };
                                //Create our hightlight
                                PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, null, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                                //Set the color
                                highlight.Color = BaseColor.YELLOW;

                                PdfAppearance appearance = PdfAppearance.CreateAppearance(stamper.Writer, rect.Width, rect.Height);
                                PdfGState     state      = new PdfGState();
                                state.BlendMode = new PdfName("Multiply");
                                appearance.SetGState(state);
                                appearance.Rectangle(0, 0, rect.Width, rect.Height);
                                appearance.SetColorFill(BaseColor.YELLOW);
                                appearance.Fill();

                                highlight.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, appearance);

                                //Add the annotation
                                stamper.AddAnnotation(highlight, pageno);
                            }
                        }
                    }
                }
            }
            reader.Close();
        }
Exemplo n.º 29
0
// ---------------------------------------------------------------------------

        /**
         * Prints 3 circles in different colors that intersect with eachother.
         *
         * @param x
         * @param y
         * @param cb
         * @throws Exception
         */
        public static void PictureCircles(float x, float y, PdfContentByte cb)
        {
            PdfGState gs = new PdfGState();

            gs.BlendMode   = PdfGState.BM_MULTIPLY;
            gs.FillOpacity = 1f;
            cb.SetGState(gs);
            cb.SetColorFill(new CMYKColor(0f, 0f, 0f, 0.15f));
            cb.Circle(x + 75, y + 75, 70);
            cb.Fill();
            cb.Circle(x + 75, y + 125, 70);
            cb.Fill();
            cb.Circle(x + 125, y + 75, 70);
            cb.Fill();
            cb.Circle(x + 125, y + 125, 70);
            cb.Fill();
        }
Exemplo n.º 30
0
        internal void Rectangle(float xInit, float yInit, float width, float height, float widthLine, float radius, BaseColor boaderColor, BaseColor internColor, float opacity)
        {
            this._contentByte.SetColorStroke(boaderColor);
            this._contentByte.SetColorFill(internColor);
            this._contentByte.SaveState();
            var gs1 = new PdfGState
            {
                FillOpacity = opacity
            };

            this._contentByte.SetGState(gs1);
            this._contentByte.RoundRectangle(xInit, yInit, width, height, radius);
            this._contentByte.SetLineWidth(widthLine);
            this._contentByte.FillStroke();
            this._contentByte.RestoreState();
            SetAtualPosition(yInit + 5);
        }