Inheritance: PdfDictionary
        // 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();
        }
Example #2
1
        private static void AddWaterMarkText(PdfContentByte directContent, string textWatermark, BaseFont font, float fontSize, float angle, BaseColor color, Rectangle realPageSize)
        {
            var gstate = new PdfGState { FillOpacity = 0.2f, StrokeOpacity = 0.2f };

            directContent.SaveState();
            directContent.SetGState(gstate);
            directContent.SetColorFill(color);
            directContent.BeginText();
            directContent.SetFontAndSize(font, fontSize);

            var x = (realPageSize.Right + realPageSize.Left) / 2;
            var y = (realPageSize.Bottom + realPageSize.Top) / 2;

            directContent.ShowTextAligned(Element.ALIGN_CENTER, textWatermark, x, y, angle);
            directContent.EndText();
            directContent.RestoreState();
        }
 /// <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();
 }
Example #4
0
// ---------------------------------------------------------------------------
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {    
        // step 1
        using (Document document = new Document(new Rectangle(850, 600))) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          PdfContentByte canvas = writer.DirectContent;
          // add the clipped image
          Image img = Image.GetInstance(
            Path.Combine(Utility.ResourceImage, RESOURCE)
          );
          float w = img.ScaledWidth;
          float h = img.ScaledHeight;
          canvas.Ellipse(1, 1, 848, 598);
          canvas.Clip();
          canvas.NewPath();
          canvas.AddImage(img, w, 0, 0, h, 0, -600);

          // Create a transparent PdfTemplate
          PdfTemplate t2 = writer.DirectContent.CreateTemplate(850, 600);
          PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
          transGroup.Put( PdfName.CS, PdfName.DEVICEGRAY);
          transGroup.Isolated = true;
          transGroup.Knockout = false;
          t2.Group = transGroup;

          // Add transparent ellipses to the template
          int gradationStep = 30;
          float[] gradationRatioList = new float[gradationStep];
          for(int i = 0; i < gradationStep; i++) {
/*
* gotta love .NET, guess they forgot to copy java.lang.Math.toRadians
*/
            double radians = (Math.PI / 180) * 90.0f / gradationStep * (i + 1);
            gradationRatioList[i] = 1 - (float) Math.Sin(radians);
          }
          for(int i = 1; i < gradationStep + 1; i++) {
              t2.SetLineWidth(5 * (gradationStep + 1 - i));
              t2.SetGrayStroke(gradationRatioList[gradationStep - i]);
              t2.Ellipse(0, 0, 850, 600);
              t2.Stroke();
          }
          
          // Create an image mask for the direct content
          PdfDictionary maskDict = new PdfDictionary();
          maskDict.Put(PdfName.TYPE, PdfName.MASK);
          maskDict.Put(PdfName.S, new PdfName("Luminosity"));
          maskDict.Put(new PdfName("G"), t2.IndirectReference);
          PdfGState gState = new PdfGState();
          gState.Put(PdfName.SMASK, maskDict );
          canvas.SetGState(gState);
          
          canvas.AddTemplate(t2, 0, 0);        
        }
        return ms.ToArray();
      }
    }
Example #5
0
        }     //  end setGraphTitle

        private void AddWatermarkText(string sourceFile, string outputFile, string watermarkText, float watermarkFontSize, float watermarkFontOpacity, float watermarkRotation)
        {
            iTextSharp.text.pdf.PdfReader      reader       = null;
            iTextSharp.text.pdf.PdfStamper     stamper      = null;
            iTextSharp.text.pdf.PdfGState      gstate       = null;
            iTextSharp.text.pdf.PdfContentByte underContent = null;
            iTextSharp.text.Rectangle          rect         = null;

            int pageCount = 0;

            try
            {
                reader  = new iTextSharp.text.pdf.PdfReader(sourceFile);
                rect    = reader.GetPageSizeWithRotation(1);
                stamper = new PdfStamper(reader, new System.IO.FileStream(outputFile, System.IO.FileMode.CreateNew), '\0', true);

                iTextSharp.text.pdf.BaseFont watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER,
                                                                                                     iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
                gstate               = new iTextSharp.text.pdf.PdfGState();
                gstate.FillOpacity   = watermarkFontOpacity;
                gstate.StrokeOpacity = watermarkFontOpacity;
                pageCount            = reader.NumberOfPages;
                for (int i = 1; i <= pageCount; i++)
                {
                    underContent = stamper.GetUnderContent(i);
                    underContent.SaveState();
                    underContent.SetGState(gstate);
                    underContent.SetColorFill(iTextSharp.text.BaseColor.DARK_GRAY);
                    underContent.BeginText();
                    underContent.SetFontAndSize(watermarkFont, watermarkFontSize);
                    underContent.SetTextMatrix(30, 30);
                    underContent.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, watermarkRotation);
                    underContent.EndText();
                    underContent.RestoreState();
                }   //  end for i loop

                stamper.Close();
                reader.Close();
            }   //  end try
            catch (Exception ex)
            {
                throw ex;
            } //  end
            return;
        }     //  end AddWatermark
        /// <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));
            PdfContentByte under = stamper.GetUnderContent(1);

            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)),
                297, 421, 45);
            under.RestoreState();
            stamper.Close();
            reader.Close();
        }
Example #7
0
        public void TransparencyCheckTest1() {
            string filename = OUT + "pdfa2TransparencyCheckTest1.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 conformanceExceptionThrown = false;
            try {
                canvas.SaveState();
                gs = new PdfGState();
                gs.BlendMode = new PdfName("UnknownBM");
                canvas.SetGState(gs);
                canvas.Rectangle(300, 300, 100, 100);
                canvas.Fill();
                canvas.RestoreState();

                document.Close();
            }
            catch (PdfAConformanceException pdface) {
                conformanceExceptionThrown = true;
            }

            if (!conformanceExceptionThrown)
                Assert.Fail("PdfAConformance exception should be thrown on unknown blend mode.");
        }
Example #8
0
        public void TransparencyCheckTest2() {
            Document document = new Document();
            try {
                // step 2
                PdfAWriter writer = PdfAWriter.GetInstance(document,
                    new FileStream(OUT + "pdfa2TransperancyCheckTest2.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_2B);
                writer.CreateXmpMetadata();
                // step 3
                document.Open();
                PdfDictionary sec = new PdfDictionary();
                sec.Put(PdfName.GAMMA, new PdfArray(new float[] {2.2f, 2.2f, 2.2f}));
                sec.Put(PdfName.MATRIX,
                    new PdfArray(new float[]
                    {0.4124f, 0.2126f, 0.0193f, 0.3576f, 0.7152f, 0.1192f, 0.1805f, 0.0722f, 0.9505f}));
                sec.Put(PdfName.WHITEPOINT, new PdfArray(new float[] {0.9505f, 1f, 1.089f}));
                PdfArray arr = new PdfArray(PdfName.CALRGB);
                arr.Add(sec);
                writer.SetDefaultColorspace(PdfName.DEFAULTRGB, writer.AddToBody(arr).IndirectReference);
                // step 4
                PdfContentByte cb = writer.DirectContent;
                float gap = (document.PageSize.Width - 400)/3;

                PictureBackdrop(gap, 500f, cb);
                PictureBackdrop(200 + 2*gap, 500, cb);
                PictureBackdrop(gap, 500 - 200 - gap, cb);
                PictureBackdrop(200 + 2*gap, 500 - 200 - gap, cb);

                PictureCircles(gap, 500, cb);
                cb.SaveState();
                PdfGState gs1 = new PdfGState();
                gs1.FillOpacity = 0.5f;
                cb.SetGState(gs1);
                PictureCircles(200 + 2*gap, 500, cb);
                cb.RestoreState();

                cb.SaveState();
                PdfTemplate tp = cb.CreateTemplate(200, 200);
                PdfTransparencyGroup group = new PdfTransparencyGroup();
                tp.Group = group;
                PictureCircles(0, 0, tp);
                cb.SetGState(gs1);
                cb.AddTemplate(tp, gap, 500 - 200 - gap);
                cb.RestoreState();

                cb.SaveState();
                tp = cb.CreateTemplate(200, 200);
                tp.Group = group;
                PdfGState gs2 = new PdfGState();
                gs2.FillOpacity = 0.5f;
                gs2.BlendMode = PdfGState.BM_HARDLIGHT;
                tp.SetGState(gs2);
                PictureCircles(0, 0, tp);
                cb.AddTemplate(tp, 200 + 2*gap, 500 - 200 - gap);
                cb.RestoreState();

                Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf",
                    BaseFont.WINANSI, true);
                font.Color = BaseColor.BLACK;
                cb.ResetRGBColorFill();
                ColumnText ct = new ColumnText(cb);
                Phrase ph = new Phrase("Ungrouped objects\nObject opacity = 1.0", font);
                ct.SetSimpleColumn(ph, gap, 0, gap + 200, 500, 18, Element.ALIGN_CENTER);
                ct.Go();

                ph = new Phrase("Ungrouped objects\nObject opacity = 0.5", font);
                ct.SetSimpleColumn(ph, 200 + 2*gap, 0, 200 + 2*gap + 200, 500,
                    18, Element.ALIGN_CENTER);
                ct.Go();

                ph = new Phrase("Transparency group\nObject opacity = 1.0\nGroup opacity = 0.5\nBlend mode = Normal",
                    font);
                ct.SetSimpleColumn(ph, gap, 0, gap + 200, 500 - 200 - gap, 18, Element.ALIGN_CENTER);
                ct.Go();

                ph = new Phrase(
                    "Transparency group\nObject opacity = 0.5\nGroup opacity = 1.0\nBlend mode = HardLight", font);
                ct.SetSimpleColumn(ph, 200 + 2*gap, 0, 200 + 2*gap + 200, 500 - 200 - gap,
                    18, Element.ALIGN_CENTER);
                ct.Go();
                //ICC_Profile icc = ICC_Profile.GetInstance(File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read));
                //writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            }
            catch (DocumentException de) {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe) {
                Console.Error.WriteLine(ioe.Message);
            }

            bool conformanceExceptionThrown = false;
            try {
                document.Close();
            }
            catch (PdfAConformanceException pdface) {
                conformanceExceptionThrown = true;
            }

            if (!conformanceExceptionThrown)
                Assert.Fail("PdfAConformance exception should be thrown on unknown blend mode.");
        }
Example #9
0
 /**
  * Prints 3 circles in different colors that intersect with eachother.
  *
  * @param x
  * @param y
  * @param cb
  * @throws Exception
  */
 private void PictureCircles(float x, float y, PdfContentByte cb, PdfWriter writer) {
     PdfGState gs = new PdfGState();
     gs.BlendMode = PdfGState.BM_MULTIPLY;
     gs.FillOpacity = 1f;
     cb.SetGState(gs);
     cb.SetColorFill(BaseColor.LIGHT_GRAY);
     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();
 }
Example #10
0
        public static Point DrawUpperRectangle(PdfContentByte content, Rectangle pageRect, float barSize)
        {
            content.SaveState();
            var state = new PdfGState {FillOpacity = FillOpacity};
            content.SetGState(state);
            content.SetColorFill(BaseColor.BLACK);

            content.SetLineWidth(0);
            var result = new Point(SideBorder + BorderPage,
                                   pageRect.Height - (BorderPage + LeaderEdge + BarHeight + 1));
            content.Rectangle(result.X, result.Y, barSize, BarHeight);
            content.ClosePathFillStroke();
            content.RestoreState();
            return result;
        }
Example #11
0
        public static MemoryStream Generate(CompetitorCardModel competitor, string competitionImagePath, string competitionName)
        {
            var userImagePath =
                HttpContext.Current.Server.MapPath(
                    "~/App_Data/User_Image/" + competitor.Image);

            var universityLogoPath = HttpContext.Current.Server.MapPath(
                    "~/Content/IAU_Najafabad_Branch_logo.png");

            var competitionLogoPath = HttpContext.Current.Server.MapPath(
                    "~/App_Data/Logo_Image/" + competitionImagePath);

            var memoryStream = new MemoryStream();

            var pageSize = PageSize.A6.Rotate();

            Document doc = new Document(pageSize);

            doc.SetMargins(18f, 18f, 15f, 2f);


            PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);

            writer.CloseStream = false;

            doc.Open();

            PdfContentByte canvas = writer.DirectContentUnder;

            var logoImg = Image.GetInstance(competitionLogoPath);

            logoImg.SetAbsolutePosition(0, 0);

            logoImg.ScaleAbsolute(pageSize);

            PdfGState graphicsState = new PdfGState { FillOpacity = 0.2F };

            canvas.SetGState(graphicsState);

            canvas.AddImage(logoImg);


            var table = new PdfPTable(3)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
            };

            var universityLogoImage = Image.GetInstance(universityLogoPath);

            var cell1 = new PdfPCell(universityLogoImage)
            {
                HorizontalAlignment = 0,
                Border = 0
            };

            universityLogoImage.ScaleAbsolute(70, 100);

            table.AddCell(cell1);


            var cell2 = new PdfPCell(new Phrase(string.Format("کارت {0}", competitionName), GetTahoma()))
            {
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                HorizontalAlignment = 1,
                Border = 0
            };

            table.AddCell(cell2);


            var userImage = Image.GetInstance(userImagePath);

            userImage.Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
            userImage.BorderWidth = 1f;
            userImage.BorderColor = new BaseColor(ColorTranslator.FromHtml("#CCCCCC").ToArgb());

            var cell3 = new PdfPCell(userImage)
            {
                HorizontalAlignment = 2,
                Border = 0
            };

            userImage.ScaleAbsolute(70, 100);

            table.AddCell(cell3);

            int[] firstTablecellwidth = { 10, 20, 10 };

            table.SetWidths(firstTablecellwidth);

            doc.Add(table);


            var table2 = new PdfPTable(4)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
                SpacingBefore = 15
            };

            var celll0 = new PdfPCell(new Phrase("نام:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0

            };
            var celll1 = new PdfPCell(new Phrase(competitor.FirstName, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0

            };

            var celll2 = new PdfPCell(new Phrase("نام خانوادگی:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0

            };

            var celll3 = new PdfPCell(new Phrase(competitor.LastName, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0

            };

            table2.AddCell(celll0);
            table2.AddCell(celll1);
            table2.AddCell(celll2);
            table2.AddCell(celll3);


            int[] secondTablecellwidth = { 20, 15, 20, 15 };

            table2.SetWidths(secondTablecellwidth);

            doc.Add(table2);


            var table3 = new PdfPTable(4)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
                SpacingBefore = 15,

            };


            var cellll0 = new PdfPCell(new Phrase("شماره\nدانشجویی:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };
            var cellll1 = new PdfPCell(new Phrase(competitor.StudentNumber, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var cellll2 = new PdfPCell(new Phrase("کد ملی:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var cellll3 = new PdfPCell(new Phrase(competitor.NationalCode, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            table3.AddCell(cellll0);
            table3.AddCell(cellll1);
            table3.AddCell(cellll2);
            table3.AddCell(cellll3);


            int[] table3Cellwidth = { 20, 15, 20, 15 };

            table3.SetWidths(table3Cellwidth);

            doc.Add(table3);


            var table4 = new PdfPTable(4)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
                SpacingBefore = 15,

            };


            var celllll0 = new PdfPCell(new Phrase("", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0,
            };
            var celllll1 = new PdfPCell(new Phrase(competitor.University, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var celllll2 = new PdfPCell(new Phrase("محل اسکان:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var celllll3 = new PdfPCell(new Phrase(string.Format("{0}-{1}", competitor.Dorm, competitor.DormNumber), GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            table4.AddCell(celllll1);
            table4.AddCell(celllll0);
            table4.AddCell(celllll2);
            table4.AddCell(celllll3);


            int[] table4Cellwidth = { 20, 15, 0, 35 };

            table4.SetWidths(table4Cellwidth);

            doc.Add(table4);



            var table5 = new PdfPTable(4)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
                SpacingBefore = 15,

            };


            var cellllll0 = new PdfPCell(new Phrase("رشته ورزشی:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };
            var cellllll1 = new PdfPCell(new Phrase(competitor.Sport, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var cellllll2 = new PdfPCell(new Phrase("", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var cellllll3 = new PdfPCell(new Phrase("", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            table5.AddCell(cellllll0);
            table5.AddCell(cellllll1);
            table5.AddCell(cellllll2);
            table5.AddCell(cellllll3);


            int[] table5Cellwidth = { 0, 0, 55, 15 };

            table5.SetWidths(table5Cellwidth);

            doc.Add(table5);

            doc.Close();


            return memoryStream;
        }
Example #12
0
        /// <summary>
        /// 添加倾斜水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="waterMarkName"></param>
        /// <param name="userPassWord"></param>
        /// <param name="ownerPassWord"></param>
        /// <param name="permission"></param>
        public static void setWatermark(string inputfilepath, string outputfilepath, string waterMarkName, string userPassWord, string ownerPassWord, int permission)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                // 设置密码
                //pdfStamper.SetEncryption(false,userPassWord, ownerPassWord, permission);

                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;//透明度

                int j = waterMarkName.Length;
                char c;
                int rise = 0;
                for (int i = 1; i < total; i++)
                {
                    rise = 500;
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印

                    content.BeginText();
                    content.SetColorFill(BaseColor.DARK_GRAY);
                    content.SetFontAndSize(font, 50);
                    // 设置水印文字字体倾斜 开始
                    if (j >= 15)
                    {
                        content.SetTextMatrix(200, 120);
                        for (int k = 0; k < j; k++)
                        {
                            content.SetTextRise(rise);
                            c = waterMarkName[k];
                            content.ShowText(c + "");
                            rise -= 20;
                        }
                    }
                    else
                    {
                        content.SetTextMatrix(180, 100);
                        for (int k = 0; k < j; k++)
                        {
                            content.SetTextRise(rise);
                            c = waterMarkName[k];
                            content.ShowText(c + "");
                            rise -= 18;
                        }
                    }
                    // 字体设置结束
                    content.EndText();
                    // 画一个圆
                    //content.Ellipse(250, 450, 350, 550);
                    //content.SetLineWidth(1f);
                    //content.Stroke();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

                if (pdfStamper != null)
                    pdfStamper.Close();

                if (pdfReader != null)
                    pdfReader.Close();
            }
        }
Example #13
0
        public static void DrawSquare(PdfContentByte content, Point point, System.Data.IDataReader reader)
        {
            content.SaveState();
            var state = new PdfGState {FillOpacity = FillOpacity};
            content.SetGState(state);
            var color = new CMYKColor(reader.GetFloat(1), reader.GetFloat(2), reader.GetFloat(3), reader.GetFloat(4));
            content.SetColorFill(color);

            content.SetLineWidth(0);
            content.Rectangle(point.X, point.Y, PatchSize, PatchSize);
            content.Fill();
            content.RestoreState();
        }
Example #14
0
        virtual public void TransparencyCheckTest2()
        {
            string filename = OUT + "TransparencyCheckTest2.pdf";
            FileStream fos = new FileStream(filename, FileMode.Create);

            Document document = new Document();

            PdfAWriter writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_1B);
            writer.CreateXmpMetadata();

            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            PdfContentByte canvas = writer.DirectContent;
            PdfGState gs = new PdfGState();
            gs.Put(PdfName.SMASK, new PdfName("Test"));
            canvas.SetGState(gs);

            bool exceptionThrown = false;
            try
            {
                document.Close();
            }
            catch (PdfAConformanceException e)
            {
                if (e.GetObject().Equals(gs))
                {
                    exceptionThrown = true;
                }
            }
            if (!exceptionThrown)
                Assert.Fail("PdfAConformanceException should be thrown.");
        }
Example #15
0
        private static void WriteTextToDocument(BaseFont bf,Rectangle tamPagina,
            PdfContentByte over,PdfGState gs,string texto)
        {
            over.SetGState(gs);

            over.SetRGBColorFill(220, 220, 220);

            over.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);

            over.SetFontAndSize(bf, 46);

            Single anchoDiag =

                (Single)Math.Sqrt(Math.Pow((tamPagina.Height - 120), 2)

                + Math.Pow((tamPagina.Width - 60), 2));

            Single porc = (Single)100

                * (anchoDiag / bf.GetWidthPoint(texto, 46));

            over.SetHorizontalScaling(porc);

            double angPage = (-1)

            * Math.Atan((tamPagina.Height - 60) / (tamPagina.Width - 60));

            over.SetTextMatrix((float)Math.Cos(angPage),

                       (float)Math.Sin(angPage),

                       (float)((-1F) * Math.Sin(angPage)),

                       (float)Math.Cos(angPage),

                       30F,

                       (float)tamPagina.Height - 60);

            over.ShowText(texto);
        }
Example #16
0
        public void EgsCheckTest3() {
            Document document = new Document();
            PdfAWriter writer = PdfAWriter.GetInstance(document,
                new FileStream(OUT + "pdfa2EgsCheckTest3.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_2A);
            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));

            PdfContentByte canvas = writer.DirectContent;
            PdfGState gs = new PdfGState();
            PdfDictionary dict = new PdfDictionary();
            dict.Put(PdfName.HALFTONETYPE, new PdfNumber(5));
            dict.Put(PdfName.HALFTONENAME, new PdfName("Test"));
            gs.Put(PdfName.HT, dict);
            canvas.SetGState(gs);

            bool exceptionThrown = false;
            try {
                document.Close();
            }
            catch (PdfAConformanceException e) {
                exceptionThrown = true;
            }
            if (!exceptionThrown)
                Assert.Fail("PdfAConformanceException should be thrown.");
        }
Example #17
0
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte cb = writer.DirectContent;
        float gap = (document.PageSize.Width - 400) / 3;

        PictureBackdrop(gap, 500, cb);
        PictureBackdrop(200 + 2 * gap, 500, cb);
        PictureBackdrop(gap, 500 - 200 - gap, cb);
        PictureBackdrop(200 + 2 * gap, 500 - 200 - gap, cb);

        PictureCircles(gap, 500, cb);
        cb.SaveState();
        PdfGState gs1 = new PdfGState();
        gs1.FillOpacity = 0.5f;
        cb.SetGState(gs1);
        PictureCircles(200 + 2 * gap, 500, cb);
        cb.RestoreState();

        cb.SaveState();
        PdfTemplate tp = cb.CreateTemplate(200, 200);
        PdfTransparencyGroup group = new PdfTransparencyGroup();
        tp.Group = group;
        PictureCircles(0, 0, tp);
        cb.SetGState(gs1);
        cb.AddTemplate(tp, gap, 500 - 200 - gap);
        cb.RestoreState();

        cb.SaveState();
        tp = cb.CreateTemplate(200, 200);
        tp.Group = group;
        PdfGState gs2 = new PdfGState();
        gs2.FillOpacity = 0.5f;
        gs2.BlendMode = PdfGState.BM_HARDLIGHT;
        tp.SetGState(gs2);
        PictureCircles(0, 0, tp);
        cb.AddTemplate(tp, 200 + 2 * gap, 500 - 200 - gap);
        cb.RestoreState();

        cb.ResetRGBColorFill();
        ColumnText ct = new ColumnText(cb);
        Phrase ph = new Phrase("Ungrouped objects\nObject opacity = 1.0");
        ct.SetSimpleColumn(ph, gap, 0, gap + 200, 500, 18,
          Element.ALIGN_CENTER
        );
        ct.Go();

        ph = new Phrase("Ungrouped objects\nObject opacity = 0.5");
        ct.SetSimpleColumn(ph, 200 + 2 * gap, 0, 200 + 2 * gap + 200, 500,
          18, Element.ALIGN_CENTER
        );
        ct.Go();

        ph = new Phrase(
          "Transparency group\nObject opacity = 1.0\nGroup opacity = 0.5\nBlend mode = Normal"
        );
        ct.SetSimpleColumn(ph, gap, 0, gap + 200, 500 - 200 - gap, 18,
          Element.ALIGN_CENTER
        );
        ct.Go();

        ph = new Phrase(
          "Transparency group\nObject opacity = 0.5\nGroup opacity = 1.0\nBlend mode = HardLight"
        );
        ct.SetSimpleColumn(ph, 200 + 2 * gap, 0, 200 + 2 * gap + 200,
          500 - 200 - gap, 18, Element.ALIGN_CENTER
        );
        ct.Go();
      }
    }
Example #18
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();
    }
        public static MemoryStream Generate(TechnicalStaffCardModel technicalStaff, string competitionImagePath, string competitionName)
        {
            var userImagePath =
                HttpContext.Current.Server.MapPath(
                    "~/App_Data/TechnicalStaff_Image/" + technicalStaff.Image);

            var universityLogoPath = HttpContext.Current.Server.MapPath(
                    "~/Content/IAU_Najafabad_Branch_logo.png");

            var competitionLogoPath = HttpContext.Current.Server.MapPath(
                    "~/App_Data/Logo_Image/" + competitionImagePath);

            var fs = new MemoryStream(); //new FileStream(HttpContext.Current.Server.MapPath("~/App_Data/Pdf/aaa.pdf"), FileMode.Create);

            Document doc = new Document(new Rectangle(PageSize.A6.Rotate()));

            doc.SetMargins(18f, 18f, 15f, 2f);

            PdfWriter writer = PdfWriter.GetInstance(doc, fs);

            writer.CloseStream = false;

            doc.Open();

            PdfContentByte canvas = writer.DirectContentUnder;

            var logoImg = Image.GetInstance(competitionLogoPath);

            logoImg.SetAbsolutePosition(0, 0);

            logoImg.ScaleAbsolute(PageSize.A6.Rotate());

            PdfGState graphicsState = new PdfGState();
            graphicsState.FillOpacity = 0.2F;  // (or whatever)
            //set graphics state to pdfcontentbyte    
            canvas.SetGState(graphicsState);

            canvas.AddImage(logoImg);

            //create new graphics state and assign opacity    



            var table = new PdfPTable(3)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
            };

            var imgg = Image.GetInstance(universityLogoPath);

            var cell1 = new PdfPCell(imgg)
            {
                HorizontalAlignment = 0,
                Border = 0

            };

            imgg.ScaleAbsolute(70, 100);

            table.AddCell(cell1);


            var cell2 = new PdfPCell(new Phrase(string.Format("کارت {0}", competitionName), GetTahoma()))
            {
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                HorizontalAlignment = 1,
                Border = 0

            };

            table.AddCell(cell2);


            var imgg2 = Image.GetInstance(userImagePath);

            imgg2.Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
            imgg2.BorderWidth = 1f;
            imgg2.BorderColor = new BaseColor(ColorTranslator.FromHtml("#CCCCCC").ToArgb());

            var cell3 = new PdfPCell(imgg2)
            {
                HorizontalAlignment = 2,
                Border = 0
            };

            imgg2.ScaleAbsolute(70, 100);

            table.AddCell(cell3);


            int[] firstTablecellwidth = { 10, 20, 10 };

            table.SetWidths(firstTablecellwidth);

            doc.Add(table);


            var table2 = new PdfPTable(4)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
                SpacingBefore = 15
            };


            var celll0 = new PdfPCell(new Phrase("نام:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0

            };
            var celll1 = new PdfPCell(new Phrase(technicalStaff.FirstName, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0

            };

            var celll2 = new PdfPCell(new Phrase("نام خانوادگی:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0

            };

            var celll3 = new PdfPCell(new Phrase(technicalStaff.LastName, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0

            };

            table2.AddCell(celll0);
            table2.AddCell(celll1);
            table2.AddCell(celll2);
            table2.AddCell(celll3);

            //table2.Rows.Add(new PdfPRow(new[] { celll0, cell1, cell2, cell3 }));

            int[] secondTablecellwidth = { 20, 15, 20, 15 };

            table2.SetWidths(secondTablecellwidth);

            doc.Add(table2);





            var table3 = new PdfPTable(4)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
                SpacingBefore = 15,

            };


            var cellll0 = new PdfPCell(new Phrase("", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };
            var cellll1 = new PdfPCell(new Phrase("", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var cellll2 = new PdfPCell(new Phrase("کد ملی:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var cellll3 = new PdfPCell(new Phrase(technicalStaff.NationalCode, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            table3.AddCell(cellll2);
            table3.AddCell(cellll3);
            table3.AddCell(cellll0);
            table3.AddCell(cellll1);


            //table2.Rows.Add(new PdfPRow(new[] { celll0, cell1, cell2, cell3 }));

            int[] table3cellwidth = { 20, 15, 20, 15 };

            table3.SetWidths(table3cellwidth);

            doc.Add(table3);




            var table4 = new PdfPTable(4)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
                SpacingBefore = 15,

            };


            var celllll0 = new PdfPCell(new Phrase("", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };
            var celllll1 = new PdfPCell(new Phrase(technicalStaff.University, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var celllll2 = new PdfPCell(new Phrase("محل اسکان:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var celllll3 = new PdfPCell(new Phrase(string.Format("{0}-{1}", technicalStaff.Dorm, technicalStaff.DormNumber), GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            table4.AddCell(celllll1);
            table4.AddCell(celllll0);
            table4.AddCell(celllll2);
            table4.AddCell(celllll3);

            //table2.Rows.Add(new PdfPRow(new[] { celll0, cell1, cell2, cell3 }));

            int[] table4cellwidth = { 20, 15, 0, 35 };

            table4.SetWidths(table4cellwidth);

            doc.Add(table4);



            var table5 = new PdfPTable(4)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                ExtendLastRow = false,
                SpacingBefore = 15,

            };


            var cellllll0 = new PdfPCell(new Phrase("سمت:", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var techRoles = "";

            foreach (var role in technicalStaff.Roles.Distinct())
            {
                techRoles += role + "-";
            }

            techRoles = techRoles.Substring(0, techRoles.Length - 1);

            var cellllll1 = new PdfPCell(new Phrase(techRoles, GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var cellllll2 = new PdfPCell(new Phrase("", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            var cellllll3 = new PdfPCell(new Phrase("", GetTahoma()))
            {
                RunDirection = (int)PdfRunDirection.RightToLeft,
                HorizontalAlignment = (int)HorizontalAlignment.Left,
                Border = 0
            };

            table5.AddCell(cellllll0);
            table5.AddCell(cellllll1);
            table5.AddCell(cellllll2);
            table5.AddCell(cellllll3);

            //table2.Rows.Add(new PdfPRow(new[] { celll0, cell1, cell2, cell3 }));

            int[] table5cellwidth = { 0, 0, 40, 10 };

            table5.SetWidths(table5cellwidth);

            doc.Add(table5);


            doc.Close();

            return fs;
        }
Example #20
0
        private String MarcaCancelado(String path)
        {
            PdfReader reader = new PdfReader(path);
            FileStream fs = null;
            PdfStamper stamp = null;

            var fileOutput = Path.GetTempFileName() + ".pdf";

            string outputPdf = String.Format(fileOutput, 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, "CANCELADO");
                over.EndText();

            }

            reader.Close();
            if (stamp != null) stamp.Close();
            if (fs != null) fs.Close();

            return fileOutput;
        }
Example #21
0
        public void TransparencyCheckTest4() {
            // step 1
            Document document = new Document(new Rectangle(850, 600));
            // step 2
            PdfAWriter writer
                = PdfAWriter.GetInstance(document, new FileStream(OUT + "pdfa2TransperancyCheckTest4.pdf", FileMode.Create),
                    PdfAConformanceLevel.PDF_A_2B);
            writer.CreateXmpMetadata();
            // step 3
            document.Open();
            // step 4
            PdfContentByte canvas = writer.DirectContent;

            // add the clipped image
            Image img = Image.GetInstance(RESOURCES + "img/bruno_ingeborg.jpg");
            float w = img.ScaledWidth;
            float h = img.ScaledHeight;
            canvas.Ellipse(1, 1, 848, 598);
            canvas.Clip();
            canvas.NewPath();
            canvas.AddImage(img, w, 0, 0, h, 0, -600);

            // Create a transparent PdfTemplate
            PdfTemplate t2 = writer.DirectContent.CreateTemplate(850, 600);
            PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
            transGroup.Put(PdfName.CS, PdfName.DEVICEGRAY);
            transGroup.Isolated = true;
            transGroup.Knockout = false;
            t2.Group = transGroup;

            // Add transparent ellipses to the template
            int gradationStep = 30;
            float[] gradationRatioList = new float[gradationStep];
            for (int i = 0; i < gradationStep; i++) {
                gradationRatioList[i] = 1 - (float) Math.Sin(Math.PI/180*90.0f/gradationStep*(i + 1));
            }
            for (int i = 1; i < gradationStep + 1; i++) {
                t2.SetLineWidth(5*(gradationStep + 1 - i));
                t2.SetGrayStroke(gradationRatioList[gradationStep - i]);
                t2.Ellipse(0, 0, 850, 600);
                t2.Stroke();
            }

            // Create an image mask for the direct content
            PdfDictionary maskDict = new PdfDictionary();
            maskDict.Put(PdfName.TYPE, PdfName.MASK);
            maskDict.Put(PdfName.S, new PdfName("Luminosity"));
            maskDict.Put(new PdfName("G"), t2.IndirectReference);
            PdfGState gState = new PdfGState();
            gState.Put(PdfName.SMASK, maskDict);
            canvas.SetGState(gState);

            canvas.AddTemplate(t2, 0, 0);

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            // step 5
            document.Close();
        }
Example #22
0
        virtual public void TransparencyCheckTest4()
        {
            string filename = OUT + "TransparencyCheckTest4.pdf";
            FileStream fos = new FileStream(filename, FileMode.Create);

            Document document = new Document();

            PdfAWriter writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_1B);
            writer.CreateXmpMetadata();

            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            PdfContentByte canvas = writer.DirectContent;
            PdfGState gs = new PdfGState();

            canvas.SetGState(gs);
            document.Close();
        }
        /** Sets the fill color. <CODE>color</CODE> can be an
         * <CODE>ExtendedColor</CODE>.
         * @param color the color
         */    
        public virtual void SetColorFill(BaseColor value) {
            int type = ExtendedColor.GetType(value);
            switch (type) {
                case ExtendedColor.TYPE_GRAY: {
                    SetGrayFill(((GrayColor)value).Gray);
                    break;
                }
                case ExtendedColor.TYPE_CMYK: {
                    CMYKColor cmyk = (CMYKColor)value;
                    SetCMYKColorFillF(cmyk.Cyan, cmyk.Magenta, cmyk.Yellow, cmyk.Black);
                    break;
                }
                case ExtendedColor.TYPE_SEPARATION: {
                    SpotColor spot = (SpotColor)value;
                    SetColorFill(spot.PdfSpotColor, spot.Tint);
                    break;
                }
                case ExtendedColor.TYPE_PATTERN: {
                    PatternColor pat = (PatternColor)value;
                    SetPatternFill(pat.Painter);
                    break;
                }
                case ExtendedColor.TYPE_SHADING: {
                    ShadingColor shading = (ShadingColor)value;
                    SetShadingFill(shading.PdfShadingPattern);
                    break;
                }
                case ExtendedColor.TYPE_DEVICEN: {
                    DeviceNColor devicen = (DeviceNColor) value;
                    SetColorFill(devicen.PdfDeviceNColor, devicen.Tints);
                    break;
                }
                case ExtendedColor.TYPE_LAB: {
                    LabColor lab = (LabColor) value;
                    SetColorFill(lab.LabColorSpace, lab.L, lab.A, lab.B);
                    break;
                }
                default:
                    SetRGBColorFill(value.R, value.G, value.B);
                    break;
            }

            int alpha = value.A;
            if (alpha < 255) {
                PdfGState gState = new PdfGState();
                gState.FillOpacity = alpha / 255f ;
                SetGState(gState);
            }


        }
Example #24
0
        public static void CreateWaterMarkPdf(List <TAILIEUDINHKEM> ListTaiLieu, string waterMark)
        {
            FileUltilities file   = new FileUltilities();
            BaseFont       bfFont = BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);

            iTextSharp.text.pdf.PdfGState gstate = null;
            gstate               = new iTextSharp.text.pdf.PdfGState();
            gstate.FillOpacity   = 0.3f;
            gstate.StrokeOpacity = 0.3f;
            foreach (var item in ListTaiLieu)
            {
                try
                {
                    #region gan water mark
                    string     DestinationFile = Path.GetDirectoryName(FolderPath + item.DUONGDAN_FILE) + Path.GetFileNameWithoutExtension(FolderPath + item.DUONGDAN_FILE) + "_1.pdf";
                    PdfReader  reader          = new PdfReader(FolderPath + item.DUONGDAN_FILE);
                    PdfStamper stamper         = new PdfStamper(reader,
                                                                new FileStream(DestinationFile, FileMode.Create, FileAccess.Write));
                    for (int iCount = 0; iCount < reader.NumberOfPages; iCount++)
                    {
                        iTextSharp.text.Rectangle PageSize = reader.GetCropBox(iCount + 1);
                        PdfContentByte            PDFData  = stamper.GetOverContent(iCount + 1);
                        BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
                        int      altitude = Math.Max(bfFont.GetAscent(waterMark), bfFont.GetDescent(waterMark));
                        int      width    = bfFont.GetWidth(waterMark);
                        PDFData.SaveState();
                        PDFData.SetGState(gstate);
                        PDFData.BeginText();
                        PDFData.SetColorFill(CMYKColor.LIGHT_GRAY);
                        PDFData.SetFontAndSize(bfFont, (float)80);
                        PDFData.ShowTextAligned(PdfContentByte.ALIGN_CENTER, waterMark, (PageSize.Right + PageSize.Left) / 2, (PageSize.Top + PageSize.Bottom) / 2, 45);
                        PDFData.EndText();
                    }
                    stamper.Close();
                    file.MoveFile(DestinationFile, FolderPath + item.DUONGDAN_FILE);
                    #endregion

                    #region ap dung chu ky so
                    if (ENABLECHUKYSO.ToIntOrZero() == 1)
                    {
                        string TmpDestinationFile = Path.GetDirectoryName(FolderPath + item.DUONGDAN_FILE) + "\\" + Path.GetFileNameWithoutExtension(FolderPath + item.DUONGDAN_FILE) + "_111.pdf";
                        Cert   myCert             = null;
                        myCert = new Cert(CHUKYSO, PASSCHUKYSO);
                        MetaData metaDT = new MetaData();
                        metaDT.Author   = "Duynt";
                        metaDT.Title    = "Demo title";
                        metaDT.Subject  = "Demo subject";
                        metaDT.Creator  = "Duynt create";
                        metaDT.Producer = "HiNet product";

                        PDFSigner pdf = new PDFSigner(FolderPath + item.DUONGDAN_FILE, TmpDestinationFile, myCert, metaDT);
                        pdf.Sign("Reason text", "Contact text", "Location text", true);
                        file.MoveFile(TmpDestinationFile, FolderPath + item.DUONGDAN_FILE);
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Example #25
0
        public void EgsCheckTest4() {
            Document document = new Document();
            PdfAWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT + "pdfa2egsCheckTest4.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_2B);
            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));

            PdfContentByte canvas = writer.DirectContent;
            PdfGState gs = new PdfGState();
            gs.Put(PdfName.TR2, new PdfName("Test"));
            gs.Put(PdfName.HTP, new PdfName("Test"));
            canvas.SaveState();
            canvas.SetGState(gs);
            canvas.RestoreState();
            canvas.MoveTo(writer.PageSize.Left, writer.PageSize.Bottom);
            canvas.LineTo(writer.PageSize.Right, writer.PageSize.Bottom);
            canvas.LineTo(writer.PageSize.Right, writer.PageSize.Top);
            canvas.Fill();

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            bool exceptionThrown = false;
            try {
                document.Close();
            }
            catch (PdfAConformanceException e) {
                if (e.GetObject() == gs) {
                    exceptionThrown = true;
                }
            }
            if (!exceptionThrown)
                Assert.Fail("PdfAConformanceException should be thrown.");
        }
Example #26
0
        public Respuesta find(byte[] pdf, string text)
        {
            int coincidences = 0;
            List<string> cadenas = new List<string>();
            List<WordFine> renglones = new List<WordFine>();
            if (String.IsNullOrEmpty(text))
                return new Respuesta();

            MyLocationTextExtractionStrategy txt = new MyLocationTextExtractionStrategy(text);
            LocationTextExtractionStrategyEx st = new LocationTextExtractionStrategyEx();
            Stream inputPdfStream = new MemoryStream(pdf);
            MemoryStream outPdfStream = new MemoryStream();

            PdfReader reader = new PdfReader(inputPdfStream);
            using (PdfStamper stamper = new PdfStamper(reader, outPdfStream))
            {
                for (int i = 1; i < reader.NumberOfPages + 1; i++)
                {

                    txt = new MyLocationTextExtractionStrategy(text);
                    var ex = PdfTextExtractor.GetTextFromPage(reader, i, txt);

                    txt.strings.ForEach(item => { if (item.ToLower().Contains(text.ToLower())) { coincidences++; ; cadenas.Add(item);  } });
                    //coincidences = txt.myPoints.Count();
                    foreach (var item in txt.myPoints)
                    {
                        WordFine itemWord = new WordFine();
                        if (!item.Text.ToLower().Contains(text.ToLower()))
                            continue;

                        //Create a rectangle for the highlight. NOTE: Technically this isn't used but it helps with the quadpoint calculation
                        iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(item.Rect);
                        //Create an array of quad points based on that rectangle. NOTE: The order below doesn't appear to match the actual spec but is what Acrobat produces
                        itemWord.pagina =i;
                        itemWord.cadenas = item.Text;
                        itemWord.coordenada = rect.Left;
                        renglones.Add(itemWord);

                        using (Document doc = new Document())
                        {
                            PdfContentByte over = stamper.GetOverContent(i);

                            over.SaveState();

                            PdfGState gs1 = new PdfGState();
                            gs1.FillOpacity = 0.3f;
                            over.SetGState(gs1);
                            Rectanngulo rectangulo = findInLine(item.Text.ToLower(), text.ToLower(), rect);
                            //over.Rectangle(rect.Left, rect.Bottom, rect.Width, rect.Height);
                            over.Rectangle(rectangulo.left, rectangulo.bottom, rectangulo.width, rectangulo.height);
                            over.SetColorFill(BaseColor.YELLOW);
                            over.Fill();
                            over.SetColorStroke(BaseColor.BLUE);
                            over.Stroke();

                            over.RestoreState();
                            doc.Close();
                        }
                    }
                }
            }
            return new Respuesta() { coincidences = coincidences, file = outPdfStream.GetBuffer(), text = cadenas, ubicacion= renglones };
        }
Example #27
0
        /// <summary>
        /// Draws the diamont.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        public static void DrawDiamont(PdfContentByte content, float x, float y)
        {
            content.SaveState();
            var state = new PdfGState();
            content.SetGState(state);
            content.SetColorFill(BaseColor.BLACK);
            content.MoveTo(x, y);
            var sPoint = new Point(x, y);
            var uMPoint = new Point(x + WPosMarkerMid, y + HPosMarkerMid);
            var rPoint = new Point(uMPoint.X + WPosMarkerMid, uMPoint.Y - HPosMarkerMid);
            var mPoint = new Point(rPoint.X - WPosMarkerMid, rPoint.Y - HPosMarkerMid);

            DrawLines(content, uMPoint, rPoint, mPoint, sPoint);

            content.ClosePathFillStroke();
            content.RestoreState();
        }
Example #28
0
        /// <summary>
        /// 添加普通偏转角度文字水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="waterMarkName"></param>
        /// <param name="permission"></param>
        public static void setWatermark(string inputfilepath, string outputfilepath, string waterMarkName)
        {
            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.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.LIGHT_GRAY);
                    content.SetFontAndSize(font, 60);
                    content.SetTextMatrix(0, 0);
                    content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 , height / 2 , 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();
            }
        }
 /** Sets the graphic state
 * @param gstate the graphic state
 */
 public void SetGState(PdfGState gstate)
 {
     PdfObject[] obj = writer.AddSimpleExtGState(gstate);
     PageResources prs = PageResources;
     PdfName name = prs.AddExtGState((PdfName)obj[0], (PdfIndirectReference)obj[1]);
     content.Append(name.GetBytes()).Append(" gs").Append_i(separator);
 }
Example #30
0
        /// <summary>
        /// Add watermark to a document
        /// </summary>
        /// <returns>
        /// true if watermak is apply
        /// </returns>
        private byte[] WatermarkPdf(byte[] fileBlob)
        {
            PdfReader reader = new PdfReader(fileBlob);
            int       pages  = reader.NumberOfPages;

            using (MemoryStream fileMemoryStream = new MemoryStream())
            {
                PdfStamper stamper             = new PdfStamper(reader, fileMemoryStream);
                iTextSharp.text.Rectangle rect = null;
                string testo    = testoEtichetta;
                int    style    = iTextSharp.text.Font.NORMAL;
                string FontName = FontFactory.COURIER;

                if (string.Compare(FontFace, "HELVETICA", true) == 0)
                {
                    FontName = FontFactory.HELVETICA;
                }
                if (string.Compare(FontFace, "TIMES", true) == 0)
                {
                    FontName = FontFactory.TIMES;
                }
                if (FontStyle.IndexOf("Bold") >= 0)
                {
                    style |= iTextSharp.text.Font.BOLD;
                }
                if (FontStyle.IndexOf("Italic") >= 0)
                {
                    style |= iTextSharp.text.Font.ITALIC;
                }

                var gstate = new iTextSharp.text.pdf.PdfGState();
                gstate.FillOpacity   = fillOpacity;
                gstate.StrokeOpacity = fillOpacity;

                var watermarkFont = FontFactory.GetFont(FontName, font.SizeInPoints, style, Color);


                Single offset   = 0.0F;
                Single offsetX  = 0.0F;
                Single currentY = 0;
                Single currentX = 0;
                rect = reader.GetPageSizeWithRotation(1);
                try
                {
                    for (int j = 1; j <= pages; j++)
                    {
                        var underContent = stamper.GetOverContent(j);
                        //stamper.GetOverContent(j);
                        underContent.BeginText();
                        underContent.SetFontAndSize(watermarkFont.BaseFont, font.SizeInPoints);
                        underContent.SetColorFill(Color);
                        underContent.SaveState();
                        underContent.SetGState(gstate);
                        //underContent.SetTextMatrix(font.SizeInPoints+2, font.SizeInPoints + 2);
                        if (testo.Length > 1)
                        {
                            currentY = (rect.Height / 2) + ((font.SizeInPoints * testo.Length) / 2);
                            if (watermarkRotation != 90)
                            {
                                currentX = (rect.Width / 2) + ((font.SizeInPoints * testo.Length) / 2);
                            }
                            else
                            {
                                currentX = (rect.Width / 2);
                            }
                        }
                        else
                        {
                            currentY = (rect.Height / 2);
                            currentX = (rect.Width / 2);
                        }
                        if (testo.Contains("#"))
                        {
                            string[] partTesto = testo.Split(new Char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                            int      yPlus     = 0;
                            foreach (var item in partTesto)
                            {
                                float extY = (yPlus * font.SizeInPoints);
                                if (extY > 0)
                                {
                                    extY += 20;
                                }
                                underContent.ShowTextAligned(PdfContentByte.ALIGN_CENTER, item, rect.Width / 2, (rect.Height / 2) - extY, watermarkRotation);
                                yPlus += 1;
                            }
                        }
                        else
                        {
                            for (int i = 0; i < testo.Length; i++)
                            {
                                if (i > 0)
                                {
                                    offset = (i * font.SizeInPoints);
                                    if (watermarkRotation != 90)
                                    {
                                        offsetX = (i * font.SizeInPoints);
                                    }
                                }
                                else
                                {
                                    offset  = 0;
                                    offsetX = 0;
                                }

                                underContent.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, testo[testo.Length - (i + 1)].ToString(), currentX - offsetX, currentY - offset, watermarkRotation);
                            }
                        }

                        //float textAngle = (float)GetHypotenuseAngleInDegreesFrom(rect.Height, rect.Width);

                        //underContent.ShowTextAligned(PdfContentByte.ALIGN_CENTER, testo, rect.Width / 2, rect.Height / 2, watermarkRotation);

                        underContent.EndText();
                        underContent.RestoreState();
                    }
                    stamper.FormFlattening = true;
                }
                finally
                {
                    try { if (stamper != null)
                          {
                              stamper.Close();
                          }
                    }
                    catch { }
                    try { if (reader != null)
                          {
                              reader.Close();
                          }
                    }
                    catch { }
                }
                return(fileMemoryStream.ToArray());
            }
        }
Example #31
0
 private static void ApplyWaterMark(string filePath)
 {
     Logger.LogI("ApplyWatermark -> " + filePath);
     var watermarkedFile = Path.GetFileNameWithoutExtension(filePath) + "-w.pdf";
     using (var reader1 = new PdfReader(filePath))
     {
         using (var fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
         using (var stamper = new PdfStamper(reader1, fs))
         {
             var pageCount = reader1.NumberOfPages;
             var layer = new PdfLayer("WatermarkLayer", stamper.Writer);
             for (var i = 1; i <= pageCount; i++)
             {
                 var rect = reader1.GetPageSize(i);
                 var cb = stamper.GetUnderContent(i);
                 cb.BeginLayer(layer);
                 cb.SetFontAndSize(BaseFont.CreateFont(
                     BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
                 var gState = new PdfGState {FillOpacity = 0.25f};
                 cb.SetGState(gState);
                 cb.SetColorFill(BaseColor.BLACK);
                 cb.BeginText();
                 cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
                     "(c)2015 ScrapEra", rect.Width/2, rect.Height/2, 45f);
                 cb.EndText();
                 cb.EndLayer();
             }
         }
     }
     File.Delete(filePath);
 }
Example #32
-9
 // ---------------------------------------------------------------------------    
 /**
  * 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();
 }