java 图像重定向到服务器

lsmd5eda  于 2023-09-29  发布在  Java
关注(0)|答案(2)|浏览(94)

我试图写一个嵌入式自定义的fop xml到pdf java应用程序使用自定义图像重定向内的fop
我在一个旧的xslt文件中有以下内容

<fo:block text-indent="1mm" padding-before="20mm">
        <xsl:variable name="barcode" select="concat('/prescriptions/', id, '/barcode.html')"/>
        <fo:external-graphic>
          <xsl:attribute name="src">
            <xsl:value-of select="$barcode" />
          </xsl:attribute>
        </fo:external-graphic>
      </fo:block>

我写了一个自定义ResourceResolver

package embedding;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.xmlgraphics.io.Resource;
import org.apache.xmlgraphics.io.ResourceResolver;
import java.io.BufferedInputStream;
import java.net.URI;
import java.net.URISyntaxException;

public class CustomResourceResolver implements ResourceResolver {
    String base;
    String session;
    String cookie;
    String user_id;
    String authorization;
    static final Logger logger = Logger.getLogger("fop-log");
    
    public String get_base(){
        return base;
    }
    
    public CustomResourceResolver(String _base, String _session, String _cookie, String _user_id, String _authorization){
        super();
            base = _base;
            session = _session;
            cookie = _cookie;
            user_id = _user_id;
            authorization = _authorization;
    }
    
    @Override
    public Resource getResource(URI uri) throws IOException {          
    HttpURLConnection urlConnection = null;
    try {
      String href = uri.getRawPath();

      if (!href.startsWith("/") && !base.endsWith("/")) {
          base = base + "/";
      }

      String new_uri;
      if (href.startsWith("http://") || href.startsWith("https://")) {
          new_uri = href;
      } else {
          new_uri = base + href;
      }
      
      uri = new URI(new_uri);
      logger.log(Level.INFO, "loading: ({0})", new_uri);
      URL url = uri.toURL();
      
      urlConnection = (HttpURLConnection) url.openConnection();
      if(session!= null){
          urlConnection.setRequestProperty("Cookie", cookie + "=" + session);
      }
      if(authorization != null){
          urlConnection.setRequestProperty("Fop-authorization", authorization );
      }
      if(user_id != null){
          urlConnection.setRequestProperty("Fop-user",user_id );
      }
      
      InputStream in = new BufferedInputStream(urlConnection.getInputStream());
      return new Resource(in);
      
    } catch (MalformedURLException e) {
        logger.log(Level.SEVERE, null, e);
        return null;
    } catch (IOException | URISyntaxException ioe) {
        logger.log(Level.SEVERE, null, ioe);
      return null;
    } finally {
      if (urlConnection != null) {
        urlConnection.disconnect();
      }
    }
    }

    @Override
    public OutputStream getOutputStream(URI uri) throws IOException {
        URL url = uri.toURL();
    return url.openConnection().getOutputStream();
    }
    
}

这个被称为

CustomResourceResolver resolver = new CustomResourceResolver(base, session, cookie, user_id, authorization);
FopFactoryBuilder builder = new FopFactoryBuilder(new File(".").toURI(), (ResourceResolver)resolver);
final FopFactory fopFactory = builder.build();
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

OutputStream out = new java.io.FileOutputStream(pdffile);
out = new java.io.BufferedOutputStream(out);
try {
       Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
                
        TransformerFactory factory = TransformerFactory.newInstance();
        URIResolver uiResolver = new CustomUriResolver(base, session, cookie, user_id, authorization);
        
        factory.setURIResolver(uiResolver);
        Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));

        // Set the value of a <param> in the stylesheet
        transformer.setParameter("versionParam", "2.0");

        // Setup input for XSLT transformation
        Source src = new StreamSource(xmlfile);

        // Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);
            } finally {
                out.close();
            }

java被打包在单个FopXml2Pdf.jar中,并从命令行调用,如下所示:
java -jar FopXml2Pdf.jar file.xml file.xsl file.config
但当我运行代码时

Sep 19, 2023 6:52:36 AM embedding.CustomResourceResolver getResource
INFO: loading: (http://localhost:3000/prescriptions/420/barcode.html)
Sep 19, 2023 6:52:36 AM org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext createImageSource
SEVERE: Unable to create ImageInputStream for InputStream from system identifier 'file:/media/sf_Clintel/careright/./' (stream is closed)
Sep 19, 2023 6:52:36 AM org.apache.fop.events.LoggingEventListener processEvent
SEVERE: Image not found. URI: /prescriptions/420/barcode.html. (No context info available)

我可以看到重定向是加载正确的网址获得正确的数据,但
new File(“.”).toURI()正在解析为文件:/media/sf_Clintel/careright/./
我应该将其设置为什么,以便它保存来自Resource getResource的数据?

0dxa2lsx

0dxa2lsx1#

我已经更改了customResourceResolver,以便它输出一个文件,然后我将该文件作为InputStream资源返回

package embedding;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.xmlgraphics.io.Resource;
import org.apache.xmlgraphics.io.ResourceResolver;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;

public class CustomResourceResolver implements ResourceResolver {
    String base;
    String session;
    String cookie;
    String user_id;
    String authorization;
    static final Logger logger = Logger.getLogger("fop-log");
    
    public String get_base(){
        return base;
    }
    
    public CustomResourceResolver(String _base, String _session, String _cookie, String _user_id, String _authorization){
        super();
            base = _base;
            session = _session;
            cookie = _cookie;
            user_id = _user_id;
            authorization = _authorization;
    }
    
    @Override
    public Resource getResource(URI uri) throws IOException {          
    HttpURLConnection urlConnection = null;
    try {
      String href = uri.getRawPath();

      if (!href.startsWith("/") && !base.endsWith("/")) {
          base = base + "/";
      }

      String new_uri;
      if (href.startsWith("http://") || href.startsWith("https://")) {
          new_uri = href;
      } else {
          new_uri = base + href;
      }
      
      uri = new URI(new_uri);
      logger.log(Level.INFO, "loading: ({0})", new_uri);
      URL url = uri.toURL();
      
      urlConnection = (HttpURLConnection) url.openConnection();
      if(session!= null){
          urlConnection.setRequestProperty("Cookie", cookie + "=" + session);
      }
      if(authorization != null){
          urlConnection.setRequestProperty("Fop-authorization", authorization );
      }
      if(user_id != null){
          urlConnection.setRequestProperty("Fop-user",user_id );
      }
      
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(timestamp);
    
    filename = new File(Paths.get(".").toAbsolutePath().normalize().toString() +"/tmp/loading_"+timeStamp+".data");

    byte[] buffer = new byte[8 * 1024];
      try {
        OutputStream output = new FileOutputStream(filename);
        try {
          int bytesRead;
          while ((bytesRead = in.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
          }
        } finally {
          output.close();
        }
      } finally {
        in.close();
      }
      logger.log(Level.INFO, "Adding file to cache {0} for {1}", new Object[]{filename, href});
      
      InputStream is = new BufferedInputStream(new FileInputStream(filename));
      encoding = URLConnection.guessContentTypeFromStream(is);     
     
     InputStream result = new FileInputStream(filename);
      //Resource res = new Resource(encoding,result);
      Resource res = new Resource(result);
      logger.log(Level.INFO, "returning stream to file {0} with mime_type {1}", new Object[]{filename, res.getType()});
      return res;
      
    } catch (MalformedURLException e) {
        logger.log(Level.SEVERE, null, e);
        return null;
    } catch (IOException | URISyntaxException ioe) {
        logger.log(Level.SEVERE, null, ioe);
      return null;
    } finally {
      if (urlConnection != null) {
        urlConnection.disconnect();
      }
    }
    }

    @Override
    public OutputStream getOutputStream(URI uri) throws IOException {
        URL url = uri.toURL();
    return url.openConnection().getOutputStream();
    }
    
}

但我现在

SEVERE: Image not available. URI: /prescriptions/423/barcode.html. Reason: org.apache.xmlgraphics.image.loader.ImageException: The file format is not supported. No ImagePreloader found for /prescriptions/423/barcode.html (No context info available)
org.apache.xmlgraphics.image.loader.ImageException: The file format is not supported. No ImagePreloader found for /prescriptions/423/barcode.html
    at org.apache.xmlgraphics.image.loader.ImageManager.preloadImage(ImageManager.java:181)
    at org.apache.xmlgraphics.image.loader.cache.ImageCache.needImageInfo(ImageCache.java:127)
    at org.apache.xmlgraphics.image.loader.ImageManager.getImageInfo(ImageManager.java:123)
    at org.apache.fop.fo.flow.ExternalGraphic.bind(ExternalGraphic.java:81)
    at org.apache.fop.fo.FObj.processNode(FObj.java:131)
    at org.apache.fop.fo.FOTreeBuilder$MainFOHandler.startElement(FOTreeBuilder.java:293)
    at org.apache.fop.fo.FOTreeBuilder.startElement(FOTreeBuilder.java:179)
    at org.apache.xml.serializer.ToXMLSAXHandler.closeStartTag(ToXMLSAXHandler.java:206)
    at org.apache.xml.serializer.ToSAXHandler.flushPending(ToSAXHandler.java:279)
    at org.apache.xml.serializer.ToXMLSAXHandler.endElement(ToXMLSAXHandler.java:245)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1401)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1376)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemIf.execute(ElemIf.java:162)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemTemplate.execute(ElemTemplate.java:394)
    at org.apache.xalan.templates.ElemCallTemplate.execute(ElemCallTemplate.java:248)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1376)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1376)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1376)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1376)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1376)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemTemplate.execute(ElemTemplate.java:394)
    at org.apache.xalan.templates.ElemCallTemplate.execute(ElemCallTemplate.java:248)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemChoose.execute(ElemChoose.java:141)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1376)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1376)
    at org.apache.xalan.templates.ElemApplyTemplates.transformSelectedNodes(ElemApplyTemplates.java:395)
    at org.apache.xalan.templates.ElemApplyTemplates.execute(ElemApplyTemplates.java:178)
    at org.apache.xalan.templates.ElemApplyTemplates.transformSelectedNodes(ElemApplyTemplates.java:395)
    at org.apache.xalan.templates.ElemApplyTemplates.execute(ElemApplyTemplates.java:178)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1376)
    at org.apache.xalan.transformer.TransformerImpl.executeChildTemplates(TransformerImpl.java:2402)
    at org.apache.xalan.transformer.TransformerImpl.applyTemplateToNode(TransformerImpl.java:2272)
    at org.apache.xalan.transformer.TransformerImpl.transformNode(TransformerImpl.java:1358)
    at org.apache.xalan.transformer.TransformerImpl.transform(TransformerImpl.java:711)
    at org.apache.xalan.transformer.TransformerImpl.transform(TransformerImpl.java:1275)
    at org.apache.xalan.transformer.TransformerImpl.transform(TransformerImpl.java:1253)
    at embedding.FopXml2Pdf.main(FopXml2Pdf.java:129)

文件已正确获取,但未嵌入到fop文档中
我已经退房了org.apache.xmlgraphics.image.loader.ImageException: The file format is not supported. No ImagePreloader found
但这行不通
我的jar的顺序是:Jar ordering
任何额外的帮助都是受欢迎的

kuhbmx9i

kuhbmx9i2#

问题已解决。使用ANT将Batik-all-1.14.jar Package 到单个脂肪罐中导致了该异常。将 Package 更改为使用MVN已修复此问题

<?xml version="1.0"?>
<project
  xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.clintel.java_fop</groupId>
  <artifactId>java_fop</artifactId>
  <version>develop</version>
  <name>java_fop</name>
  <url>http://maven.apache.org</url>
  <packaging>jar</packaging>
  <repositories>
    <repository>
      <id>Sonatype-public</id>
      <name>SnakeYAML repository</name>
      <url>https://oss.sonatype.org/content/groups/public/</url>
    </repository>
  </repositories>
  <dependencies>
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.0.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.github.jtidy/jtidy -->
    <dependency>
      <groupId>com.github.jtidy</groupId>
      <artifactId>jtidy</artifactId>
      <version>1.0.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/xalan/serializer -->
    <dependency>
      <groupId>xalan</groupId>
      <artifactId>serializer</artifactId>
      <version>2.7.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/xalan/xalan -->
    <dependency>
      <groupId>xalan</groupId>
      <artifactId>xalan</artifactId>
      <version>2.7.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/xerces/xercesImpl -->
    <dependency>
      <groupId>xerces</groupId>
      <artifactId>xercesImpl</artifactId>
      <version>2.12.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/xmlgraphics-commons -->
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>xmlgraphics-commons</artifactId>
      <version>2.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-all -->
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-all</artifactId>
      <version>1.14</version>
      <type>pom</type>
    </dependency>
    <!-- https://mvnrepository.com/artifact/xml-apis/xml-apis -->
    <dependency>
      <groupId>xml-apis</groupId>
      <artifactId>xml-apis</artifactId>
      <version>1.4.01</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>fop</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>com.github.jnr</groupId>
      <artifactId>jnr-posix</artifactId>
      <version>3.0.15</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.11.0</version>
        <configuration>
          <compilerVersion>1.8</compilerVersion>
        </configuration>
      </plugin>
      <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-shade-plugin</artifactId>
          <executions>
              <execution>
                  <goals>
                      <goal>shade</goal>
                  </goals>
                  <configuration>
                      <shadedArtifactAttached>true</shadedArtifactAttached>
                      <transformers>
                          <transformer implementation=
                            "org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                              <mainClass>embedding.FopXml2Pdf</mainClass>
                      </transformer>
                  </transformers>
              </configuration>
              </execution>
          </executions>
      </plugin>
    </plugins>
  </build>
</project>

相关问题