用Java创建PDF文件

时间:2018-05-02 11:58:34

标签: java servlets itext xmlworker

我正在尝试使用Java从HTML创建PDF文件。我添加了两个jar文件。

  1. itextpdf-5.1.0
  2. xmlworker-5.5.6
  3. 我的代码:

    import com.itextpdf.text.Document;
    import com.itextpdf.text.pdf.PdfWriter;
    import com.itextpdf.tool.xml.XMLWorkerHelper;
        String emailBody = "<html><body> This is my Project </body></html>";
    
        OutputStream file = new FileOutputStream(new File("E:\\Test.pdf"));
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, file);
        document.open();
        InputStream is = new ByteArrayInputStream(emailBody.getBytes());
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
        document.close();
        file.close();
    

    我从这一行得到了一个错误:

    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    

    它抛出了我这个例外。我正在寻找解决方案。

    java.lang.NoSuchMethodError: com.itextpdf.text.log.LoggerFactory.getLogger(Ljava/lang/Class;)Lcom/itextpdf/text/log/Logger;
        at com.itextpdf.tool.xml.net.FileRetrieveImpl.<clinit>(FileRetrieveImpl.java:68)
        at com.itextpdf.tool.xml.css.StyleAttrCSSResolver.<init>(StyleAttrCSSResolver.java:116)
        at com.itextpdf.tool.xml.css.StyleAttrCSSResolver.<init>(StyleAttrCSSResolver.java:105)
        at com.itextpdf.tool.xml.css.StyleAttrCSSResolver.<init>(StyleAttrCSSResolver.java:93)
        at com.itextpdf.tool.xml.XMLWorkerHelper.parseXHtml(XMLWorkerHelper.java:212)
        at com.itextpdf.tool.xml.XMLWorkerHelper.parseXHtml(XMLWorkerHelper.java:184)
        at com.cds.controllers.subservlets.Admin.PDFDownload.manageDetails(PDFDownload.java:102)
        at com.cds.models.SubServletModel.handleRequest(SubServletModel.java:66)
        at com.cds.controllers.HDTController.doPost(HDTController.java:390)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    

    感谢。

2 个答案:

答案 0 :(得分:1)

很可能它们彼此不相容。请尝试使用以下最新版本xmlworker-5.5.13.jaritextpdf-5.5.13.jar

答案 1 :(得分:-1)

你真的与这两个库有冲突。 您必须将Loggeer的传递依赖性排除在其中一个之外。

您使用什么构建工具?与mavengradle

相同

请参阅https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.htmlhttps://docs.gradle.org/current/userguide/managing_transitive_dependencies.html