public WatermarkAnnotator(AnnotationDataEntity annotationData, PageInfo pageInfo)
     : base(annotationData, pageInfo)
 {
     watermarkAnnotation = new WatermarkAnnotation
     {
         Box        = GetBox(),
         FontFamily = !string.IsNullOrEmpty(annotationData.font) ? annotationData.font : "Arial",
         FontColor  = annotationData.fontColor,
         FontSize   = annotationData.fontSize == 0 ? 12 : annotationData.fontSize,
         Text       = annotationData.text
     };
 }
        /// <summary>
        /// Adds a watermark on all pages of the specified document.
        /// </summary>
        /// <param name="doc">Document to process.</param>
        /// <param name="imageDataStream">Stream containing image data to be used as watermark. Caller is reposible for closing it.</param>
        /// <param name="outputStream">Output stream, optional. If not set, incremental save will be performed. Caller is responsible for closing it.</param>
        public static void Watermark(this FixedDocument doc, Stream imageDataStream, Stream outputStream = null)
        {
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (imageDataStream == null)
            {
                throw new ArgumentNullException(nameof(imageDataStream));
            }

            // create and register image resource
            string imageResourceId = Guid.NewGuid().ToString("N");
            Image  imageResource   = new Image(imageResourceId, imageDataStream);

            doc.ResourceManager.RegisterResource(imageResource);

            // register watermark XObject it will be referenced in all watermark annotations
            FixedContent watermarkContent = new FixedContent(Guid.NewGuid().ToString("N"),
                                                             new Boundary(imageResource.Width, imageResource.Height));

            watermarkContent.Content.AppendImage(imageResourceId, 0, 0, imageResource.Width, imageResource.Height);
            doc.ResourceManager.RegisterResource(watermarkContent);

            // add annotations to every page
            foreach (Page page in doc.Pages)
            {
                WatermarkAnnotation watermarkAnnotation = CreateWatermarkAnnotation(page.Boundary.MediaBox, watermarkContent);
                doc.ResourceManager.RegisterResource(watermarkAnnotation.Watermark);
                page.Annotations.Add(watermarkAnnotation);
            }

            // save to specified file or do an incremental update
            if (outputStream != null)
            {
                doc.Save(outputStream);
            }
            else
            {
                doc.Save();
            }
        }
        public void WatermarkText()
        {
            string outputFileName = GetFileNameBasedOnCaller();

            // string watermarkText = "Top secret - for internal use - top secret - for internal use";
            string watermarkText = "TOP secret -for INTERNAL use - TOP secret - for INTERNAL use - TOP secret - for INTERNAL use - TOP secret";

            using (Stream inputStream = File.Open("../../data/letter_unsigned.pdf", FileMode.Open))
            {
                using (FixedDocument doc = new FixedDocument(inputStream))
                {
                    doc.WatermarkText(watermarkText, outputFileName);
                }
            }

            using (Stream inputStream = File.Open(outputFileName, FileMode.Open))
            {
                using (FixedDocument doc = new FixedDocument(inputStream))
                {
                    // check that we have watermarks placed on first page
                    // TODO: make it working for all pages
                    for (int i = 0; i < 1; ++i)
                    {
                        bool watermarkAnnotationFound = false;

                        foreach (Annotation annotation in doc.Pages[i].Annotations)
                        {
                            WatermarkAnnotation watermarkAnnotation = (annotation as WatermarkAnnotation);

                            if (watermarkAnnotation != null && (watermarkAnnotationFound = FindTextInElements(watermarkText, watermarkAnnotation.Watermark.Elements)))
                            {
                                break;
                            }
                        }

                        Assert.IsTrue(watermarkAnnotationFound);
                    }
                }
            }

            Process.Start(outputFileName);
        }
        /// <summary>
        /// Creates watermark annotations object referencing specified XObject.
        /// </summary>
        /// <param name="pageBoundary">Targer page boundary.</param>
        /// <param name="watermarkXobject">XObject containing visual content for the watermark.</param>
        /// <param name="rotated">Indicates that watermark object should be rotated and aligned between the lower left and upper right corners.</param>
        /// <returns>Initialized watermarp annotation.</returns>
        private static WatermarkAnnotation CreateWatermarkAnnotation(Boundary pageBoundary,
                                                                     FixedContent watermarkXobject, bool rotated = false)
        {
            // create watermark content XObject and reference existing "real" watermark XObject containing content
            FixedContent watermarkStub = new FixedContent(Guid.NewGuid().ToString("N"), pageBoundary);

            if (rotated)
            {
                // calculate rotation angle
                double alpha = Math.Atan(watermarkStub.Boundary.Height / watermarkStub.Boundary.Width);
                double beta  = Math.PI / 2.0 - alpha;

                double centeringDelta = watermarkXobject.Boundary.Height * Math.Cos(beta);

                double rotatedWidth  = watermarkXobject.Boundary.Width * Math.Cos(alpha) + centeringDelta;
                double rotatedHeight = watermarkXobject.Boundary.Width * Math.Sin(alpha) + watermarkXobject.Boundary.Height * Math.Sin(beta);

                watermarkStub.Content.SaveGraphicsState();
                watermarkStub.Content.Translate(centeringDelta + (watermarkStub.Boundary.Width - rotatedWidth) / 2.0,
                                                (watermarkStub.Boundary.Height - rotatedHeight) / 2.0);
                watermarkStub.Content.SetRotate(alpha);
                watermarkStub.Content.AppendXObject(watermarkXobject.ID, 0, 0);
                watermarkStub.Content.RestoreGraphicsState();
            }
            else
            {
                watermarkStub.Content.AppendXObject(watermarkXobject.ID, (watermarkStub.Boundary.Width - watermarkXobject.Boundary.Width) / 2.0,
                                                    (watermarkStub.Boundary.Height - watermarkXobject.Boundary.Height) / 2.0);
                watermarkStub.Content.RestoreGraphicsState();
            }

            // create annotation and wire its visual part
            WatermarkAnnotation annotation = new WatermarkAnnotation(pageBoundary);

            annotation.Watermark = watermarkStub;

            return(annotation);
        }
        /// <summary>
        /// Adds a watermark to all pages of the specified document.
        /// </summary>
        /// <param name="doc">Document to process.</param>
        /// <param name="watermarkText">Watermark text.</param>
        /// <param name="outputStream">Output stream, optional. If not set, incremental save will be performed.</param>
        public static void WatermarkText(this FixedDocument doc, string watermarkText, Stream outputStream = null)
        {
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (string.IsNullOrEmpty(watermarkText))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(watermarkText));
            }


            // register graphics state that sets transparency level for content
            GraphicsState gsTransparency = new GraphicsState("gsTransparency");

            gsTransparency.CurrentNonStrokingAlpha = 0.3;
            gsTransparency.CurrentStrokingAlpha    = 0.3;
            doc.ResourceManager.RegisterResource(gsTransparency);

            // create watermark content template using given text
            double fontSizeInPoints = 20;
            double padding          = 10;
            double borderThickness  = 2;

            double totalAddedSpace = (padding + borderThickness) * 2;

            TextBlock watermarkTextBlock = new TextBlock(watermarkText)
            {
                Font         = new Font("Times New Roman", fontSizeInPoints),
                Color        = RgbColors.Red,
                Padding      = new Thickness(padding),
                BorderColor  = RgbColors.Red,
                Border       = new Border(borderThickness),
                BorderRadius = 5,
                Background   = RgbColors.Pink
            };

            double textBlockWidth  = watermarkTextBlock.Measure(doc.ResourceManager) + totalAddedSpace;
            double textBlockHeight = fontSizeInPoints + totalAddedSpace + 10;

            FixedContent watermarkContent = new FixedContent(Guid.NewGuid().ToString("N"), new Boundary(textBlockWidth, textBlockHeight));

            watermarkContent.Content.SetGraphicsState(gsTransparency.ID);
            watermarkContent.Content.AppendContentElement(watermarkTextBlock, textBlockWidth, textBlockHeight);

            // register watermark XObject it will be referenced in all watermark annotations
            doc.ResourceManager.RegisterResource(watermarkContent);

            // add annotations to every page
            foreach (Page page in doc.Pages)
            {
                WatermarkAnnotation watermarkAnnotation = CreateWatermarkAnnotation(page.Boundary.MediaBox, watermarkContent, true);
                doc.ResourceManager.RegisterResource(watermarkAnnotation.Watermark);
                page.Annotations.Add(watermarkAnnotation);
            }

            // save to specified file or do an incremental update
            if (outputStream != null)
            {
                doc.Save(outputStream);
            }
            else
            {
                doc.Save();
            }
        }
 public override AnnotationBase AnnotateWord()
 {
     watermarkAnnotation = InitAnnotationBase(watermarkAnnotation) as WatermarkAnnotation;
     return(watermarkAnnotation);
 }
Exemplo n.º 7
0
        private void InsertStamp()
        {
            try
            {
                double imageSize = 115;
                double xShift    = 10;
                double yShift    = 10;


                Rectangle imageRectangle = new Rectangle(xShift, yShift, xShift + imageSize, yShift + imageSize);
                using (Aspose.Pdf.Document document = new Aspose.Pdf.Document(tempFile))
                {
                    Assembly assembly = Assembly.GetExecutingAssembly();

                    using (var imageStream = assembly.GetManifestResourceStream("CoolTool.pecsét.png"))
                    {
                        XImage image = null;
                        foreach (Page page in document.Pages)
                        {
                            double xCoor;
                            switch (stampMode)
                            {
                            case 1:
                                xCoor = page.PageInfo.Width - xShift - imageSize;
                                break;

                            case 2:
                                xCoor = xShift;
                                break;

                            default:
                                xCoor = page.PageInfo.Width - xShift - imageSize;
                                break;
                            }

                            WatermarkAnnotation annotation = new WatermarkAnnotation(page, page.Rect);
                            XForm form = annotation.Appearance["N"];
                            form.BBox = page.Rect;

                            string name;
                            if (image == null)
                            {
                                name  = form.Resources.Images.Add(imageStream);
                                image = form.Resources.Images[name];
                            }
                            else
                            {
                                name = form.Resources.Images.Add(image);
                            }

                            form.Contents.Add(new Operator.GSave());
                            form.Contents.Add(new Operator.ConcatenateMatrix(new Matrix(imageSize, 0, 0, imageSize, xCoor, yShift)));
                            form.Contents.Add(new Operator.Do(name));
                            form.Contents.Add(new Operator.GRestore());

                            page.Annotations.Add(annotation, false);
                        }
                    }

                    document.Save(outputFile);
                }
            }
            catch (Exception ex)
            {
                Log.AddLog("Hiba a pecsét beillesztése során - " + ex.Message, true);
            }
        }