@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.