Exemple #1
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 (Style == null)
            {
                Style = PdfTextStyle.Default;
            }

            return(ReplaceImpl(context, input, Text, NewText, ReplaceOptions, TextOffset, Style, UseTestMode));
        }
Exemple #2
0
        /// <summary>
        /// Creates a new cell with the visual style defined in the model.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="style">The style.</param>
        /// <param name="useTestMode">Indicates if draw a border in testmode.</param>
        /// <returns>
        /// A new <see cref="PdfPCell"/> with visual style defined in the model.
        /// </returns>
        public static PdfPCell CreateCell(string text, PdfTextStyle style, YesNo useTestMode = YesNo.No)
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Utilities.Pdf, Namespace: iTin.Utilities.Pdf.Helpers, Class: PdfHelper");
            Logger.Instance.Debug($" Creates a new cell with the visual style defined in the model");
            Logger.Instance.Debug($" > Signature: ({typeof(PdfPCell)}) CreateCell({typeof(string)}, {typeof(PdfTextStyle)})");
            Logger.Instance.Debug($"   > text: {text}");
            Logger.Instance.Debug($"   > style: {style}");

            var phrase = new Phrase {
                Font = CreateFont(style.Font)
            };

            phrase.Add(text);

            return(new PdfPCell(phrase).SetVisualStyle(style, useTestMode));
        }
Exemple #3
0
        /// <summary>
        /// Sets visual style for specified cell.
        /// </summary>
        /// <param name="cell">Cell which receives visual style.</param>
        /// <param name="style">Style to apply.</param>
        /// <param name="useTestMode">Indicates if draw a border in testmode.</param>
        /// <returns>
        /// A <see cref="PdfPCell"/> object which contains specified visual style.
        /// </returns>
        public static PdfPCell SetVisualStyle(this PdfPCell cell, PdfTextStyle style, YesNo useTestMode = YesNo.No)
        {
            Logger.Instance.Debug("External Call");
            Logger.Instance.Info("  Sets visual style for specified cell");
            Logger.Instance.Info("  > Library: iTin.Utilities.Pdf");
            Logger.Instance.Info("  > Class: PdfExtensions");
            Logger.Instance.Info("  > Method: SetVisualStyle(this PdfPCell, StyleModel)");
            Logger.Instance.Info("  > Output: PdfPCell");

            SentinelHelper.ArgumentNull(cell, nameof(cell));
            SentinelHelper.ArgumentNull(style, nameof(style));

            cell.BackgroundColor = new BaseColor(style.Content.GetColor());
            cell.SetAlignmentVisualStyle(style.Content.Alignment);

            if (useTestMode.AsBoolean())
            {
                cell.SetBordersVisualStyle(
                    new BordersCollection
                {
                    new BaseBorder {
                        Color = "Red", Position = KnownBorderPosition.Left, Show = YesNo.Yes
                    },
                    new BaseBorder {
                        Color = "Red", Position = KnownBorderPosition.Top, Show = YesNo.Yes
                    },
                    new BaseBorder {
                        Color = "Red", Position = KnownBorderPosition.Right, Show = YesNo.Yes
                    },
                    new BaseBorder {
                        Color = "Red", Position = KnownBorderPosition.Bottom, Show = YesNo.Yes
                    }
                });
            }
            else
            {
                cell.SetBordersVisualStyle(style.Borders);
            }

            return(cell);
        }
Exemple #4
0
        private static ReplaceResult ReplaceImpl(IInput context, Stream input, string oldText, string newText, ReplaceTextOptions options, PointF offset, PdfTextStyle style, YesNo useTestMode)
        {
            var outputStream = new MemoryStream();

            try
            {
                var reader  = new PdfReader(input);
                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();

                    // Text matches found contains all text with locations, so do whatever you want with it
                    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, strategy, cb, (string[])stringsArray.Clone(), options);

                        //PdfGState gs = new PdfGState {FillOpacity = 0.3f};
                        //cb.SaveState();
                        //cb.SetGState(gs);
                        //cb.SetRGBColorFill(200, 200, 0);

                        // Add table
                        var table = new PdfPTable(1)
                        {
                            TotalWidth = r.Width - offset.X
                        };
                        table.AddCell(PdfHelper.CreateCell(newText, style, useTestMode));
                        table.WriteSelectedRows(-1, -1, r.X + offset.X, r.Y - offset.Y, cb);
                        cb.Fill();

                        //cb.RestoreState();
                    }

                    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
                }));
            }
        }
Exemple #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
        }