Skip to main content
2 of 4
removed thanks as per Stack Exchange policy
200_success
  • 144.2k
  • 22
  • 188
  • 473

Read and replace URL From PDF File - JAVA

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:

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();
            }
        }
    }
}
}
Teio
  • 135
  • 8