We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Environment.NewLine not working

Hi,

When I try and populate a pdf control and apply the Environment.NewLine it’s not adding the carriage return. For example, I want the textbox to include the following format

Sample Data
More Sample Data

I have the following
string testString = “Sample Data” + Environment.Newline + "More Sample Data"

My question:
How do I accomplish adding a carriage return so it drops to a new line? Thanks!
<span style=“font-size: 12pt; font-family: “Times New Roman”,“serif”;”>

Hi,

Thanks for using our products.

In case you need to add new line character when creating a new PDF document, please try using #$NL instead of Environment.Newline. For more information, please visit Replaceable Symbols

In case it does not satisfy your requirements or you have any further query, please feel free to contact. We apologize for your inconvenience.

I’m trying to populate a pdf template. I’m expecting the string fieldValue to display two lines in the pdf document. When I add the “#$NL” it’s getting rendered in the pdf document - no new line is occuring. Should I be using different steps to accomplish this?

String fieldValue = “This is on first line #$NL this on the second line”;
Document pdfDocument = new Document(path);
Form pdfForm = pdfDocument.Form;
TextBoxField field = pdfForm[fieldName] as TextBoxField;
field.Value = fieldValue;
pdfDocument.Flatten();


Dear All,

I just wanted to confirm on adding newline in PDF. I tried with #$NL, but it yeilded no result. Please share me if you have found any work-around for this.

Thanks,

Kumaresh

Hi,

Thanks for your using our products.

In order to insert multiline text, first the field property should be set to accept multiline information. In case you need to place a TextField which can accept multiline information, please try using the following code snippet.

[C#]

//open document
Document pdfDocument = new Document("d:/pdftest/source_updated.pdf");
// create a rectangle object to define the region of text field
Aspose.Pdf.Rectangle rect = new Aspose.Pdf.Rectangle(100, 200, 300,300);
//create a field
TextBoxField textBoxField = new TextBoxField(pdfDocument.Pages[1],rect);
// specify the namde of form field
textBoxField.Name = "textbox1";
// specify that text field will be multiline
textBoxField.Multiline = true;
// text value to be placed inside text field
textBoxField.Value = "Text Box \n new line data";
//add field to the document
pdfDocument.Form.Add(textBoxField, 1);
//save modified PDF
pdfDocument.Save("d:/pdftest/MultiLine_FormFields_output.pdf");

In case you need to insert multiline string inside an TextField already present in a PDF form, please try using the following code line to accomplish your requirement.

[C#]

//modify field value
textBoxField.Value = "First line \n Second line";

In case you still face any problem or you have any further query, please feel free to contact. We apologize for your inconvenience.

I’m passing a dictionary of text values to replace in my document where there is an existing single large multiline text box that contains the data points to update.
Code:
TextFragmentAbsorber tfa = new TextFragmentAbsorber(kvp.Key.ToString());
document.Pages.Accept(tfa);
foreach (TextFragment tf in tfa.TextFragments)
{
if (kvp.Value.ToList().Count > 1)
{
foreach (string s in kvp.Value.ToList())
sb.Append(s + “\n”);
tf.Text = sb.ToString();
}
else
tf.Text = kvp.Value[0].ToString();

My dictionary value contains a list of “Mary Smith” and “John Smith”. In variations of trying to get them to be multilined, I’ve only been able to produce the output of “Mary SmithJohn Smith” and “Mary Smith\nJohn Smith\n”

@rbp2

Can you please share sample PDF document along with the text value which you want to replace? We will test the scenario in our environment and address it accordingly.

I’ve since modified the code to utilize TextParagraph, which is working, however, I have a different issue with that - it’s not placing the paragraph in the same location. So, if there are three lines, it’s in the correct location, but if there are 5 lines, everything shifts up.
New Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aspose.Pdf;
using Aspose.Pdf.Facades;
using Aspose.Pdf.Text;
namespace PDF_test
{
public class CreateDocument
{
public static Dictionary<string, List> docData = new Dictionary<string, List>();
private static StringBuilder sb = new StringBuilder();
private static Document document = new Document();
public static string dir = @“C:”;
public static void Main(string[] args)
{
try
{
docData.Add("[Risks]", new List { “Risk 1”, “Risk 2”, “Risk 3”, “Risk 4”, “Risk 5” });
docData.Add("[Conditions]", new List { “Condition 1”, “Condition 2”, “Condition 3”, “Condition 4”, “Condition 5” });
var cd = CreateDocument.pdfDocument(docData);
cd.Save(dir + isQuote.ToString() + “_output.pdf”);
}
catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadKey(); }
}
public class CreateDocument
{
public static Document pdfDocument(Dictionary<string, List> docData, bool isQuote)
{
foreach (KeyValuePair<string, List> kvp in docData)
{
// other things happening
DoLists(kvp);

                    }
                    return document;
                }

                private static void DoLists(KeyValuePair<string, List<string>> kvp)
                {
                    TextFragmentAbsorber tfa = new TextFragmentAbsorber(kvp.Key.ToString());
                    TextFragment tf = new TextFragment();
                    TextState tState = new TextState()
                    {
                        FontSize = 9
                    };
                    tf.TextState.ApplyChangesFrom(tState);
                    tfa.TextReplaceOptions.Equals(kvp.Key.ToString());
                    document.Pages.Accept(tfa);
                    int pageno = 1;
                    double x = 0, y = 0, l = 1, b = 1, r = 1, t = 1;
                    foreach (TextFragment tFrag in tfa.TextFragments)
                    {
                        pageno = tFrag.Page.Number;
                        x = tFrag.Position.XIndent - 10;
                        y = tFrag.Position.YIndent;
                    }

                    string[] strings = new string[0];
                    foreach (string s in kvp.Value.ToList())
                    {
                        if (!strings.Contains(s))
                        {
                            Array.Resize(ref strings, strings.Length + 1);
                            strings[strings.Length - 1] = s;
                            sb.AppendLine("- " + s);

                        }

                        tf.Text = sb.ToString();
                        tfa.TextFragments.Add(tf);
                        TextParagraph par = new TextParagraph()
                        {
                            Position = new Position(x, y),
                            FirstLineIndent = 10,
                            SubsequentLinesIndent = 10,
                            Justify = false,
                            HorizontalAlignment = HorizontalAlignment.Left
                        };
                        par.FormattingOptions.WrapMode = TextFormattingOptions.WordWrapMode.ByWords;
                        tf.IsInLineParagraph = true;
                        par.AppendLine(tf);
                        par.TextRectangle.URY = y;
                        Page pg = document.Pages[pageno];
                        TextBuilder tBuild = new TextBuilder(pg);
                        tBuild.AppendParagraph(par);

                    }
                }
            }
        }
    }

not sure why only half of the code snippet is being treated as code snippet - sorry…
dummy_quote_support.pdf (97.9 KB)

@rbp2

We are afraid that we could not understand the issue correctly. Also, the code snippet that you shared is not generating the PDF similar to which you shared with us. Can you please share an expected output PDF along with a sample Console Application which we can use to replicate the issue and address it accordingly?

I’ve been able to correct the issue. Anyone else that stumbles across this…

  • Original Issue: Using TextFragment (via TextFragmentAbsorber to replace specific text) does not produce line breaks using Environment.Newline, \n or \r\n. (i.e.:

    "This is one line." + Environment.NewLine + "This is the second line."
    Will output: “This is one line.This is the second line.” instead of:
    This is one line.
    This is the second line.

  • Original Resolution: Use TextParagraph to include the TextFragment, will present the line breaks. :+1:

  • Resolution Issue: Using TextParagraph to place the text at a specific location on the document, if the paragraph (i.e. text being passed into the paragraph) changes, the location of the paragraph placement shifts even though the location of the TextFragmentAbsorber object (the text being replaced) does not change its location on the page.

  • Resolution Issue Resolution :slight_smile: : Finding the location of the TextFragment that is being replaced can be utilized in placing the TextParagraph in the appropriate location. (in code snippet; setting value ‘y’ on line 19, used in conjunction with the paragraph position on line 43).

Code Snippet:

        ReplaceText() 
        {  
        Document document = new Document(@"C:\location\document.pdf")
        TextFragmentAbsorber tfa = new TextFragmentAbsorber(kvp.Key.ToString());
        TextFragment tf = new TextFragment();
        TextState tState = new TextState()
        {
            FontSize = 9
        };
        tf.TextState.ApplyChangesFrom(tState);
        tfa.TextReplaceOptions.Equals(kvp.Key.ToString());
        document.Pages.Accept(tfa);
        int pageno = 1;
        double x = 0, y = 0;
        foreach (TextFragment tFrag in tfa.TextFragments)
        {
            pageno = tFrag.Page.Number;
            x = tFrag.Position.XIndent;
            y = tFrag.Position.YIndent; //You'll use this for the paragraph location
        }
        string[] strings = new string[0];
        if (kvp.Key.ToString() != "YourTextToBeReplaced")
            foreach (string s in kvp.Value.ToList())    
                {
                if (!strings.Contains(s))
                    {
                    Array.Resize(ref strings, strings.Length + 1);
                    strings[strings.Length - 1] = s;
                    sb.AppendLine("- " + s);
                   }
               }
        tf.Text = sb.ToString();
        tfa.TextFragments.Add(tf);
        TextParagraph par = new TextParagraph()
        {    
            FirstLineIndent = 10,
            SubsequentLinesIndent = 10,
            HorizontalAlignment = HorizontalAlignment.Left
        };
        par.FormattingOptions.WrapMode = TextFormattingOptions.WordWrapMode.ByWords;
        tf.IsInLineParagraph = true;
        par.AppendLine(tf);
        par.Position = new Position(x, y - par.TextRectangle.Height);//Once the TextFragment is in the TextParagraph, it will change the Height so you can use with the TextFragment Y coordinate
        Page pg = document.Pages[pageno];
        TextBuilder tBuild = new TextBuilder(pg);
        tBuild.AppendParagraph(par);
    }

@rbp2

Thanks for sharing the solution for the issue you were facing. It is good to know that you were able to sort your issue out. Please keep using our API and feel free to create a new topic in case you face any issues.