public static void UsingTextBuilderAndParagraph() { // ExStart:UsingTextBuilderAndParagraph // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Create Document instance Document pdfDocument = new Document(); // Add page to pages collection of Document Page page = pdfDocument.Pages.Add(); // Create TextBuilder instance TextBuilder builder = new TextBuilder(pdfDocument.Pages[1]); // Instantiate TextParagraph instance TextParagraph paragraph = new TextParagraph(); // Create TextState instance to specify font name and size TextState state = new TextState("Arial", 12); // Specify the character spacing state.CharacterSpacing = 1.5f; // Append text to TextParagraph object paragraph.AppendLine("This is paragraph with character spacing", state); // Specify the position for TextParagraph paragraph.Position = new Position(100, 550); // Append TextParagraph to TextBuilder instance builder.AppendParagraph(paragraph); dataDir = dataDir + "CharacterSpacingUsingTextBuilderAndParagraph_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:UsingTextBuilderAndParagraph Console.WriteLine("\nCharacter spacing specified successfully using Text builder and paragraph.\nFile saved at " + dataDir); }
public static void AddUnderlineText() { // ExStart:AddUnderlineText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Create documentation object Document pdfDocument = new Document(); // Add age page to PDF document pdfDocument.Pages.Add(); // Create TextBuilder for first page TextBuilder tb = new TextBuilder(pdfDocument.Pages[1]); // TextFragment with sample text TextFragment fragment = new TextFragment("Test message"); // Set the font for TextFragment fragment.TextState.Font = FontRepository.FindFont("Arial"); fragment.TextState.FontSize = 10; // Set the formatting of text as Underline fragment.TextState.Underline = true; // Specify the position where TextFragment needs to be placed fragment.Position = new Position(10, 800); // Append TextFragment to PDF file tb.AppendText(fragment); dataDir = dataDir + "AddUnderlineText_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:AddUnderlineText Console.WriteLine("\nUnderline text added successfully.\nFile saved at " + dataDir); }
public CartProxy Find(CartId id) { List<Parameter> parameterList = new List<Parameter>(); string where = "where" + Environment.NewLine ; where += _indent + "Cart.CustomerId = @customerId"; parameterList.Add(new Parameter("customerId", id.CustomerId)); TextBuilder tb = new TextBuilder(_templateSql, new { where = where }); string sql = tb.Generate(); DagentDatabase db = new DagentDatabase(_connection); CartProxy cart = db.Query<CartProxy>(sql, parameterList.ToArray()) .Unique("CustomerId") .Create(row => new CartProxy(row.Get<int>("CustomerId"))) .Each((model, row) => { row.Map(model, x => x.CartItemList, "CartItemNo") .Create(() => new CartItemEntity(row.Get<int>("CustomerId"), row.Get<int>("CartItemNo"))) .Do(); }) .Single(); return cart; }
public static void UsingTextBuilderAndFragment() { // ExStart:UsingTextBuilderAndFragment // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Create Document instance Document pdfDocument = new Document(); // Add page to pages collection of Document Page page = pdfDocument.Pages.Add(); // Create TextBuilder instance TextBuilder builder = new TextBuilder(pdfDocument.Pages[1]); // Create text fragment instance with sample contents TextFragment wideFragment = new TextFragment("Text with increased character spacing"); wideFragment.TextState.ApplyChangesFrom(new TextState("Arial", 12)); // Specify character spacing for TextFragment wideFragment.TextState.CharacterSpacing = 2.0f; // Specify the position of TextFragment wideFragment.Position = new Position(100, 650); // Append TextFragment to TextBuilder instance builder.AppendText(wideFragment); dataDir = dataDir + "CharacterSpacingUsingTextBuilderAndFragment_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:UsingTextBuilderAndFragment Console.WriteLine("\nCharacter spacing specified successfully using Text builder and fragment.\nFile saved at " + dataDir); }
private static void TestEach(){ // Prepare meta data const string className = "Example"; var members = new Dictionary<string, string>{ {"id", "int"}, {"name", "string"} }; // Generate CPP class var code = new TextBuilder(); code.ConfigTab(4) .Line("//Begin Test Each") .Line("class {0} ", className) .PushLine("{") .TopLine("private:") .Each(members) .Line("{1} m_{0};", m => m.Key, m => m.Value) .End() .Line() .TopLine("public:") .Line("{0}()", className) .PushLine("{") .Line("// TODO") .PopLine("}") .Line() .Line("~{0}()", className) .PushLine("{") .Line("// TODO") .PopLine("}") .Line() .TopLine("public:") .Each(members) .Line("const {1}& get_{0}()const", m => m.Key, m => m.Value) .PushLine("{") .Line("return m_{0};", m => m.Key) .PopLine("}") .Line() .Line("void set_{0}(const {1}& v)", m => m.Key, m => m.Value) .PushLine("{") .Line("m_{0} = v;", m => m.Key) .PopLine("}") .Line() .End() .PopLine("}") .Line("// End") .Line(); // Print Code Console.WriteLine(code.ToString()); }
private static void TestSwitchCase(){ var code=new TextBuilder(); var numbers=new[]{ 1, 2 }; code.ConfigTab(4) .Line("// Begin Test SwitchCase") .Line("int test(int i)") .Line("{") .Push() .Line("switch(i)") .Line("{") .Push() .Each(numbers) .Line("case {0}:", i => i) .Switch(i => i) .Case(1) .Push() .Line("int i={0};", s => s) .Line("break;") .Pop() .Case(2) .Push() .Line("int x={0};", s => s) .Line("break;") .Pop() .Default() .Line("default:") .Push() .Line("assert(false);") .Line("break;") .Pop() .End() .End() .Pop() .Line("}") .Pop() .Line("}") .Line("// End") .Line(); Console.WriteLine(code.ToString()); }
public void Add(TextBuilder characters, int start, int count, Vector2 screenToPackedScale, Vector2 startingPosition, Vector2 horizontalAxis, Vector3 color, float height, Font font) { var scale = height * font.Content.InverseSizeInTexels; //Note that we don't actually include glyphs for spaces, so this could result in an oversized allocation. Not very concerning; no effect on correctness. var potentiallyRequiredCapacity = GlyphCount + count; if (potentiallyRequiredCapacity > glyphs.Length) { Array.Resize(ref glyphs, Math.Max(potentiallyRequiredCapacity, glyphs.Length * 2)); } var penPosition = startingPosition; var verticalAxis = new Vector2(-horizontalAxis.Y, horizontalAxis.X); var nextCharacterIndex = start; var characterEnd = start + count; while (true) { if (nextCharacterIndex >= characterEnd) { break; } var character = characters[nextCharacterIndex++]; //Only create a glyph for characters that our font actually has entries for. Others will just be skipped without advancing. if (font.Content.Characters.TryGetValue(character, out var characterData)) { //No point wasting time rendering a glyph with nothing in it. At least for any normal-ish font. if (character != ' ') { ref var glyph = ref glyphs[GlyphCount++]; //Note subtraction on y component. In texture space, +1 is down, -1 is up. var localOffsetToCharacter = new Vector2(characterData.Bearing.X * scale, characterData.Bearing.Y * scale); var offsetToCharacter = localOffsetToCharacter.X * horizontalAxis - localOffsetToCharacter.Y * verticalAxis; var minimum = penPosition + offsetToCharacter; glyph = new GlyphInstance(ref minimum, ref horizontalAxis, scale, font.GetSourceId(character), ref color, ref screenToPackedScale); } //Move the pen to the next character. float advance = characterData.Advance; if (nextCharacterIndex < characterEnd) { advance += font.Content.GetKerningInTexels(character, characters[nextCharacterIndex]); } penPosition += horizontalAxis * (scale * advance); } }
public static void AddNewLineFeed() { try { // ExStart:AddNewLineFeed // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); Aspose.Pdf.Document pdfApplicationDoc = new Aspose.Pdf.Document(); Aspose.Pdf.Page applicationFirstPage = (Aspose.Pdf.Page)pdfApplicationDoc.Pages.Add(); // Initialize new TextFragment with text containing required newline markers Aspose.Pdf.Text.TextFragment textFragment = new Aspose.Pdf.Text.TextFragment("Applicant Name: " + Environment.NewLine + " Joe Smoe"); // Set text fragment properties if necessary textFragment.TextState.FontSize = 12; textFragment.TextState.Font = Aspose.Pdf.Text.FontRepository.FindFont("TimesNewRoman"); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; // Create TextParagraph object TextParagraph par = new TextParagraph(); // Add new TextFragment to paragraph par.AppendLine(textFragment); // Set paragraph position par.Position = new Aspose.Pdf.Text.Position(100, 600); // Create TextBuilder object TextBuilder textBuilder = new TextBuilder(applicationFirstPage); // Add the TextParagraph using TextBuilder textBuilder.AppendParagraph(par); dataDir = dataDir + "AddNewLineFeed_out.pdf"; // Save resulting PDF document. pdfApplicationDoc.Save(dataDir); // ExEnd:AddNewLineFeed Console.WriteLine("\nNew line feed added successfully.\nFile saved at " + dataDir); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static ReadOnlyCollection <Line> GetConstructor(string name, ReadOnlyCollection <DataTransferObjectField> fields) { var textBuilder = new TextBuilder(); var parameters = fields.Select(field => $"{field.Type} {field.Name.ToCamelCase()}").Join(", "); textBuilder.Add($"public {name}({parameters})"); using (textBuilder.AddCSharpBlock()) { foreach (var field in fields) { textBuilder.Add($"{field.Name} = {field.Name.ToCamelCase()};"); } } return(textBuilder.ToLines()); }
public override void Render(Renderer renderer, Camera camera, Input input, TextBuilder text, Font font) { //var step = debugSteps[stepIndex]; //var scale = 10f; //for (int i = 0; i < points.Count; ++i) //{ // var pose = new RigidPose(points[i] * scale); // renderer.Shapes.AddShape(new Box(0.1f, 0.1f, 0.1f), Simulation.Shapes, ref pose, new Vector3(0.5f, 0.5f, 0.5f)); // if (!step.AllowVertex[i]) // renderer.Shapes.AddShape(new Box(0.6f, 0.25f, 0.25f), Simulation.Shapes, ref pose, new Vector3(1, 0, 0)); //} //for (int i = 0; i < step.Raw.Count; ++i) //{ // var pose = new RigidPose(points[step.Raw[i]] * scale); // renderer.Shapes.AddShape(new Box(0.25f, 0.6f, 0.25f), Simulation.Shapes, ref pose, new Vector3(0, 0, 1)); //} //for (int i = 0; i < step.Reduced.Count; ++i) //{ // var pose = new RigidPose(points[step.Reduced[i]] * scale); // renderer.Shapes.AddShape(new Box(0.25f, 0.25f, 0.6f), Simulation.Shapes, ref pose, new Vector3(0, 1, 0)); //} //for (int i = 0; i <= stepIndex; ++i) //{ // var pose = RigidPose.Identity; // var oldStep = debugSteps[i]; // for (int j = 2; j < oldStep.Reduced.Count; ++j) // { // renderer.Shapes.AddShape(new Triangle // { // A = points[oldStep.Reduced[0]] * scale, // B = points[oldStep.Reduced[j]] * scale, // C = points[oldStep.Reduced[j - 1]] * scale // }, Simulation.Shapes, ref pose, new Vector3(1, 0, 1)); // } //} //var edgeMidpoint = (points[step.SourceEdge.A] + points[step.SourceEdge.B]) * scale * 0.5f; //renderer.Lines.Allocate() = new LineInstance(edgeMidpoint, edgeMidpoint + step.BasisX * scale * 0.5f, new Vector3(1, 1, 0), new Vector3()); //renderer.Lines.Allocate() = new LineInstance(edgeMidpoint, edgeMidpoint + step.BasisY * scale * 0.5f, new Vector3(0, 1, 0), new Vector3()); //renderer.TextBatcher.Write( // text.Clear().Append($"Enumerate step with X and C. Current step: ").Append(stepIndex + 1).Append(" out of ").Append(debugSteps.Count), // new Vector2(32, renderer.Surface.Resolution.Y - 140), 20, new Vector3(1), font); base.Render(renderer, camera, input, text, font); }
public async Task <bool?> Process(User user, string nickname, CancellationToken cancellationToken = default) { var player = await myContext.Set <Player>().Get(user, cancellationToken); if (!string.IsNullOrEmpty(nickname)) { if (player == null) { player = new Player { UserId = user.Id }; myContext.Add(player); } player.Nickname = nickname; await myContext.SaveChangesAsync(cancellationToken); } IReplyMarkup?replyMarkup = null; var builder = new TextBuilder(); if (!string.IsNullOrEmpty(player?.Nickname)) { builder .Append($"Your IGN is {player.Nickname:bold}") .NewLine() .NewLine(); replyMarkup = new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData("Clear IGN", $"{PlayerCallbackQueryHandler.ID}:{PlayerCallbackQueryHandler.Commands.ClearIGN}")); } builder .Append($"To set up your in-game-name reply with it to this message.").NewLine() .Append($"Or use /{COMMAND} command.").NewLine() .Code("/ign your-in-game-name"); await myBot.SendTextMessageAsync(user.Id, builder.ToTextMessageContent(), cancellationToken : cancellationToken, replyMarkup : replyMarkup ?? new ForceReplyMarkup { InputFieldPlaceholder = "in-game-name" }); return(false); // processed, but not pollMessage }
/// <summary> /// Generates the serializer code for an enum /// </summary> /// <param name="dataType">Type of the data.</param> /// <returns>Serializer code for enums</returns> private string GenerateSerializerDefinition(XerusEnumType dataType, string serializerName) { string name = dataType.Name; int maxValue = 0; foreach (var xerusEnumMemberType in dataType.Members) { if (xerusEnumMemberType.DefinedValue > maxValue) { maxValue = xerusEnumMemberType.DefinedValue; } } var tb = new TextBuilder(); tb.AppendLine(string.Format( @"/** Serializer for data type {0} * @param input Data type * @param data Buffer for the serialized data * @return Length of the serialized data in bytes */", name)); tb.AppendLine("uint16 " + serializerName + "::{0}_To_Bytes(const {0} input, uint8 *const data)", name); tb.AppendLine("{"); tb.PushIndent(); if (maxValue > 65535) { tb.AppendLine("uint32_To_Bytes((const uint32)input, data);"); tb.AppendLine("return 4;"); } else if (maxValue > 255) { tb.AppendLine("uint16_To_Bytes((const uint16)input, data);"); tb.AppendLine("return 2;"); } else { tb.AppendLine("data[0] = input;"); tb.AppendLine("return 1;"); } tb.PopIndent(); tb.AppendLine("}"); return(tb.ToString()); }
public void Exporters_DatExporter_FromLfpTest() { // Arrange var mockReader = new Mock <TextReader>(); var mockWriter = new Mock <TextWriter>(); int calls = 0; mockReader .Setup(r => r.ReadLine()) .Returns(() => optLines[calls]) .Callback(() => calls++); List <string> output = new List <string>(); mockWriter .Setup(r => r.WriteLine(It.IsAny <string>())) .Callback((string s) => output.Add(s)); FileInfo infile = new FileInfo(@"X:\VOL001\infile.opt"); TextBuilder rep = new TextBuilder( TextBuilder.TextLevel.None, TextBuilder.TextLocation.None, null, null); var builder = new OptBuilder(); IParser parser = new DatParser(Delimiters.COMMA_DELIMITED); builder.PathPrefix = String.Empty; builder.TextBuilder = rep; // act List <string[]> records = parser.Parse(mockReader.Object); List <Document> documents = builder.Build(records); DocumentCollection docs = new DocumentCollection(documents); string[] fields = new string[] { "DocID", "Page Count" }; var exporter = DatExporter.Builder .Start(mockWriter.Object, fields) .SetDelimiters(Delimiters.COMMA_QUOTE) .Build(); exporter.Export(docs); // assert Assert.AreEqual("\"DocID\",\"Page Count\"", output[0]); Assert.AreEqual("\"000000001\",\"1\"", output[1]); Assert.AreEqual("\"000000002\",\"2\"", output[2]); }
public static void Main(string[] args) { if (args[0].Equals("plain")) { TextBuilder textBuilder = new TextBuilder(); Director director = new Director(textBuilder); director.Construct(); System.Console.WriteLine(textBuilder.GetResult()); } if (args[0].Equals("html")) { HtmlBuilder htmlBuilder = new HtmlBuilder(); Director director = new Director(htmlBuilder); director.Construct(); System.Console.WriteLine(htmlBuilder.GetResult()); } }
public static Dictionary <string, string> GetModels(string modelsNamespace, IDictionary <string, string> files) { var umbraco = Application.GetApplication(); var typeModels = umbraco.GetAllTypes(); var parseResult = new CodeParser().ParseWithReferencedAssemblies(files); var builder = new TextBuilder(typeModels, parseResult, modelsNamespace); var models = new Dictionary <string, string>(); foreach (var typeModel in builder.GetModelsToGenerate()) { var sb = new StringBuilder(); builder.Generate(sb, typeModel); models[typeModel.ClrName] = sb.ToString(); } return(models); }
public async Task <bool?> Handle(MessageEntityEx data, PollMessage context = default, CancellationToken cancellationToken = default) { if (!this.ShouldProcess(data, context)) { return(null); } var player = await myDB.Set <Player>().Get(data.Message.From, cancellationToken); var content = new TextBuilder("When someone is asking for Friendship") .ToTextMessageContent(); var replyMarkup = GetInlineKeyboardMarkup(player); await myBot.SendTextMessageAsync(data.Message.Chat.Id, content, replyMarkup : replyMarkup, cancellationToken : cancellationToken); return(false); // processed, but not pollMessage }
public static void Generate(string text, Font font) { using (var img = new Image <Rgba32>(1000, 1000)) { img.Fill(Rgba32.White); var box = TextMeasurer.MeasureBounds(text, new RendererOptions(font)); var data = TextBuilder.GenerateGlyphsWithBox(text, new RendererOptions(font)); var f = Rgba32.Fuchsia; f.A = 128; img.Fill(Rgba32.Black, data.paths); img.Draw(f, 1, data.boxes); img.Draw(Rgba32.Lime, 1, new SixLabors.Shapes.RectangularePolygon(box)); img.Save("Output/Boxed.png"); } }
// Başlangıç indisinden[startIndex] başlayarak belirlenden karaktere [endchar] kadar keser public string Cut(string value, int startIndex, char endChar) { using (TextBuilder b = new TextBuilder()) { for (int i = startIndex; i < value.Length; i++) { if (value[i] == endChar) { break; } else { b.Append(value[i]); } } return(b.ToString()); } }
public string Cut(string value, int startIndex, int endIndex) { using (TextBuilder b = new TextBuilder()) { for (int i = startIndex; i <= endIndex; i++) { try { b.Append(value[i]); } catch { break; } } return(b.ToString()); } }
public void HeadingFilledWithTextBuilder() { string headingText = "Some Heading with\n styles\t and more"; //Create a new text document TextDocument document = new TextDocument(); document.New(); //Create a new Heading Header header = new Header(document, Headings.Heading); //Create a TextCollection from headingText using the TextBuilder ITextCollection textCol = TextBuilder.BuildTextCollection(document, headingText); //Add text collection header.TextContent = textCol; //Add header document.Content.Add(header); document.SaveTo(AARunMeFirstAndOnce.outPutFolder + "HeadingWithControlCharacter.odt"); }
public static void RenderText( Font font, string text, string outputPath, Rgba32?backgroundColor = null) { if (font == null) { return; } var style = new RendererOptions(font, 72); var rawShapes = TextBuilder.GenerateGlyphs(text, new PointF(0, 0), style); var shapes = rawShapes.Translate(-rawShapes.Bounds.X, -rawShapes.Bounds.Y); const int safetyFrame = 0; var bounds = shapes.Bounds; var width = (int)Math.Ceiling(bounds.Width + safetyFrame); var height = (int)Math.Ceiling(bounds.Height + safetyFrame); if (width <= 0) { width = MinimumSide; } if (height <= 0) { height = MinimumSide; } using (var render = new Image <Rgba32>(width, height)) { var actualBackgroundColor = backgroundColor ?? Rgba32.Transparent; render.Mutate(operation => operation.Fill(actualBackgroundColor)); render.Mutate(operation => operation.Fill(Rgba32.Black, shapes)); if (File.Exists(outputPath)) { File.Delete(outputPath); } using (var stream = File.Create(outputPath)) { render.SaveAsPng(stream); } } }
static void Main(string[] args) { System.IO.Directory.CreateDirectory("output"); using (Image img = new Image <Rgba32>(1500, 500)) { PathBuilder pathBuilder = new PathBuilder(); pathBuilder.SetOrigin(new PointF(500, 0)); pathBuilder.AddBezier(new PointF(50, 450), new PointF(200, 50), new PointF(300, 50), new PointF(450, 450)); // add more complex paths and shapes here. IPath path = pathBuilder.Build(); // For production application we would recomend you create a FontCollection // singleton and manually install the ttf fonts yourself as using SystemFonts // can be expensive and you risk font existing or not existing on a deployment // by deployment basis. var font = SystemFonts.CreateFont("Arial", 39, FontStyle.Regular); string text = "Hello World Hello World Hello World Hello World Hello World"; var textGraphicsOptions = new TextGraphicsOptions(true) // draw the text along the path wrapping at the end of the line { WrapTextWidth = path.Length }; // lets generate the text as a set of vectors drawn along the path var glyphs = TextBuilder.GenerateGlyphs(text, path, new RendererOptions(font, textGraphicsOptions.DpiX, textGraphicsOptions.DpiY) { HorizontalAlignment = textGraphicsOptions.HorizontalAlignment, TabWidth = textGraphicsOptions.TabWidth, VerticalAlignment = textGraphicsOptions.VerticalAlignment, WrappingWidth = textGraphicsOptions.WrapTextWidth, ApplyKerning = textGraphicsOptions.ApplyKerning }); img.Mutate(ctx => ctx .Fill(Color.White) // white background image .Draw(Color.Gray, 3, path) // draw the path so we can see what the text is supposed to be following .Fill((GraphicsOptions)textGraphicsOptions, Color.Black, glyphs)); img.Save("output/wordart.png"); } }
public static void AddStrikeOutText() { try { // ExStart:AddStrikeOutText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(); // Get particular page Page pdfPage = (Page)pdfDocument.Pages.Add(); // Create text fragment TextFragment textFragment = new TextFragment("main text"); textFragment.Position = new Position(100, 600); // Set text properties textFragment.TextState.FontSize = 12; textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; // Set StrikeOut property textFragment.TextState.StrikeOut = true; // Mark text as Bold textFragment.TextState.FontStyle = FontStyles.Bold; // Create TextBuilder object TextBuilder textBuilder = new TextBuilder(pdfPage); // Append the text fragment to the PDF page textBuilder.AppendText(textFragment); dataDir = dataDir + "AddStrikeOutText_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:AddStrikeOutText Console.WriteLine("\nStrikeOut text added successfully.\nFile saved at " + dataDir); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void Exporters_LfpExporter_FromOptTest() { // Arrange var mockReader = new Mock <TextReader>(); var mockWriter = new Mock <TextWriter>(); int calls = 0; mockReader .Setup(r => r.ReadLine()) .Returns(() => optLines[calls]) .Callback(() => calls++); List <string> output = new List <string>(); mockWriter .Setup(r => r.WriteLine(It.IsAny <string>())) .Callback((string s) => output.Add(s)); FileInfo infile = new FileInfo(@"X:\VOL001\infile.opt"); string vol = "TEST001"; TextBuilder rep = new TextBuilder( TextBuilder.TextLevel.None, TextBuilder.TextLocation.None, null, null); var builder = new OptBuilder(); IParser parser = new DatParser(Delimiters.COMMA_DELIMITED); builder.PathPrefix = String.Empty; builder.TextBuilder = rep; // act List <string[]> records = parser.Parse(mockReader.Object); List <Document> documents = builder.Build(records); DocumentCollection docs = new DocumentCollection(documents); var exporter = LfpExporter.Builder .Start(mockWriter.Object) .SetVolumeName(vol) .Build(); exporter.Export(docs); // assert Assert.AreEqual("IM,000000001,D,0,@TEST001;X:\\VOL001\\IMAGES\\0001;000000001.jpg;4,0", output[0]); Assert.AreEqual("IM,000000002,D,0,@TEST001;X:\\VOL001\\IMAGES\\0001;000000002.tif;2,0", output[1]); Assert.AreEqual("IM,000000003,,0,@TEST001;X:\\VOL001\\IMAGES\\0001;000000003.tif;2,0", output[2]); }
/// <summary> /// Generate a non- PDF/UA compliant PDF for use in demo /// </summary> /// <param name="outputFilePath">Full output path including filename with extension</param> public static void CreateDemoNonCompliantPdfFile(string outputFilePath) { var pdfDoc = new Document(); pdfDoc.Pages.Add(); var pageOne = pdfDoc.Pages[1]; #region Add image int lowerLeftX = 100; int lowerLeftY = 680; int upperRightX = 200; int upperRightY = 780; FileStream imageStream = new FileStream("aspose.png", FileMode.Open); pageOne.Resources.Images.Add(imageStream); pageOne.Contents.Add(new Aspose.Pdf.Operators.GSave()); Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY); Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY }); pageOne.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix)); XImage ximage = pageOne.Resources.Images[pageOne.Resources.Images.Count]; pageOne.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name)); pageOne.Contents.Add(new Aspose.Pdf.Operators.GRestore()); #endregion #region Add text fragments var textFragmentOne = new TextFragment("Some large indigo text for our header."); textFragmentOne.Position = new Position(100, 800); textFragmentOne.TextState.FontSize = 24; textFragmentOne.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragmentOne.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Indigo); var textFragmentTwo = new TextFragment("Some smaller blue text in a non-tagged document."); textFragmentTwo.Position = new Position(100, 660); textFragmentTwo.TextState.FontSize = 12; textFragmentTwo.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragmentTwo.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue); var textBuilder = new TextBuilder(pageOne); textBuilder.AppendText(textFragmentOne); textBuilder.AppendText(textFragmentTwo); #endregion pdfDoc.Save(outputFilePath); }
public static void Run() { // ExStart:AddText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(dataDir + "input.pdf"); // Get particular page Page pdfPage = (Page)pdfDocument.Pages[1]; // Create text fragment TextFragment textFragment = new TextFragment("main text"); textFragment.Position = new Position(100, 600); // Set text properties textFragment.TextState.FontSize = 12; textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray); textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Red); // Create TextBuilder object TextBuilder textBuilder = new TextBuilder(pdfPage); // Append the text fragment to the PDF page textBuilder.AppendText(textFragment); dataDir = dataDir + "AddText_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:AddText Console.WriteLine("\nText added successfully.\nFile saved at " + dataDir); AddUnderlineText(); AddingBorderAroundAddedText(); AddTextUsingTextParagraph(); AddHyperlinkToTextSegment(); OTFFont(); AddStrikeOutText(); }
public static TextBuilder AppendDump(this TextBuilder textBuilder, MemberInfo?member, DumpOptions options = default) { if (member is null) { if (options.Verbose) { return(textBuilder.Append("(MemberInfo)null")); } return(textBuilder); } if (member is FieldInfo fieldInfo) { return(AppendDump(textBuilder, fieldInfo, options)); } // Fallback return(textBuilder.Append(member)); }
void Supl(int id) //бланк в разрезе по поставщикам, поэтому функция для фильтрации объектов того или иного поставщика { SpreadsheetDocument spreadsheetDocument = new SpreadsheetDocument(); spreadsheetDocument.New(); Table table = new Table(spreadsheetDocument, "First", "tablefirst"); for (int j = 0; j < countsup; j++) { Paragraph parag = ParagraphBuilder.CreateSpreadsheetParagraph(spreadsheetDocument); var text = TextBuilder.BuildTextCollection(spreadsheetDocument, " "); Cell cell = table.CreateCell(); parag.TextContent.Add(new SimpleText(spreadsheetDocument, "элемент бд, где поставщик ид=ид"));//И за это тоже выебу и в прямом, и в переносном смысле за такие фразы cell.Content.Add(parag); table.InsertCellAt(0, 0, cell); spreadsheetDocument.TableCollection.Add(table); spreadsheetDocument.SaveTo("Matr.ods"); } }
private void RenderFontToTexture(Font font, ref ISet <char> requestedSymbols, int textureSize, int padding) { var options = new RendererOptions(font); int x = 0, y = 0, maxHeight = 0; do { var glyphStr = $"{requestedSymbols.First()}"; var glyph = glyphStr[0]; var sizeF = TextMeasurer.Measure(glyphStr, options); var size = new Size((int)Math.Ceiling(sizeF.Width), (int)Math.Ceiling(sizeF.Height)); maxHeight = Math.Max(maxHeight, size.Height); var dstRect = new Rectangle(x, y, size.Width, size.Height); if (dstRect.Right >= textureSize) { // jump onto the next line x = 0; y += maxHeight + padding; maxHeight = 0; dstRect.X = x; dstRect.Y = y; } if (dstRect.Bottom >= textureSize) { // we can't fit letters anymore break; } var shapes = TextBuilder.GenerateGlyphs(glyphStr, new SPointF(x, y), options); Texture.Mutate(m => m.Fill(Rgba32.White, shapes)); _glyphMap.Add(glyph, dstRect); requestedSymbols.Remove(glyph); if (Start == default(char)) { Start = glyph; } End = glyph; x += size.Width + padding; } while (requestedSymbols.Any()); }
public void TestCharacterWithHigherBaselineGetsOffset() { var builder = new TextBuilder(fontStore, normal_font); builder.AddText("m"); Assert.That(builder.LineBaseHeight, Is.EqualTo(m_baseline)); builder.AddText("b"); Assert.That(builder.LineBaseHeight, Is.EqualTo(m_baseline)); Assert.That(builder.Characters[1].DrawRectangle.Top, Is.EqualTo(b_y_offset + (m_baseline - b_baseline))); builder.AddText("a"); Assert.That(builder.LineBaseHeight, Is.EqualTo(m_baseline)); Assert.That(builder.Characters[1].DrawRectangle.Top, Is.EqualTo(b_y_offset + (m_baseline - b_baseline))); Assert.That(builder.Characters[2].DrawRectangle.Top, Is.EqualTo(y_offset + (m_baseline - baseline))); }
public static ReadOnlyCollection <Line> CreateDataTransferObject(string name, ReadOnlyCollection <DataTransferObjectField> fields) { var textBuilder = new TextBuilder(); textBuilder.Add($"public sealed class {name}"); using (textBuilder.AddCSharpBlock()) { foreach (var field in fields) { textBuilder.Add($"public readonly {field.Type} {field.Name};"); } textBuilder.Add(Line.Empty); var constructor = GetConstructor(name, fields); textBuilder.Add(constructor); } return(textBuilder.ToLines()); }
public static void Run() { // ExStart:RotateTextUsingTextFragment string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Initialize document object Document pdfDocument = new Document(); // Get particular page Page pdfPage = (Page)pdfDocument.Pages.Add(); // Create text fragment TextFragment textFragment1 = new TextFragment("main text"); textFragment1.Position = new Position(100, 600); // Set text properties textFragment1.TextState.FontSize = 12; textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman"); // Create rotated text fragment TextFragment textFragment2 = new TextFragment("rotated text"); textFragment2.Position = new Position(200, 600); // Set text properties textFragment2.TextState.FontSize = 12; textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragment2.TextState.Rotation = 45; // Create rotated text fragment TextFragment textFragment3 = new TextFragment("rotated text"); textFragment3.Position = new Position(300, 600); // Set text properties textFragment3.TextState.FontSize = 12; textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragment3.TextState.Rotation = 90; // create TextBuilder object TextBuilder textBuilder = new TextBuilder(pdfPage); // Append the text fragment to the PDF page textBuilder.AppendText(textFragment1); textBuilder.AppendText(textFragment2); textBuilder.AppendText(textFragment3); // Save document pdfDocument.Save(dataDir + "TextFragmentTests_Rotated1_out.pdf"); // ExEnd:RotateTextUsingTextFragment }
/// <summary> /// Generates the deserializer code for an enum. /// </summary> /// <param name="dataType">Type of the data.</param> /// <returns>Derializer code for enums</returns> private string GenerateDeserializerDefinition(XerusEnumType dataType, string serializerName) { string name = dataType.Name; int maxValue = 0; foreach (var xerusEnumMemberType in dataType.Members) { if (xerusEnumMemberType.DefinedValue > maxValue) { maxValue = xerusEnumMemberType.DefinedValue; } } var tb = new TextBuilder(); tb.AppendLine(string.Format( @"/** Deserializer for data type {0} * @param data Buffer with the serialized data * @return Deserialized data type */", name)); tb.AppendLine("uint16 " + serializerName + "::Bytes_To_{0}(const uint8 *const data, {0}& output )", name); tb.AppendLine("{"); tb.PushIndent(); if (maxValue > 65535) { tb.AppendLine("return Bytes_To_uint32(data, (uint32&) output);", name); } else if (maxValue > 255) { tb.AppendLine("return Bytes_To_uint16(data, (uint16&) output);", name); } else { tb.AppendLine("return Bytes_To_uint8(data, (uint8&) output);", name); } tb.PopIndent(); tb.AppendLine("}"); return(tb.ToString()); }
public int ConvertNumber(string value) { using (TextBuilder builder = new TextBuilder()) { for (int i = 0; i < value.Length; i++) { try { if (chs.Contains(value[i]) == true) { builder.Append(value[i]); } } catch { } } return(Convert.ToInt32(builder.ToString().Trim())); } }
public void TextBuilder_Bounds_AreCorrect() { Vector2 position = new(5, 5); var options = new TextOptions(TestFontUtilities.GetFont(TestFonts.OpenSans, 16)) { Origin = position }; string text = "Hello World"; IPathCollection glyphs = TextBuilder.GenerateGlyphs(text, options); RectangleF builderBounds = glyphs.Bounds; FontRectangle measuredBounds = TextMeasurer.MeasureBounds(text, options); Assert.Equal(measuredBounds.X, builderBounds.X); Assert.Equal(measuredBounds.Y, builderBounds.Y); Assert.Equal(measuredBounds.Width, builderBounds.Width); Assert.Equal(measuredBounds.Height, builderBounds.Height); }
public static void RenderText(Font font, string text, int width, int height) { string path = IOPath.GetInvalidFileNameChars().Aggregate(text, (x, c) => x.Replace($"{c}", "-")); string fullPath = IOPath.GetFullPath(IOPath.Combine("Output", IOPath.Combine(path))); using var img = new Image <Rgba32>(width, height); img.Mutate(x => x.Fill(Color.White)); IPathCollection shapes = TextBuilder.GenerateGlyphs(text, new TextOptions(font) { Origin = new Vector2(50f, 4f) }); img.Mutate(x => x.Fill(Color.Black, shapes)); Directory.CreateDirectory(IOPath.GetDirectoryName(fullPath)); using FileStream fs = File.Create(fullPath + ".png"); img.SaveAsPng(fs); }
public virtual string FormatCompoundElement(ICompoundElement element) { TextBuilder builder = new TextBuilder(Template); if (Template.Contains(Constants.TemplateField_ElTypeName)) builder.Replace(Constants.TemplateField_ElTypeName, element.TypeName); if (Template.Contains(Constants.TemplateField_ElId)) builder.Replace(Constants.TemplateField_ElId, element.Id); if (Template.Contains(Constants.TemplateField_ParentId)) builder.Replace(Constants.TemplateField_ParentId, element.ParentId); if (Template.Contains(Constants.TemplateField_ElStatus)) builder.Replace(Constants.TemplateField_ElStatus, element.Status); if (Template.Contains(Constants.TemplateField_Params)) { IParamMgrTextFormatter formatter = TextFormatterFactory.CreateParamMgrFormatter(); builder.Replace(Constants.TemplateField_Params, formatter.Format(element.ParamMgr)); } if (Template.Contains(Constants.TemplateField_Inputs)) { IInputPortMgrTextFormatter formatter = TextFormatterFactory.CreateInputPortMgrFormatter(); builder.Replace(Constants.TemplateField_Inputs, formatter.Format(element.InPortMgr)); } if (Template.Contains(Constants.TemplateField_Outputs)) { IOutputPortMgrTextFormatter formatter = TextFormatterFactory.CreateOutputPortMgrFormatter(); builder.Replace(Constants.TemplateField_Outputs, formatter.Format(element.OutPortMgr)); } if (Template.Contains(Constants.TemplateField_Settings)) { ISettingsMgrTextFormatter formatter = TextFormatterFactory.CreateSettingsMgrFormatter(); builder.Replace(Constants.TemplateField_Settings, formatter.Format(element.SettingsMgr)); } if (Template.Contains(Constants.TemplateField_Options)) { IOptionsMgrTextFormatter formatter = TextFormatterFactory.CreateOptionsMgrFormatter(); builder.Replace(Constants.TemplateField_Options, formatter.Format(element.OptionsMgr)); } return builder.ToString(); }
public static void Run() { // ExStart:RenderingReplaceableSymbols // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); Aspose.Pdf.Document pdfApplicationDoc = new Aspose.Pdf.Document(); Aspose.Pdf.Page applicationFirstPage = (Aspose.Pdf.Page)pdfApplicationDoc.Pages.Add(); // Initialize new TextFragment with text containing required newline markers Aspose.Pdf.Text.TextFragment textFragment = new Aspose.Pdf.Text.TextFragment("Applicant Name: " + Environment.NewLine + " Joe Smoe"); // Set text fragment properties if necessary textFragment.TextState.FontSize = 12; textFragment.TextState.Font = Aspose.Pdf.Text.FontRepository.FindFont("TimesNewRoman"); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; // Create TextParagraph object TextParagraph par = new TextParagraph(); // Add new TextFragment to paragraph par.AppendLine(textFragment); // Set paragraph position par.Position = new Aspose.Pdf.Text.Position(100, 600); // Create TextBuilder object TextBuilder textBuilder = new TextBuilder(applicationFirstPage); // Add the TextParagraph using TextBuilder textBuilder.AppendParagraph(par); dataDir = dataDir + "RenderingReplaceableSymbols_out.pdf"; pdfApplicationDoc.Save(dataDir); // ExEnd:RenderingReplaceableSymbols Console.WriteLine("\nReplaceable symbols render successfully duing pdf creation.\nFile saved at " + dataDir); }
public override void DeleteRangeSpanningSegmentBoundaryAndWholeTwfics() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(para0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); // remove segment boundary pb.DeleteSegmentBreak(0, 3); // delete "xxxnihimbilira xxxnihimbilira xxxpus" from first sentence pb.RemoveSegmentForm(0, 2); // (first) xxxnihimbilira pb.RemoveSegmentForm(0, 2); // (second) xxxnihimbilira pb.RemoveSegmentForm(0, 2); // (second) xxxpus XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.DeleteRangeSpanningSegmentBoundaryAndWholeTwfics(); }
public static void AddTextUsingTextParagraph() { // ExStart:AddTextUsingTextParagraph // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document doc = new Document(); // Add page to pages collection of Document object Page page = doc.Pages.Add(); TextBuilder builder = new TextBuilder(page); // Create text paragraph TextParagraph paragraph = new TextParagraph(); // Set subsequent lines indent paragraph.SubsequentLinesIndent = 20; // Specify the location to add TextParagraph paragraph.Rectangle = new Aspose.Pdf.Rectangle(100, 300, 200, 700); // Specify word wraping mode paragraph.FormattingOptions.WrapMode = TextFormattingOptions.WordWrapMode.ByWords; // Create text fragment TextFragment fragment1 = new TextFragment("the quick brown fox jumps over the lazy dog"); fragment1.TextState.Font = FontRepository.FindFont("Times New Roman"); fragment1.TextState.FontSize = 12; // Add fragment to paragraph paragraph.AppendLine(fragment1); // Add paragraph builder.AppendParagraph(paragraph); dataDir = dataDir + "AddTextUsingTextParagraph_out.pdf"; // Save resulting PDF document. doc.Save(dataDir); // ExEnd:AddTextUsingTextParagraph Console.WriteLine("\nText using text paragraph added successfully.\nFile saved at " + dataDir); }
public override void DeleteAllSentencesResultingInEmptyPara() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(para0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); // remove all segments pb.RemoveSegment(2); pb.RemoveSegment(1); pb.RemoveSegment(0); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.DeleteAllSentencesResultingInEmptyPara(); }
public override void ReplaceSentencesWithSentence() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(para0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); // remove last two segments pb.RemoveSegment(2); pb.RemoveSegment(1); // remove all but one form in the sentence pb.RemoveSegmentForm(0, 3); pb.RemoveSegmentForm(0, 2); pb.RemoveSegmentForm(0, 1); pb.ReplaceSegmentForm(0, 0, "xxxsup", 0); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.ReplaceSentencesWithSentence(); }
/// <summary> /// Override the main body of this test to adjust the expected annotations. /// 1 2 3 4 5 6 7 8 9 /// 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 ///1 xxxpus xxxyalola xxxnihimbilira. xxxnihimbilira xxxpus xxxyalola. xxxhesyla xxxnihimbilira. /// paste xxxNew\r\n at start of para ///1 xxxNew ///2 nxxxMoreNew xxxpus xxxyalola xxxnihimbilira. xxxnihimbilira xxxpus xxxyalola. xxxhesyla xxxnihimbilira. /// </summary> protected override void PasteParaPlusTextAtStart(StTxtPara para0, out TextSelInfo tsiBeforePaste, out TextSelInfo tsiAfterPaste) { m_rtp.TextBuilder.SelectNode(para0, 0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); pb.InsertSegmentForm(0, 0, LangProject.kguidAnnWordformInContext, "xxxMoreNew"); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.PasteParaPlusTextAtStart(para0, out tsiBeforePaste, out tsiAfterPaste); }
/// <summary> /// /// </summary> /// <param name="textsDefinitionRelativePath"></param> /// <param name="index"></param> /// <param name="textsDefn"></param> /// <param name="tb"></param> /// <returns></returns> protected FDO.IText LoadTestText(string textsDefinitionRelativePath, int index, XmlDocument textsDefn, out TextBuilder tb) { string textsDefinitionsPath = ConfigurationFilePath(textsDefinitionRelativePath); textsDefn.Load(textsDefinitionsPath); XmlNode text1Defn = textsDefn.SelectSingleNode("/Texts6001/Text[" + index + "]"); tb = new ParagraphParserTests.TextBuilder(Cache); return tb.BuildText(text1Defn); }
public override void DeleteParagraphBreak() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(null); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); tb.DeleteParagraphBreak(para0); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.DeleteParagraphBreak(); }
public virtual void DeleteAllParagraphs() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(null); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); IStTxtPara newPara = tb.AppendNewParagraph(); ParagraphBuilder pb = tb.GetParagraphBuilder(newPara.Hvo); pb.CreateSegmentNode(); pb.CreateSegmentForms(); pb.InsertSegmentForm(0, 0, LangProject.kguidAnnPunctuationInContext, "."); pb.InsertSegmentForm(0, 0, LangProject.kguidAnnWordformInContext, "xxxups"); pb.InsertSegmentForm(0, 1, LangProject.kguidAnnWordformInContext, "xxxloyala"); pb.InsertSegmentForm(0, 2, LangProject.kguidAnnWordformInContext, "xxxliranihimbi"); pb.RebuildParagraphContentFromAnnotations(); m_rtp.SelectAll(); TextSelInfo tsiBeforeDel; m_rtp.OnDelete(out tsiBeforeDel); m_rtp.ValidateStTextAnnotations(); }
public override void InsertSentencesAfterFirstSentence() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(para0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); // replace wordforms pb.InsertSegmentForm(1, 0, LangProject.kguidAnnWordformInContext, "xxxfirstnew"); pb.InsertSegmentForm(1, 1, LangProject.kguidAnnWordformInContext, "xxxsentence"); pb.InsertSegmentForm(1, 2, LangProject.kguidAnnWordformInContext, "xxxsecondnew"); pb.InsertSegmentForm(1, 3, LangProject.kguidAnnWordformInContext, "xxxsentence"); // insert segment breaks pb.InsertSegmentBreak(1, 4, "."); pb.InsertSegmentBreak(1, 2, "."); pb.ReplaceTrailingWhitepace(1, 2, 1); pb.ReplaceTrailingWhitepace(2, 2, 1); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.InsertSentencesAfterFirstSentence(); }
public override void ReplaceSentenceWithSentences() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(para0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); // replace wordforms pb.ReplaceSegmentForm(0, 0, "xxxsup", 0); pb.ReplaceSegmentForm(0, 1, "xxxalolay", 0); pb.ReplaceSegmentForm(0, 2, "xxxarilibmihin", 0); // insert segment breaks pb.InsertSegmentBreak(0, 2, "."); pb.ReplaceTrailingWhitepace(0, 2, 1); pb.InsertSegmentBreak(0, 1, "."); pb.ReplaceTrailingWhitepace(0, 1, 1); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.ReplaceSentenceWithSentences(); }
public override void ReplaceSentenceWithSameSizeSentence() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(para0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); pb.ReplaceSegmentForm(0, 0, "xxxsup", 0); pb.ReplaceSegmentForm(0, 1, "xxxalolay", 0); pb.ReplaceSegmentForm(0, 2, "xxxarilibmihin", 0); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.ReplaceSentenceWithSameSizeSentence(); }
private static void TestIfElse(){ var code=new TextBuilder(); code.ConfigTab(4) .Line("// Begin Test IfElse") .If(s => s, "x") .Line("if") .Line("if") .Else() .Line("else") .Line("else") .If(s => s, "") .Line(" else if:{0}", v => v) .Line(" else if") .Else() .Line(" else if else:{0}", v => v) .Line(" else if else") .End() .End() .Line("// End") .Line(); Console.WriteLine(code.ToString()); }
public override void DeleteLastTwficIn1stSentence() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(para0, 0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); pb.RemoveSegmentForm(0, 2); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.DeleteLastTwficIn1stSentence(); }
public override void DeleteSentenceWithoutSegmentBreakChar() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(para0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); // Setup new initial state: // remove last two segments and last punctuation. pb.RemoveSegment(2); pb.RemoveSegment(1); pb.RemoveSegmentForm(0, 3); // last period m_rtp.TextBuilder.SetTextDefnFromSelectedNode(ParagraphBuilder.Snapshot(tb.SelectedNode)); // remove remaining segment pb.RemoveSegment(0); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.DeleteSentenceWithoutSegmentBreakChar(); }
/// <summary> /// Converts the given HTML to plain text and returns the result. /// </summary> /// <param name="html">HTML to be converted</param> /// <returns>Resulting plain text</returns> public string Convert(string html) { // Initialize state variables _text = new TextBuilder(); _html = html; _pos = 0; // Process input while (!EndOfText) { if (Peek() == '<') { // HTML tag bool selfClosing; string tag = ParseTag(out selfClosing); // Handle special tag cases if (tag == "body") { // Discard content before <body> _text.Clear(); } else if (tag == "/body") { // Discard content after </body> _pos = _html.Length; } else if (tag == "pre") { // Enter preformatted mode _text.Preformatted = true; EatWhitespaceToNextLine(); } else if (tag == "/pre") { // Exit preformatted mode _text.Preformatted = false; } string value; if (_tags.TryGetValue(tag, out value)) _text.Write(value); if (_ignoreTags.Contains(tag)) EatInnerContent(tag); } else if (Char.IsWhiteSpace(Peek())) { // Whitespace (treat all as space) _text.Write(_text.Preformatted ? Peek() : ' '); MoveAhead(); } else { // Other text _text.Write(Peek()); MoveAhead(); } } // Return result return HttpUtility.HtmlDecode(_text.ToString()); }
public static void LoadingFontFromStream() { // ExStart:LoadingFontFromStream // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); string fontFile = ""; // Load input PDF file Document doc = new Document( dataDir + "input.pdf"); // Create text builder object for first page of document TextBuilder textBuilder = new TextBuilder(doc.Pages[1]); // Create text fragment with sample string TextFragment textFragment = new TextFragment("Hello world"); if (fontFile != "") { // Load the TrueType font into stream object using (FileStream fontStream = File.OpenRead(fontFile)) { // Set the font name for text string textFragment.TextState.Font = FontRepository.OpenFont(fontStream, FontTypes.TTF); // Specify the position for Text Fragment textFragment.Position = new Position(10, 10); // Add the text to TextBuilder so that it can be placed over the PDF file textBuilder.AppendText(textFragment); } dataDir = dataDir + "LoadingFontFromStream_out.pdf"; // Save resulting PDF document. doc.Save(dataDir); } // ExEnd:LoadingFontFromStream Console.WriteLine("\nFont from stream loaded successfully.\nFile saved at " + dataDir); }
/// <summary> /// Converts the given HTML to plain text and returns the result. /// </summary> /// <param name="html">HTML to be converted</param> /// <returns>Resulting plain text</returns> public string Convert(string html) { // Initialize state variables _text = new TextBuilder(); _html = html; _pos = 0; var lastLink = string.Empty; // Process input while (!EndOfText) { if (Peek() == '<') { // HTML tag bool selfClosing; Dictionary<string, string> attributes; string tag = ParseTag(out selfClosing, out attributes); // Handle special tag cases if (tag == "body") { // Discard content before <body> _text.Clear(); } else if (tag == "/body") { // Discard content after </body> _pos = _html.Length; } else if (tag == "pre") { // Enter preformatted mode _text.Preformatted = true; EatWhitespaceToNextLine(); } else if (tag == "/pre") { // Exit preformatted mode _text.Preformatted = false; } else if (tag == "a") { // Store link mode if (attributes.ContainsKey("href")) { lastLink = attributes["href"]; } } else if (tag == "/a") { // Write link if (!string.IsNullOrWhiteSpace(lastLink)) { _text.Write(string.Format(" ({0})", lastLink)); lastLink = string.Empty; } } string value; if (_tags.TryGetValue(tag, out value)) _text.Write(value); if (_ignoreTags.Contains(tag)) EatInnerContent(tag); } else if (Char.IsWhiteSpace(Peek())) { // Whitespace (treat all as space) _text.Write(_text.Preformatted ? Peek() : ' '); MoveAhead(); } else { // Other text _text.Write(Peek()); MoveAhead(); } } // Return result return HttpUtility.HtmlDecode(_text.ToString()); }
public override void InsertAndDeleteParagraphBreak() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); tb.SelectNode(para0, 1); XmlNode newParaNodeAfterInsert = tb.InsertParagraphBreak(para0, tb.SelectedNode); m_rtp.AddResultingAnnotationState(newParaNodeAfterInsert); tb.DeleteParagraphBreak(para0); tb.SelectNode(para0, 1); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.InsertAndDeleteParagraphBreak(); }
public override void MoveLatterDuplicateWordformToFormerOffset() { StTxtPara para0 = m_text1.ContentsOA.ParagraphsOS[0] as StTxtPara; m_rtp.TextBuilder.SelectNode(para0); TextBuilder tb = new TextBuilder(m_rtp.TextBuilder); ParagraphBuilder pb = tb.GetParagraphBuilder(para0.Hvo); // remove segment boundary pb.DeleteSegmentBreak(0, 3); // delete first "xxxnihimbilira" from first sentence pb.RemoveSegmentForm(0, 2); XmlNode paraNodeAfterEdit = tb.SelectedNode; m_rtp.AddResultingAnnotationState(paraNodeAfterEdit); base.MoveLatterDuplicateWordformToFormerOffset(); }
internal TextBuilder(TextBuilder tbToClone) : this(tbToClone.m_cache) { m_text = tbToClone.m_text; this.SelectedNode = ParagraphBuilder.Snapshot(tbToClone.SelectedNode); }