This is a code I wrote to find all URL within a PDF file and replace the one that matches the ID that I passed as a parameter.
It works as intended, but as I am a beginner on Java, I am sure there are some best practices that I am not following.
I am using the PDFBox library.
Here's the code:
Main.java
public class Main {
public static void main(String[] args) {
if (args.length < 4) {
System.err.println("Parameter missing from PHP");
} else {
Helper.getURL(args[0], args[1], args[2], args[3]);
}
}
}
Helper.java
public class Helper {
public static void getURL(String oldreportid, String newreportid, String oldpdf, String newpdf) {
PDDocument doc = null;
try {
doc = PDDocument.load(oldpdf);
List allPages = doc.getDocumentCatalog().getAllPages();
for (int i = 0; i < allPages.size(); i++) {
PDPage page = (PDPage) allPages.get(i);
List annotations = page.getAnnotations();
for (int j = 0; j < annotations.size(); j++) {
PDAnnotation annot = (PDAnnotation) annotations.get(j);
if (annot instanceof PDAnnotationLink) {
PDAnnotationLink link = (PDAnnotationLink) annot;
PDAction action = link.getAction();
if (action instanceof PDActionURI) {
PDActionURI uri = (PDActionURI) action;
String oldURL = uri.getURI();
String reportID = oldURL.substring(oldURL.lastIndexOf("=") + 1, oldURL.length());
if (oldreportid.equals(reportID)) {
String newURI = "http://www.test.com/test.php?T=MQ==&F=" + newreportid;
System.out.println("Page " + (i + 1) + ": Replacing " + oldURL + " with " + newURI);
uri.setURI(newURI);
}
}
}
}
}
doc.save(newpdf);
} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
} finally {
if (doc != null) {
try {
doc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}