在 Java 中创建 PDF 文件

Creating PDF file in Java

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

  1. itextpdf-5.1.0
  2. xmlworker-5.5.6

我的代码:

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)

谢谢。

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

你这两个库确实有冲突。 您必须从其中之一排除 Loggeer 的传递依赖性。

您使用什么构建工具?比如mavengradle等等

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