如何修复Exception in thread "main" java.lang.NoSuchMethodError异常?附Docx转PDF代码
NoSuchMethodError and Properly Converting DOCX to PDF in Java First, let's tackle that error you're seeing: java.lang.NoSuchMethodError: org.apache.poi.POIXMLDocumentPart.getPackageRelationship. This almost always boils down to dependency version conflicts in your project. You're likely mixing different versions of Apache POI libraries (like poi and poi-ooxml) or using a PDF conversion library that's incompatible with your POI version.
Step 1: Fix Dependencies
To resolve the conflict, ensure all your Apache POI-related dependencies use the same stable version. Below are the correct dependencies for Maven and Gradle, including the necessary libraries for DOCX-to-PDF conversion (we use OpenPDF here to avoid iText's licensing issues):
Maven (pom.xml)
<!-- Apache POI core for handling Office files --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.5</version> </dependency> <!-- POI for OOXML (DOCX) support --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.5</version> </dependency> <!-- Full OOXML support required for PDF conversion --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-full</artifactId> <version>5.2.5</version> </dependency> <!-- OpenPDF for PDF generation (replaces iText) --> <dependency> <groupId>com.github.librepdf</groupId> <artifactId>openpdf</artifactId> <version>1.3.30</version> </dependency>
Gradle (build.gradle)
implementation 'org.apache.poi:poi:5.2.5' implementation 'org.apache.poi:poi-ooxml:5.2.5' implementation 'org.apache.poi:poi-ooxml-full:5.2.5' implementation 'com.github.librepdf:openpdf:1.3.30'
Step 2: Revised Conversion Code
Your original code had a few issues (like unclosed streams and limited exception handling). Here's a polished version that follows Java best practices, handles resources properly, and ensures consistent formatting in the output PDF:
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.converter.pdf.PdfConverter; import org.apache.poi.xwpf.converter.pdf.PdfOptions; import java.io.*; public class DocxToPdfConverter { public static void main(String[] args) { DocxToPdfConverter converter = new DocxToPdfConverter(); System.out.println("Starting DOCX to PDF conversion..."); try { converter.convertToPdf("D:\\doctopdf.docx", "D:\\Test1.pdf"); System.out.println("Conversion done! Check your output PDF at D:\\Test1.pdf"); } catch (Exception e) { System.err.println("Conversion failed with error: " + e.getMessage()); e.printStackTrace(); // Prints full stack trace for easier debugging } } public void convertToPdf(String docxFilePath, String pdfOutputPath) throws IOException { // Use try-with-resources to auto-close streams (prevents resource leaks) try (InputStream docxInput = new FileInputStream(new File(docxFilePath)); XWPFDocument docxDocument = new XWPFDocument(docxInput); OutputStream pdfOutput = new FileOutputStream(new File(pdfOutputPath))) { PdfOptions pdfOptions = PdfOptions.create(); // Optional: Uncomment below to fix Chinese/non-English character rendering // pdfOptions.fontProvider((familyName, encoding, size, style, color) -> { // try { // return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); // } catch (Exception e) { // return null; // Fallback to default font if custom font fails // } // }); // Perform the conversion PdfConverter.getInstance().convert(docxDocument, pdfOutput, pdfOptions); } } }
Key Improvements & Notes
- Auto-closed Resources: The
try-with-resourcessyntax ensures all input/output streams and the document are closed automatically, even if an error occurs. - Better Exception Handling: We catch general exceptions and print the full stack trace, which helps diagnose any remaining issues quickly.
- Font Support: If your DOCX contains non-English characters (like Chinese), uncomment the font provider code and ensure the specified font is available on your system (or embed it in your project).
- Consistent Formatting: Using the matching POI and OpenPDF versions ensures that the PDF retains the original DOCX's layout, fonts, and styling as closely as possible.
内容的提问来源于stack exchange,提问作者Jasir

