Пример #1
0
        /// <summary>
        /// Sets visual border style for specified <see cref="Image"/>.
        /// </summary>
        /// <param name="image">Horizontal alignment.</param>
        /// <param name="style">Style to apply.</param>
        /// <returns>
        /// A <see cref="int"/> value that represents the alignment.
        /// </returns>
        public static Image SetVisualStyle(this Image image, PdfImageStyle style)
        {
            if (!string.IsNullOrEmpty(style.Content.Color))
            {
                image.BackgroundColor = new BaseColor(style.Content.GetColor());
            }

            BordersCollection borders = style.Borders;

            image.BorderWidthLeft = 0.0f;
            BaseBorder leftBorder = borders.GetBy(KnownBorderPosition.Left);

            if (leftBorder != null)
            {
                if (leftBorder.Show.AsBoolean())
                {
                    image.BorderWidthLeft = leftBorder.Width;
                    image.BorderColorLeft = new BaseColor(leftBorder.GetColor());
                }
            }

            image.BorderWidthTop = 0.0f;
            BaseBorder topBorder = borders.GetBy(KnownBorderPosition.Top);

            if (topBorder != null)
            {
                if (topBorder.Show.AsBoolean())
                {
                    image.BorderWidthTop = topBorder.Width;
                    image.BorderColorTop = new BaseColor(topBorder.GetColor());
                }
            }

            image.BorderWidthRight = 0.0f;
            BaseBorder rightBorder = borders.GetBy(KnownBorderPosition.Right);

            if (rightBorder != null)
            {
                if (rightBorder.Show.AsBoolean())
                {
                    image.BorderWidthRight = rightBorder.Width;
                    image.BorderColorRight = new BaseColor(rightBorder.GetColor());
                }
            }

            image.BorderWidthBottom = 0.0f;
            BaseBorder bottomBorder = borders.GetBy(KnownBorderPosition.Bottom);

            if (bottomBorder != null)
            {
                if (bottomBorder.Show.AsBoolean())
                {
                    image.BorderWidthBottom = bottomBorder.Width;
                    image.BorderColorBottom = new BaseColor(bottomBorder.GetColor());
                }
            }

            return(image);
        }
Пример #2
0
        /// <summary>
        /// Implementation to execute when replace action.
        /// </summary>
        /// <param name="input">stream input</param>
        /// <param name="context">Input context</param>
        /// <returns>
        /// <para>
        /// A <see cref="ReplaceResult"/> reference that contains the result of the operation, to check if the operation is correct, the <b>Success</b>
        /// property will be <b>true</b> and the <b>Value</b> property will contain the value; Otherwise, the the <b>Success</b> property
        /// will be false and the <b>Errors</b> property will contain the errors associated with the operation, if they have been filled in.
        /// </para>
        /// <para>
        /// The type of the return value is <see cref="ReplaceResultData"/>, which contains the operation result
        /// </para>
        /// </returns>
        protected override ReplaceResult ReplaceImpl(Stream input, IInput context)
        {
            if (Image == Design.Image.PdfImage.Null)
            {
                return(ReplaceResult.CreateSuccessResult(new ReplaceResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }

            if (Style == null)
            {
                Style = PdfImageStyle.Default;
            }

            return(ReplaceImpl(context, input, Text, ReplaceOptions, Image, ImageOffset, Style, UseTestMode));
        }
Пример #3
0
        /// <summary>
        /// Implementation to execute when insert action.
        /// </summary>
        /// <param name="input">stream input</param>
        /// <param name="context">Input context</param>
        /// <returns>
        /// <para>
        /// A <see cref="InsertResult"/> reference that contains the result of the operation, to check if the operation is correct, the <b>Success</b>
        /// property will be <b>true</b> and the <b>Value</b> property will contain the value; Otherwise, the the <b>Success</b> property
        /// will be false and the <b>Errors</b> property will contain the errors associated with the operation, if they have been filled in.
        /// </para>
        /// <para>
        /// The type of the return value is <see cref="InsertResultData"/>, which contains the operation result
        /// </para>
        /// </returns>
        protected override InsertResult InsertImpl(Stream input, IInput context)
        {
            if (Style == null)
            {
                Style = PdfImageStyle.Default;
            }

            if (Image == Design.Image.PdfImage.Null)
            {
                return(InsertResult.CreateSuccessResult(new InsertResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }

            return(InsertImpl(context, input, Page, Image, Offset, Style));
        }
Пример #4
0
        private static ReplaceResult ReplaceImpl(IInput context, Stream input, string oldText, ReplaceTextOptions options, Design.Image.PdfImage image, PointF imageOffset, PdfImageStyle style, YesNo useTestMode)
        {
            var outputStream = new MemoryStream();

            try
            {
                using (var reader = new PdfReader(input))
                    using (var stamper = new PdfStamper(reader, outputStream))
                    {
                        var pages = reader.NumberOfPages;
                        for (var page = 1; page <= pages; page++)
                        {
                            var strategy = new CustomLocationTextExtractionStrategy();
                            var cb       = stamper.GetOverContent(page);

                            // Send some data contained in PdfContentByte, looks like the first is always cero for me and the second 100,
                            // but i'm not sure if this could change in some cases.
                            strategy.UndercontentCharacterSpacing  = cb.CharacterSpacing;
                            strategy.UndercontentHorizontalScaling = cb.HorizontalScaling;

                            // It's not really needed to get the text back, but we have to call this line ALWAYS,
                            // because it triggers the process that will get all chunks from PDF into our strategy Object
                            var allStrings   = PdfTextExtractor.GetTextFromPage(reader, page, strategy);
                            var stringsArray = allStrings.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                            // The real getter process starts in the following line
                            var textMatchesFound = strategy.GetExtendedTextLocations(oldText, options).ToList();

                            // MatchesFound contains all text with locations
                            foreach (var match in textMatchesFound)
                            {
                                // Delete tag
                                var bColor = BaseColor.WHITE;
                                cb.SetColorFill(bColor);
                                cb.Rectangle(match.Rect.Left, match.Rect.Bottom, match.Rect.Width, match.Rect.Height);
                                cb.Fill();

                                // Calculates new rectangle
                                var r = BuildRectangleByStrategies(match, oldText, image.ScaledHeight, image.ScaledWidth, strategy, cb, (string[])stringsArray.Clone(), options);

                                image.Image.ScaleToFit(r.Width, r.Height);
                                var dX = CalculatesHorizontalDelta(style.Content.Alignment.Horizontal, r, image.Image, imageOffset.X);

                                if (useTestMode == YesNo.Yes)
                                {
                                    using (Bitmap emptyImage = BitmapHelper.CreateEmptyBitmap(image.Image.ScaledWidth + 1, image.Image.ScaledHeight + 1, Color.LightGray))
                                        using (Graphics g = Graphics.FromImage(emptyImage))
                                            using (Canvas canvas = new Canvas(g))
                                            {
                                                canvas.DrawBorder(Color.Red);

                                                var testImage = TextSharpPdfImage.GetInstance(emptyImage, ImageFormat.Png);
                                                testImage.SetAbsolutePosition(r.X + dX, -imageOffset.Y + (r.Y - image.Image.ScaledHeight));
                                                cb.AddImage(testImage);
                                            }
                                }
                                else
                                {
                                    image.Image.SetVisualStyle(style);
                                    image.Image.SetAbsolutePosition(r.X + dX, -imageOffset.Y + (r.Y - image.Image.ScaledHeight));
                                    cb.AddImage(image.Image);
                                }
                            }

                            cb.Fill();
                            cb.Stroke();
                        }

                        stamper.Close();
                        reader.Close();
                    }

                return(ReplaceResult.CreateSuccessResult(new ReplaceResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = new MemoryStream(outputStream.GetBuffer())
                }));
            }
            catch (Exception ex)
            {
                return(ReplaceResult.FromException(
                           ex,
                           new ReplaceResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }
        }
Пример #5
0
        // Generates document
        public static void Generate(ILogger logger)
        {
            #region image style

            logger.Info("   > Working with image styles");

            var imageStyle = new PdfImageStyle
            {
                Name    = "ImageStyle",
                Borders =
                {
                    new BaseBorder {
                        Color = "Red", Show = YesNo.Yes, Position = KnownBorderPosition.Right
                    },
                    new BaseBorder {
                        Color = "Yellow", Show = YesNo.Yes, Position = KnownBorderPosition.Top
                    }
                },
                Content =
                {
                    Color     = "Blue",
                    Alignment =
                    {
                        Horizontal = KnownHorizontalAlignment.Right
                    },
                    Properties     = new Properties
                    {
                        new Property {
                            Name   = "p001",Value  = "v001"
                        },
                        new Property {
                            Name   = "p002",Value  = "v002"
                        }
                    }
                }
            };

            // Save image style to disk
            var imageStyleAsXmlResult = imageStyle.SaveToFile("~/Output/Sample12/ImageStyle");
            if (!imageStyleAsXmlResult.Success)
            {
                logger.Info("     > Error while saving image style as xml to disk");
                logger.Info($"      > Error: {imageStyleAsXmlResult.Errors.AsMessages().ToStringBuilder()}");
            }
            else
            {
                logger.Info("     > Saved image style as xml to disk correctly");
                logger.Info("       > Path: ~/Output/Sample12/ImageStyle.xml");
            }

            var imageStyleAsJsonResult = imageStyle.SaveToFile("~/Output/Sample12/ImageStyle", KnownFileFormat.Json);
            if (!imageStyleAsJsonResult.Success)
            {
                logger.Info("     > Error while saving image style as json to disk");
                logger.Info($"      > Error: {imageStyleAsJsonResult.Errors.AsMessages().ToStringBuilder()}");
            }
            else
            {
                logger.Info("     > Saved image style as json to disk correctly");
                logger.Info("       > Path: ~/Output/Sample12/ImageStyle.json");
            }

            // New image style instances from disk
            var imageStyleFromXml = PdfImageStyle.LoadFromFile("~/Output/Sample12/ImageStyle.xml");
            logger.Info(imageStyleFromXml == null
                ? "     > Error while loading image style from xml file"
                : "     > Image style loaded correctly from xml '~/Output/Sample12/ImageStyle.xml' file");

            var imageStyleFromJson = PdfImageStyle.LoadFromFile("~/Output/Sample12/ImageStyle.json", KnownFileFormat.Json);
            logger.Info(imageStyleFromJson == null
                ? "     > Error while loading image style from json file"
                : "     > Image style loaded correctly from json '~/Output/Sample12/ImageStyle.json' file");

            #endregion

            #region text style

            logger.Info("");
            logger.Info("   > Working with text styles");

            var textStyle = new PdfTextStyle
            {
                Name = "NormalStyle",
                Font =
                {
                    Bold      = YesNo.Yes,
                    Italic    = YesNo.Yes,
                    Color     = "Yellow",
                    Underline = YesNo.No
                },
                Borders =
                {
                    new BaseBorder {
                        Color = "Red", Show = YesNo.Yes, Position = KnownBorderPosition.Right
                    },
                    new BaseBorder {
                        Color = "Yellow", Show = YesNo.Yes, Position = KnownBorderPosition.Top
                    }
                },
                Content =
                {
                    Color     = "Blue",
                    Alignment =
                    {
                        Vertical   = KnownVerticalAlignment.Top,
                        Horizontal = KnownHorizontalAlignment.Right
                    },
                    Properties     = new Properties
                    {
                        new Property {
                            Name   = "p001",                    Value  = "v001"
                        },
                        new Property {
                            Name   = "p002",                    Value  = "v002"
                        }
                    }
                }
            };

            // Save text style to disk
            var textStyleAsXmlResult = textStyle.SaveToFile("~/Output/Sample12/TextStyle");
            if (!textStyleAsXmlResult.Success)
            {
                logger.Info("     > Error while saving text style as xml to disk");
                logger.Info($"      > Error: {textStyleAsXmlResult.Errors.AsMessages().ToStringBuilder()}");
            }
            else
            {
                logger.Info("     > Saved text style as xml to disk correctly");
                logger.Info("       > Path: ~/Output/Sample12/TextStyle.xml");
            }

            var textStyleAsJsonResult = textStyle.SaveToFile("~/Output/Sample12/TextStyle", KnownFileFormat.Json);
            if (!textStyleAsJsonResult.Success)
            {
                logger.Info("     > Error while saving text style as json to disk");
                logger.Info($"      > Error: {textStyleAsJsonResult.Errors.AsMessages().ToStringBuilder()}");
            }
            else
            {
                logger.Info("     > Saved text style as json to disk correctly");
                logger.Info("       > Path: ~/Output/Sample12/TextStyle.json");
            }

            // New text style instances from disk
            var textStyleFromXml = PdfTextStyle.LoadFromFile("~/Output/Sample12/TextStyle.xml");
            logger.Info(textStyleFromXml == null
                ? "     > Error while loading text style from xml file"
                : "     > Text style loaded correctly from xml '~/Output/Sample12/TextStyle.xml' file");

            var textStyleFromJson = PdfTextStyle.LoadFromFile("~/Output/Sample12/TextStyle.json", KnownFileFormat.Json);
            logger.Info(textStyleFromJson == null
                ? "     > Error while loading text style from json file"
                : "     > Text style loaded correctly from json '~/Output/Sample12/TextStyle.json' file");

            #endregion

            #region table style

            logger.Info("");
            logger.Info("   > Working with table styles");

            var tableStyle = new PdfTableStyle
            {
                Name      = "NormalStyle",
                Alignment =
                {
                    Vertical = KnownVerticalAlignment.Top
                },
                Borders =
                {
                    new BaseBorder {
                        Color = "Red", Show = YesNo.Yes, Position = KnownBorderPosition.Right
                    },
                    new BaseBorder {
                        Color = "Yellow", Show = YesNo.Yes, Position = KnownBorderPosition.Top
                    }
                },
                Content =
                {
                    Color      = "Blue",
                    Show       = YesNo.Yes,
                    Properties = new Properties
                    {
                        new Property {
                            Name = "p001",   Value  = "v001"
                        },
                        new Property {
                            Name = "p002",   Value  = "v002"
                        }
                    }
                }
            };

            // Save table style to disk
            var tableStyleAsXmlResult = tableStyle.SaveToFile("~/Output/Sample12/TableStyle");
            if (!tableStyleAsXmlResult.Success)
            {
                logger.Info("     > Error while saving table style as xml to disk");
                logger.Info($"      > Error: {tableStyleAsXmlResult.Errors.AsMessages().ToStringBuilder()}");
            }
            else
            {
                logger.Info("     > Saved table style as xml to disk correctly");
                logger.Info("       > Path: ~/Output/Sample12/TableStyle.xml");
            }

            var tableStyleAsJsonResult = tableStyle.SaveToFile("~/Output/Sample12/TableStyle", KnownFileFormat.Json);
            if (!tableStyleAsJsonResult.Success)
            {
                logger.Info("     > Error while saving table style as json to disk");
                logger.Info($"      > Error: {tableStyleAsJsonResult.Errors.AsMessages().ToStringBuilder()}");
            }
            else
            {
                logger.Info("     > Saved table style as json to disk correctly");
                logger.Info("       > Path: ~/Output/Sample12/TableStyle.json");
            }

            // New table style instances from disk
            var tableStyleFromXml = PdfTableStyle.LoadFromFile("~/Output/Sample12/TableStyle.xml");
            logger.Info(tableStyleFromXml == null
                ? "     > Error while loading table style from xml file"
                : "     > Table style loaded correctly from xml '~/Output/Sample12/TableStyle.xml' file");

            var tableStyleFromJson = PdfTableStyle.LoadFromFile("~/Output/Sample12/TableStyle.json", KnownFileFormat.Json);
            logger.Info(tableStyleFromJson == null
                ? "     > Error while loading table style from json file"
                : "     > Table style loaded correctly from json '~/Output/Sample12/TableStyle.json' file");

            #endregion
        }
Пример #6
0
        private static InsertResult InsertImpl(IInput context, Stream input, int page, PdfImage image, PointF imageOffset, PdfImageStyle style)
        {
            var outputStream = new MemoryStream();

            try
            {
                var reader  = new TextSharp.PdfReader(input);
                var stamper = new TextSharp.PdfStamper(reader, outputStream);

                var pages = reader.NumberOfPages;
                for (var pdfPage = 1; pdfPage <= pages; pdfPage++)
                {
                    if (pdfPage != page)
                    {
                        continue;
                    }

                    var cb = stamper.GetOverContent(pdfPage);
                    image.Image.SetAbsolutePosition(imageOffset.X, imageOffset.Y);
                    cb.AddImage(image.Image);
                    break;
                }

                stamper.Close();
                reader.Close();

                return(InsertResult.CreateSuccessResult(new InsertResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = new MemoryStream(outputStream.GetBuffer())
                }));
            }
            catch (Exception ex)
            {
                return(InsertResult.FromException(
                           ex,
                           new InsertResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }
        }