Hi, I’m trying to use aspose pdf java 23.5 to make this function:
add header/footer to pdf, some specific text in the header/footer will have link.
I’m using below code but throws NPE when using regex way to search and update.
Could you help and provide any suggestion on it?
/////// function code start ///////
public static void fn1() {
Document pdfDocument = new Document(“input.pdf”);
TextStamp textStamp = new TextStamp("------ ${$Simple $Sample} ${Text Simple} ------");
textStamp.setBackground(true);
textStamp.setVerticalAlignment(VerticalAlignment.Bottom);
textStamp.setHorizontalAlignment(HorizontalAlignment.Center);
textStamp.getTextState().setFont(FontRepository.findFont("Arial"));
textStamp.getTextState().setFontSize(16.0F);
textStamp.getTextState().setForegroundColor(Color.getBlack());
for (Page page: pdfDocument.getPages()) {
page.addStamp(textStamp);
}
// 1. will throw NPE when update text searched with regex for ‘${abc}’ pattern
Pattern pat = Pattern.compile("\$\{[^}]*+}", Pattern.CASE_INSENSITIVE);
// 2. will throw NPE when update text searched with regex for ‘any of target words’ pattern
// Pattern pat = Pattern.compile("(Simple|Sample)", Pattern.CASE_INSENSITIVE);
TextFragmentAbsorber tfAbsorber = new TextFragmentAbsorber(pat);
tfAbsorber.getTextSearchOptions().setRegularExpressionUsed(true);
// 3. works with plain text
// TextFragmentAbsorber tfAbsorber = new TextFragmentAbsorber(“Simple”);
tfAbsorber.getTextSearchOptions().setLimitToPageBounds(true);
tfAbsorber.getTextSearchOptions().setRectangle(new Rectangle(0, 0, pdfDocument.getPageInfo().getWidth(), 72));
tfAbsorber.getTextReplaceOptions().setReplaceScope(TextReplaceOptions.Scope.REPLACE_ALL);
pdfDocument.getPages().accept(tfAbsorber);
for (TextFragment tf: tfAbsorber.getTextFragments()) {
// this line prints, meaning text has been found
System.out.println("Found: " + tf.getText());
// throws NPE if using regex
tf.setText("(Replaced)");
// throws NPE if using regex
tf.getTextState().setForegroundColor(Color.getBlue());
for (Page page: pdfDocument.getPages()) {
LinkAnnotation link = new LinkAnnotation(page, tf.getRectangle());
link.setAction(new GoToURIAction("www.google.com"));
page.getAnnotations().add(link);
}
}
pdfDocument.save("output.pdf");
}
/////// function code end ///////