Retain Text position alignment while replacing Text in PDF

Hi,
We are tying to replace the text in PDFA file. Th PDFA file consists complicated tables and drawing with all keywords that we are interested to replace.
After replace the keyoword the output PDFA file changed text posiiton alignment.

Please check the attached input and output pdf.
Version of Aspose PDF API for JAVA is 17.9

output.pdf (184.0 KB)
input.pdf (192.2 KB)

@sarvanan.murthi.ext

Thank you for contacting support.

We would like to request you to share a narrowed down sample application reproducing this issue so that we may try to reproduce and investigate it on our end. Before sharing requested data, please ensure using Aspose.PDF for Java 18.3 in your environment.

Hello Aspose Team,

Please check the attached file of JAVA code which we are using to replace keyword
Currently we have aspose.pdf-17.8.jar.

Do we need to take new aspose.pdf-18.3.jar and test our functionality.

CustomStamping.zip (4.5 KB)

@sarvanan.murthi.ext

Would you please share a narrowed down working sample project along with all necessary files to reproduce this issue because few variables including strKeyFile, strValueFile, strWrapNeded etc. are not set properly. Please share requested data with us so that we may reproduce it and proceed to help you out.

Kindly test it with Aspose.PDF for Java 18.3 because support is provided based on latest available version.

Hello Aspose Team,

Please check the below command which we used to covert into PDFA and replace keywords.
command : java com.siemens.plm2020.customstamping.CustomStamping -i “%~dp5\temp-conv%%~xa” -o “%~dp6\temp-conv%%~xa” -k %~dp0\KeyWordsCustomStamping.txt -v %~dp6\StampResult_%2.txt -p true -wrap false -defaultFont “Arial”

Required attached file :
files.zip (594 Bytes)

We also had same issue with Aspose.PDF for Java 18.3.
check the attached image.
output.PNG (77.9 KB)

@sarvanan.murthi.ext

Thank you for sharing requested data.

We have worked with the data shared by you and have been able to reproduce the issue in our environment. However, the generated file is not a PDF/A compliant file but contains reported problem PDF_18.3.pdf. A ticket with ID PDFJAVA-37650 has been logged in our issue management system for further investigation and resolution. The issue ID has been linked with this thread so that you will receive notification as soon as the issue is resolved.

We are sorry for the inconvenience.

Hello Aspose Team,

is there any update on this issue?
Please try to resolve as soon as possible. It is impacting our work too much.
It will be grateful if we could get solution as soon as possible.

@sarvanan.murthi.ext

The issue reported by you, PDFJAVA-37650, has been logged in our issue management system a couple of days ago. It is pending owing to previously logged issues, and will be scheduled on its due turn that can take several months. We apprentice your patience and comprehension in this regard.

However, we also offer Paid Support, where issues are used to be investigated with higher priority. Our customers, who have paid support subscription, report their issue there which are meant to be investigated urgently. In case your reported issue is a blocker, you may please consider subscribing for Paid Support. For further information, please visit Paid Support FAQ.

Hello Aspose Team,

is there any update on this issue?
It will be grateful if we could get solution as soon as possible.

@sarvanan.murthi.ext

Thank you for getting back to us.

We are afraid that the logged ticket is still pending for investigations owing to previously logged issues. We will let you know as soon as some significant progress is made in this regard.

Hello Aspose,

It is showing status as Resolved of this issue.
How we will get the latest aspose jar for that issue.
Please give us update on it.

@sarvanan.murthi.ext

Thank you for getting back to us.

We are pleased to update you that logged ticket PDFJAVA-37650 has been resolved for Aspose.PDF for Java 18.7 which will tentatively be released by the end of July or start of August 2018. We will update and notify you here in this thread, as soon as the product will be released. Please be patient and spare us little time.

Hello Aspose,

Is there any update on Product Release for PDFJAVA-37650?
Please give us update on it.

@sarvanan.murthi.ext

Thank you for getting back to us.

We would like to update you that PDFJAVA-37650 has been resolved in Aspose.PDF for Java 18.7 and below are our findings for your kind reference.

When we change font on the TextFragment level the algorithm is taking into account font style, metrics, size, margins and other text fragments on the page.It can prevent to changing position and wrapping because this is complex element and can inter-operate with other objects and parameters. To keep all the places when just changing the font we should change font on the TextSegment level. We can get all TextSegments from the TextFragment using the following line:

textFragment.getSegments()

We have modified your code a little and following code snippet works fine with latest version of the API:

package asposeforum;



import static asposeforum.AsposeForum.readFileContents;
import com.aspose.pdf.Color;
import com.aspose.pdf.Document;
import com.aspose.pdf.FileEncoding;
import com.aspose.pdf.FileSpecification;
import com.aspose.pdf.Font;
import com.aspose.pdf.FontRepository;
import com.aspose.pdf.FontSource;
import com.aspose.pdf.HorizontalAlignment;
import com.aspose.pdf.LoadOptions;
import com.aspose.pdf.Page;
import com.aspose.pdf.PageCollection;
import com.aspose.pdf.TabStops;
import com.aspose.pdf.TextAbsorber;
import com.aspose.pdf.TextFormattingOptions;
import com.aspose.pdf.TextFragment;
import com.aspose.pdf.TextFragmentAbsorber;
import com.aspose.pdf.TextFragmentCollection;
import com.aspose.pdf.TextReplaceOptions;
import com.aspose.pdf.TextSearchOptions;
import com.aspose.pdf.TextStamp;
import com.aspose.pdf.VerticalAlignment;
import com.aspose.pdf.facades.PdfContentEditor;
import com.aspose.pdf.text.FontSourceCollection;
import static com.sun.org.apache.bcel.internal.classfile.Utility.replace;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import sun.net.dns.ResolverConfiguration.Options;

public class CustomStamping {

	public static Document pdfInputDocument;

public CustomStamping() 
{
}
/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

	System.out.println("Execution Details");
	System.out.println("*****************");
	System.out.println("USER::"+System.getProperty("user.name"));
	try {
		java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
		System.out.println("HOSTNAME::" + localMachine.getHostName());
	} catch (UnknownHostException e1) {
		e1.printStackTrace();
	}
	System.out.println("START TIME::"+new Date());
	System.out.println("");
//		try 
	{
//			cmd = parser.parse(options, args);
	}
//		catch (ParseException e)
	{
//			System.out.println("Error:: "+e.getMessage());
//			formatter.printHelp("Custom Stamping", options);
//			System.exit(1);
//			return;
	}
//		System.out.println("Arguments");
//		System.out.println("*********");
//		for(Option option : cmd.getOptions()) {
//			System.out.println("\t"+option.getOpt()+"["+option.getDescription()+"] is "+option.getValue());
//		}
	System.out.println("****************");
	System.out.println("End of Arguments");
	System.out.println("");

	System.out.println("Setting License");
	System.out.println("***************");
	boolean isLicensed=initializeAspose();
	if(isLicensed)
	{
		System.out.println("\t"+"Succesfully Set License");
	}
	else
	{
		System.out.println("\t"+"Error:: Setting License");
	}
	System.out.println("End of Setting License");
	System.out.println("**********************");
	System.out.println("");

	String strInputPath = "D:\\input_retain.pdf";// cmd.getOptionValue("i");
	String strOutputPath = "D:\\Aspose.PDF_18.3.pdf";//cmd.getOptionValue("o");
	String strKeyFile = "D:\\KeyWordsCustomStamping.txt";// cmd.getOptionValue("k");
	String strValueFile = "D:\\StampResult_xrepd51ho6iujA.txt";// cmd.getOptionValue("v");
	String strIsPreviewFile = "true";// cmd.getOptionValue("p");
	String strWrapNeded= "false";//cmd.getOptionValue("wrap");
	String strDefaultFont= "Arial";//cmd.getOptionValue("defaultFont");
	File fileOutputPath = new File(strOutputPath);
	File fileInputPath = new File(strInputPath);
	if (!fileInputPath.exists())
	{
		System.out.println("Error:: "+ "File ["+fileInputPath+"] not found");
		return;
	}
	File fileKeyFile = new File(strKeyFile);
	if (!fileKeyFile.exists())
	{
		System.out.println("Error:: "+ "File ["+fileKeyFile+"] not found");
		return;
	}
	File fileValueFile = new File(strValueFile);
	if (!fileValueFile.exists())
	{
		System.out.println("Error:: "+ "File ["+fileValueFile+"] not found");
		return;
	}

	pdfInputDocument = new Document(strInputPath);
	ArrayList<String> keyFileContents = readFileContents(strKeyFile, "::");
	ArrayList<String> valueFileContents = readFileContents(strValueFile, "::");
	Map<String, String> mKeys = new HashMap<String, String>();
	Map<String, String> mValues = new HashMap<String, String>();
	System.out.println("Reading Key File Contents");
	System.out.println("*************************");
	for (String string : keyFileContents)
	{
		System.out.println("Input Line ::"+string);
		String[] splittedStrings = string.split(" ", -1);
		if(splittedStrings.length==2)
		{
			mKeys.put(splittedStrings[0], splittedStrings[1].replaceAll("^\"|\"$", ""));
			System.out.println("\tKey="+splittedStrings[0]+" Value="+splittedStrings[1].replaceAll("^\"|\"$", ""));
		}
	}
	System.out.println("********************************");
	System.out.println("End of Reading Key File Contents");
	System.out.println("");
	System.out.println("Reading Value File Contents");
	System.out.println("***************************");
	for (String string : valueFileContents)
	{
		System.out.println("Input Line ::"+string);
		String[] splittedStrings = string.split(" ", -1);
		if(splittedStrings.length==2)
		{
			mValues.put(splittedStrings[0].replaceAll("^\"|\"$", ""), splittedStrings[1].replaceAll("^\"|\"$", ""));
			System.out.println("\tKey="+splittedStrings[0].replaceAll("^\"|\"$", "")+" Value="+splittedStrings[1].replaceAll("^\"|\"$", ""));
		}
		if(splittedStrings.length>2)
		{
			String temp="";
			for (int i1=1; i1<splittedStrings.length; i1++)
			{
				temp += splittedStrings[i1];
				temp += " ";
			}
			temp=temp.trim();
			mValues.put(splittedStrings[0].replaceAll("^\"|\"$", ""), temp.replaceAll("^\"|\"$", ""));
			System.out.println("\tKey="+splittedStrings[0].replaceAll("^\"|\"$", "")+" Value="+temp.replaceAll("^\"|\"$", ""));
		}
	}
	System.out.println("******************************");
	System.out.println("End of Value Key File Contents");
	System.out.println("");		
	System.out.println("Starting to Replace Fonts in PDF File");
	System.out.println("***********************************");

	/****************************Font Reset**************************************/		
	TextFragmentAbsorber absorberFontChanger = new TextFragmentAbsorber(new com.aspose.pdf.TextEditOptions(com.aspose.pdf.TextEditOptions.FontReplace.RemoveUnusedFonts));
	pdfInputDocument.getPages().accept(absorberFontChanger);
	TextFragmentCollection textFragmentCollection2 = absorberFontChanger.getTextFragments();
	for (Iterator<TextFragment> iterator = textFragmentCollection2.iterator(); iterator.hasNext();)
	{
		TextFragment textFragment = iterator.next();
		String textFont=textFragment.getTextState().getFont().getFontName();
		System.out.println("Text:: "+textFragment.getText()+" Font::"+textFont);
		Font fontRepo = null;
		try {
			fontRepo = FontRepository.findFont(textFont);
		} catch (Exception e) {
			
		}
		if(fontRepo!=null)
		{
			System.out.println("\t"+"Replacing with System Font ::"+textFont);
//                textFragment.getTextState().setFont(fontRepo);
            for (Iterator<TextSegment> iterator_s = textFragment.getSegments().iterator(); iterator_s.hasNext(); )
            {
                TextSegment textSegment = iterator_s.next();
                textSegment.getTextState().setFont(fontRepo);
		}
		}else{
			
			System.out.println("\t"+"Info:: Font Not Found in system ::"+textFont);
			System.out.println("\t"+"Info:: Replacing with default font ::"+strDefaultFont);				
			Font fontRepo1 = null;
			try {
				fontRepo1 = FontRepository.findFont(strDefaultFont);
			} catch (Exception e) {
				
			}
			if(fontRepo1!=null)
			{
				System.out.println("\t"+"Replacing with Default Font ::"+strDefaultFont);

//                    textFragment.getTextState().setFont(fontRepo1);
                for (Iterator<TextSegment> iterator_s = textFragment.getSegments().iterator(); iterator_s.hasNext(); )
                {
                    TextSegment textSegment = iterator_s.next();
                    textSegment.getTextState().setFont(fontRepo1);
                }
            } else
            {
				System.out.println("\t"+"Info:: Default Font Not Found in system ::"+strDefaultFont);
				System.out.println("\t"+"Info:: Replacing with System default font ::Arial");				
				Font fontRepo2 = null;
				try {
					fontRepo2 = FontRepository.findFont("Arial");
				} catch (Exception e) {
					
				}
				if(fontRepo2!=null)
				{
					System.out.println("\t"+"Replacing with System Default Font ::Arial");
//                        textFragment.getTextState().setFont(fontRepo2);
                    for (Iterator<TextSegment> iterator_s = textFragment.getSegments().iterator(); iterator_s.hasNext(); )
                    {
                        TextSegment textSegment = iterator_s.next();
                        textSegment.getTextState().setFont(fontRepo2);
                    }

                } else
                {
					System.out.println("\t"+"Error:: Default System Font[Arial] Not Found in system");
				}
			}
		}
	}
	/******************************************************************/
	System.out.println("******************************");
	System.out.println("End of Replace Fonts in PDF File");
	System.out.println("");		
	System.out.println("Starting to Replace key in PDF File");
	System.out.println("***********************************");
	for (Entry<String, String> keyEntry : mKeys.entrySet()) 
	{
		String strKey=keyEntry.getKey();
		String strValue="";
		if(mValues.containsKey(keyEntry.getValue()))
		{
			strValue=mValues.get(keyEntry.getValue());
		}
		//System.out.println("Replacing key "+strKey+" with value "+strValue);
		replace( strKey, strValue,strWrapNeded);
	}
	System.out.println("******************************");
	System.out.println("End of Replace key in PDF File");
	System.out.println("");
//		if(strIsPreviewFile.equalsIgnoreCase("true"))
	{
		System.out.println("Adding Preview stamp, since p is set to true");
//			stampPreiew();
	}
//		else
	{
		System.out.println("No Preview stamp is added, since p is set to false");
	}
	System.out.println("");		
	try {
		System.out.println("Trying to save File to "+strOutputPath);
		pdfInputDocument.setEmbedStandardFonts(true);
		pdfInputDocument.save(strOutputPath);
		System.out.println("Saved File to "+strOutputPath);			
	} catch (Exception e) {
		System.out.println("Error saving File to "+strOutputPath);
		System.out.println("Error:: "+e.getMessage());
		e.printStackTrace();
	}
	System.out.println("");
	System.out.println("END TIME::"+new Date());
	System.out.println("Completed!!!");
}
private static boolean initializeAspose()
{

//		String strAsposeLicense=System.getenv("ASPOSE_LICENSE");
//		if(strAsposeLicense==null || strAsposeLicense.isEmpty())
	{
//			System.out.println("\t"+"Error:: Unable to find System Variable \"ASPOSE_LICENSE\" or the value is empty");			
//			return false;
//		}else
	{
		com.aspose.pdf.License license = new com.aspose.pdf.License();
		try 
		{
			//license.setLicense(new java.io.FileInputStream("D:\\Aspose.Total.Java.lic"));
			license.setLicense("D:\\Aspose.Total.Java.lic");
			
			if (com.aspose.pdf.Document.isLicensed())
			{
				System.out.println("License is Set!");
				return true;
			}else{
				return false;
			}
			
			
		} catch (Exception e)
		{
			//e.printStackTrace();
			System.out.println("\t"+"Error:: "+e.getMessage());
			System.out.println("\t"+"Error:: Unable to set License from System Variable\"ASPOSE_LICENSE\"");
			return false;
		}		
	}


}}

We hope this will be helpful. Please feel free to contact us if you need any further assistance.

August 8, 2018 3:59 PM
Hi Farhan,

We still see that the issue is not completely sorted…

Please find attached the PDFs for the issue. Marked in yellow over the PDF is the problem now.

We have used the latest version of Aspose PDF For JAVA & code is also updated as you suggested…

Aspose.zip (404.2 KB)

Thanks,
Saravanan

@sarvanan.murthi.ext

We have worked with recent files shared by you but we have not been able to reproduce the issue in our environment. We have different key and value files for previous PDF file, which are not reproducing a PDF file as the output file shared by you. Would you please share respective resources, so that we may reproduce and then log a separate ticket to help you out.

August 9, 2018 10:03 AM
Hi Farhan,

Issue with Font:

There is no issue with alignment now in Issue_2_Output.pdf that I have shared. But if you check the text highlighted in yellow, in the original document Issue_2_Input.pdf it was in Helvetica-Narrow-Type1-WinAnsiEncoding font setting.

But Issue_2_Output.pdf if you check it is in Helvetica-Narrow-Type1 (CID) -Identity-H font setting.

Due to this change in font, the text looks little bigger and gets out of the boundary.

Please find attached the key value file that we used.Key_Value_Files.zip (1.0 KB)

Issue with Aligngment:

If you check the file Issue_1_Output.pdf, to the bottom right I have highlighted the text in yellow. You can clearly see that “en” is moved from Language cell to revision cell and “1/1” is moved from Sheet cell to Language cell.

I could replicate both of the issue with latest jar from Aspose & update code as you suggested.

Thanks,
Saravanan

@sarvanan.murthi.ext

Thank you for elaborating it further.

We would like to update you that, another ticket with ID PDFJAVA-37917 has been logged in our issue management system for further investigation and resolution. The issue ID has been linked with this thread so that you will receive notification as soon as the issue is resolved.

We are sorry for the inconvenience.

Hello Aspose,

Is there any update on this Aligngment issue (PDFJAVA-37917)?
It will be grateful if we could get solution as soon as possible.

Thanks,
Vivek

@vsgardi

Thank you for contacting support.

About PDFJAVA-37917, the reason of such behavior is that text fragments with keywords contain some other text and for replacing only the keywords without related text so we should set TextReplaceOptions.ReplaceAdjustment.None in the method replace:

TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(strKey);
//Add the following lines:
TextReplaceOptions objTextReplaceOptions = new TextReplaceOptions();
objTextReplaceOptions.setReplaceAdjustmentAction(TextReplaceOptions.ReplaceAdjustment.None);
textFragmentAbsorber.setTextReplaceOptions(objTextReplaceOptions);

Complete code:

    static String myDir = "E:/LocalTesting/";
public static void main(String[] args) throws Exception
    {

        License licPdf = new License();
        licPdf.setLicense("License\\Aspose.PDF.Java.lic");

        String dataDir = myDir;

        String issueName = "Issue_2_Input";//"Issue_1_Input";
        String strInputPath = dataDir + issueName+".pdf";
        String strOutputPath = dataDir + issueName+"_Output" + version + " (2).pdf";
        String strKeyFile = dataDir + "KeyWordsCustomStamping.txt";
        String strValueFile = dataDir + "StampResult.txt";//_CustomStamping
        String strIsPreviewFile = dataDir + "true";
        File fileOutputPath = new File(strOutputPath);

        pdfInputDocument = new Document(strInputPath);
        ArrayList<String> keyFileContents = readFileContents(strKeyFile, "::");
        ArrayList<String> valueFileContents = readFileContents(strValueFile, "::");
        Map<String, String> mKeys = new HashMap<String, String>();
        Map<String, String> mValues = new HashMap<String, String>();
        INFO("Reading Key File Contents");
        INFO("*************************");
        for (String string : keyFileContents)
        {
            INFO("Input Line ::" + string);
            String[] splittedStrings = string.split(" ", -1);
            if (splittedStrings.length == 2)
            {
                mKeys.put(splittedStrings[0], splittedStrings[1].replaceAll("^\"|\"$", ""));
                INFO("\tKey=" + splittedStrings[0] + " Value=" + splittedStrings[1].replaceAll("^\"|\"$", ""));
            }
        }
        INFO("********************************");
        INFO("End of Reading Key File Contents");
        INFO("");
        INFO("Reading Value File Contents");
        INFO("***************************");
        for (String string : valueFileContents)
        {
            INFO("Input Line ::" + string);
            String[] splittedStrings = string.split(" ", -1);
            if (splittedStrings.length == 2)
            {
                mValues.put(splittedStrings[0].replaceAll("^\"|\"$", ""), splittedStrings[1].replaceAll("^\"|\"$", ""));
                INFO("\tKey=" + splittedStrings[0].replaceAll("^\"|\"$", "") + " Value=" + splittedStrings[1].replaceAll("^\"|\"$", ""));
            }
            if (splittedStrings.length > 2)
            {
                String temp = "";
                for (int i1 = 1; i1 < splittedStrings.length; i1++)
                {
                    temp += splittedStrings[i1];
                    temp += " ";
                }
                temp = temp.trim();
                mValues.put(splittedStrings[0].replaceAll("^\"|\"$", ""), temp.replaceAll("^\"|\"$", ""));
                INFO("\tKey=" + splittedStrings[0].replaceAll("^\"|\"$", "") + " Value=" + temp.replaceAll("^\"|\"$", ""));
            }
        }
        INFO("******************************");
        INFO("End of Value Key File Contents");
        INFO("");
        INFO("Starting to Replace key in PDF File");
        INFO("***********************************");
        for (Entry<String, String> keyEntry : mKeys.entrySet())
        {
            String strKey = keyEntry.getKey();
            String strValue = "";
            if (mValues.containsKey(keyEntry.getValue()))
            {
                strValue = mValues.get(keyEntry.getValue());
            }
            //INFO("Replacing key "+strKey+" with value "+strValue);
            replace(strKey, strValue);//"#!based_on","T0001BHBG6743/001");//
//            pdfInputDocument.processParagraphs();//my
        }
        INFO("******************************");
        INFO("End of Replace key in PDF File");
        INFO("");
        if (strIsPreviewFile.equalsIgnoreCase("true"))
        {
            INFO("Adding Preview stamp, since p is set to true");
            stampPreiew();
        } else
        {
            INFO("No Preview stamp is added, since p is set to false");
        }
        INFO("");
        try
        {
            INFO("Trying to save File to " + strOutputPath);
            //pdfInputDocument.convert("file.log", PdfFormat.PDF_A_3B, ConvertErrorAction.Delete);
            pdfInputDocument.setEmbedStandardFonts(true);
            pdfInputDocument.save(strOutputPath);
            INFO("Saved File to " + strOutputPath);
        } catch (Exception e)
        {
            INFO("Error saving File to " + strOutputPath);
            INFO("Error:: " + e.getMessage());
            e.printStackTrace();
        }
        INFO("");
        INFO("END TIME::" + new Date());
        INFO("Completed!!!");
    }

    private static boolean initializeAspose()
    {

        String strAsposeLicense = System.getenv("ASPOSE_LICENSE");
        if (strAsposeLicense == null || strAsposeLicense.isEmpty())
        {
            INFO("\t" + "Error:: Unable to find System Variable \"ASPOSE_LICENSE\" or the value is empty");
            return false;
        } else
        {
            com.aspose.pdf.License license = new com.aspose.pdf.License();
            try
            {
                license.setLicense(new java.io.FileInputStream(strAsposeLicense));
                //license.setLicense("Aspose.Pdf.lic");
                return true;
            } catch (Exception e)
            {
                //e.printStackTrace();
                INFO("\t" + "Error:: " + e.getMessage());
                INFO("\t" + "Error:: Unable to set License from System Variable\"ASPOSE_LICENSE\"");
                return false;
            }
        }

    }

    private static void INFO(String string)
    {
        System.out.println(string);
    }

    public static void replace(String strKey, String strValue) throws IOException
    {
        INFO("Replacing key " + strKey + " with value " + strValue);
        INFO("{\"" + strKey + "\",\"" + strValue+"\"},");

        TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(strKey);

        TextReplaceOptions objTextReplaceOptions = new TextReplaceOptions();
        objTextReplaceOptions.setReplaceAdjustmentAction(TextReplaceOptions.ReplaceAdjustment
                .None);
        textFragmentAbsorber.setTextReplaceOptions(objTextReplaceOptions);

        TextReplaceOptions textReplaceOptions = textFragmentAbsorber.getTextReplaceOptions();

        textFragmentAbsorber.setTextReplaceOptions(textReplaceOptions);

        pdfInputDocument.getPages().accept(textFragmentAbsorber);

        TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments();
        if (textFragmentCollection.size() > 0)
        {
            int i = 1;
            for (TextFragment textFragment : textFragmentCollection)
            {
                if (textFragment != null)
                {
                    INFO("\tReplacing Occurence " + i + " in Page " + textFragment.getPage().getNumber());
                    try
                    {
                        textFragment.setText(strValue);
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                        INFO("\t" + "Error:: " + e.getLocalizedMessage());
                    }
                    ++i;
                }
            }
        } else
        {
            INFO("\tNo Occurences found");
        }
    }

    public static void stampPreiew() throws UnsupportedEncodingException
    {
        String path = _CustomStamping.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String strJarPath = URLDecoder.decode(path, "UTF-8");

        String strStampFile = new File(strJarPath).getParent() + "/stamp.info";
        INFO("STAMP Information File::" + strStampFile);

        Map<String, String> mStampInformation = new HashMap<String, String>();

        File file = new File(strStampFile);
        if (!file.exists())
        {
            INFO("INFO:: " + "Stamp Information File [" + strStampFile + "] not found. Using Default Settings");
        } else
        {

            INFO("Reading Stamp Information File");
            INFO("******************************");
            ArrayList<String> mapping = readFileContents(strStampFile, "::");
            for (String string : mapping)
            {
                String[] splittedStrings = string.split("=", -1);

                if (splittedStrings.length == 2)
                {
                    mStampInformation.put(splittedStrings[0], splittedStrings[1]);
                    INFO("\tSTAMPINFO:: " + splittedStrings[0] + " " + splittedStrings[1]);
                }
            }
            INFO("*************************************");
            INFO("End of Reading Stamp Information File");
            INFO("");
        }

        TextStamp textStamp = null;

        if (mStampInformation.containsKey("stamp1.text"))
        {
            textStamp = new TextStamp(mStampInformation.get("stamp1.text"));
        } else
        {
            INFO("\tStamp Text information not found!! Using Preview as default");
            textStamp = new TextStamp("Preview");
        }

        if (mStampInformation.containsKey("stamp1.fontsize"))
        {
            try
            {
                textStamp.getTextState().setFontSize(Float.parseFloat(mStampInformation.get("stamp1.fontsize")));
            } catch (NumberFormatException e)
            {
                INFO("\tStamp Font Size not valid!! Using 100f as default");
                textStamp.getTextState().setFontSize(100f);
            }
        } else
        {
            INFO("\tStamp Font Size information not found!! Using 100f as default");
            textStamp.getTextState().setFontSize(100f);
        }

        if (mStampInformation.containsKey("stamp1.horizontalalign"))
        {
            try
            {
                textStamp.setHorizontalAlignment(Integer.parseInt(mStampInformation.get("stamp1.horizontalalign")));
            } catch (NumberFormatException e)
            {
                INFO("\tStamp Horizontal Alignment information not valid!! Using Center as default");
                textStamp.setHorizontalAlignment(HorizontalAlignment.Center);
            }
        } else
        {
            INFO("\tStamp Horizontal Alignment information not found!! Using Center as default");
            textStamp.setHorizontalAlignment(HorizontalAlignment.Center);
        }

        if (mStampInformation.containsKey("stamp1.verticalalign"))
        {
            try
            {
                textStamp.setVerticalAlignment(Integer.parseInt(mStampInformation.get("stamp1.verticalalign")));
            } catch (NumberFormatException e)
            {
                INFO("\tStamp Vertical Alignment information not valid!! Using Center as default");
                textStamp.setVerticalAlignment(VerticalAlignment.Center);
            }
        } else
        {
            INFO("\tStamp Vertical Alignment information not found!! Using Center as default");
            textStamp.setVerticalAlignment(VerticalAlignment.Center);
        }

        if (mStampInformation.containsKey("stamp1.textalign"))
        {
            try
            {
                textStamp.setTextAlignment(Integer.parseInt(mStampInformation.get("stamp1.textalign")));
            } catch (NumberFormatException e)
            {
                INFO("\tStamp Text Alignment information not valid!! Using Center as default");
                textStamp.setTextAlignment(HorizontalAlignment.Center);
            }
        } else
        {
            INFO("\tStamp Text Alignment information not found!! Using Center as default");
            textStamp.setTextAlignment(HorizontalAlignment.Center);
        }

        if (mStampInformation.containsKey("stamp1.rotateangle"))
        {
            try
            {
                textStamp.setRotateAngle(Double.parseDouble(mStampInformation.get("stamp1.rotateangle")));
            } catch (NumberFormatException e)
            {
                INFO("\tStamp Rotate information not valid!! Using 0 as default");
                textStamp.setRotateAngle(0);
            }
        } else
        {
            INFO("\tStamp Rotate information not found!! Using 0 as default");
            textStamp.setRotateAngle(0);
        }

        if (mStampInformation.containsKey("stamp1.fontstyle"))
        {
            try
            {
                textStamp.getTextState().setFontStyle(Integer.parseInt(mStampInformation.get("stamp1.fontstyle")));
            } catch (NumberFormatException e)
            {
                INFO("\tStamp Font Style information not valid!! Using Italic as default");
                textStamp.getTextState().setFontStyle(com.aspose.pdf.FontStyles.Italic);
            }
        } else
        {
            INFO("\tStamp Font Style information not found!! Using Italic as default");
            textStamp.getTextState().setFontStyle(com.aspose.pdf.FontStyles.Italic);
        }

        if (mStampInformation.containsKey("stamp1.font"))
        {
            try
            {
                textStamp.getTextState().setFont(FontRepository.findFont(mStampInformation.get("stamp1.font"), true));
            } catch (Exception e)
            {
                INFO("\tStamp Font not installed!! Using Arial as default");
                textStamp.getTextState().setFont(FontRepository.findFont("Arial", true));
            }
        } else
        {
            INFO("\tStamp Font information not found!! Using Arial as default");
            textStamp.getTextState().setFont(FontRepository.findFont("Arial", true));
        }

        textStamp.getTextState().setForegroundColor(Color.getLightGray());
        textStamp.setJustify(true);
        textStamp.setBackground(true);

        PageCollection pages = pdfInputDocument.getPages();
        for (Page page : pages)
        {
            page.addStamp(textStamp);
        }
    }

    public static ArrayList<String> readFileContents(String filePath, String strCommentIdentifier)
    {
        ArrayList<String> contents = new ArrayList<String>();
        String encoding = "UTF-8";//Normal
        FileInputStream fis = null;
        try
        {
            fis = new FileInputStream(filePath);
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        if (null != fis)
        {
            InputStreamReader isr = null;
            try
            {
                isr = new InputStreamReader(fis, encoding);
            } catch (UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }
            BufferedReader br = new BufferedReader(isr);
            String strLine = null;
            try
            {
                while ((strLine = br.readLine()) != null)
                {
                    if (!strLine.startsWith(strCommentIdentifier))
                    {
                        contents.add(strLine);
                    }
                }
                fis.close();
                br.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        contents.trimToSize();
        return contents;
    }

Please feel free to contact us if you need any further assistance.