Use of relative path for anchor method using iText

2019-02-20 03:36发布

问题:

I am using iText for PDF generation and I create an anchor using the following code:

String newPath = "file:///";
newPath = newPath + completePath;
trial.setAnchor(newPath);

The trial object is of type Chunk and completePath is the path to the file I want a link to.

When I try to use a relative path, the link doesn't work. For instance "C:\Doc\folder1\trial.xml" works fine but when I try relative paths such as "..\trial1.xml" there is no link being formed, although both my PDF document and XML file are in the same folder named "folder1".

回答1:

If you have this situation:

C:\Doc\folder1\trial.xml
C:\Doc\folder1\my.pdf

And if you create a path "..\trial1.xml" as a reference in my.pdf, then you are telling the PDF that the xml file can be found here:

C:\Doc\trial1.xml

I see two errors:

  1. there's a difference between trial.xml and trial1.xml, and
  2. you are pointing at the wrong directory.

There may even be a third error if you are concatenating the relative path with "file:///". We should see the PDF to make sure what happens.

I've written an example named RelativeLink that creates a PDF with a Chunk that says "Click me". If you click that Chunk, the XML file data.xml that resides in the same direction as relative_link.pdf opens.

Chunk chunk = new Chunk("Click me");
chunk.setAnchor("./" + new File(XML).getName());
document.add(chunk);

This doesn't work in the context of a web plugin (for obvious reasons). To see this in action, you need to download the PDF file and open it in a standalone viewer.