Apache FOP: How to set base URL for accessing external resource using relative path

痞子三分冷 提交于 2020-01-02 21:59:35

问题


In my .xsl file I am using external graphics like this
<fo:external-graphic width="90pt" height="29pt" src="url(xsl/logo.jpg)"/>

But image is not getting loaded in the generated PDF and I get this error in console.
[ERROR] Error while creating area : Error with image URL: xsl\logo.jpg (The system cannotfind the path specified) and no base URL is specified

How do I solve this issue? I guess setting the base URL will do. But how to set the base URL? Please help.


回答1:


I got a solution from this link
http://groups.yahoo.com/group/XSL-FO/message/6116

set base dir using Java code

ServletContext servletContext = getServletConfig().getServletContext();

String appPath = servletContext.getRealPath(""); //root of web app
org.apache.fop.configuration.Configuration.put("baseDir",appPath);

This worked for me.
Please post if you know any better solution.




回答2:


I am using Apache FOP 1.1 Ver.

    fopFactory = FopFactory.newInstance();
    // for image base URL : images from Resource path of project
    String serverPath = request.getSession().getServletContext().getRealPath("/");
    fopFactory.setBaseURL(serverPath);
    // for fonts base URL :  .ttf from Resource path of project
    fopFactory.getFontManager().setFontBaseURL(serverPath);

I added all images and required font font files in resource director of my project. It is working fine for me. Thank you




回答3:


I had the same problem and this only works for me in the version 0.95 of fop. SetBaseUrl is ignored in version 1.0




回答4:


Solution for versions 1.0, 1.1 : In fop 1.0 and 1.1 method setBaseURL() does not work correctly with local files, so you can use method setURIResolveri and write your implementation of interface URIResolver.

1.Add in uses import javax.xml.transform.URIResolver;

2.Add in mainClass

 private static class LocalResolver implements URIResolver {
         private String BaseFolder; 
            @Override
            public Source resolve(String href, String base) throws TransformerException {
             File f = new File(BaseFolder + "\\" + href);
             if (f.exists())
             return new StreamSource(f);
                     else
                      throw new TransformerException("File " + f.getAbsolutePath() +" not found!");         
            }

         public LocalResolver(String BaseFolder) {
           this.BaseFolder = BaseFolder;   
         }

     }

Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

3.Add before call transformer.transform(src, res) this:

fop.getUserAgent().setURIResolver(new LocalResolver("C:\\Users\\photon\\Downloads\\fop-1.1-bin\\fop-1.1"));


来源:https://stackoverflow.com/questions/5416421/apache-fop-how-to-set-base-url-for-accessing-external-resource-using-relative-p

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