Use of relative path for anchor method using iText for pdf Generation

天涯浪子 提交于 2019-12-04 02:20:00

问题


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.



来源:https://stackoverflow.com/questions/27063677/use-of-relative-path-for-anchor-method-using-itext-for-pdf-generation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!