为何无法正确使用iText7中的Document类?技术咨询
Let’s get to the bottom of this issue—you’re running into two main problems here that are causing the error: incorrect syntax when creating the Document instance, and importing the wrong Document class entirely. Here’s how to fix both:
1. Correct the Document Instantiation Syntax
Your line Document doc = new Document; has two critical issues:
- It’s missing parentheses for the constructor call
- It’s missing the required
PdfDocumentparameter that links your layoutDocumentto the underlying PDF structure
Fix it to this:
Document doc = new Document(pdfDocument);
2. Import the Right Document Class
The static import import static com.itextpdf.kernel.pdf.PdfName.Document; is pulling in a PDF internal name constant, not the layout Document class you need for building content. Replace that incorrect import with the correct one:
import com.itextpdf.layout.Document;
3. Double-Check Your Dependencies (If Issues Persist)
If you’re still seeing problems after fixing the above, make sure you have the full iText7 core dependencies installed. The Document class lives in the layout module, so if you’re using a build tool:
- For Maven, add this to your
pom.xml:<dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</artifactId> <version>7.2.5</version> <!-- Use the latest stable version available --> <type>pom</type> </dependency> - For Gradle, add this to your build script:
implementation 'com.itextpdf:itext7-core:7.2.5'
Full Working Example
Here’s your code corrected end-to-end, including a valid file path and basic content addition:
import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import java.io.File; import java.io.IOException; public class CreatePdf { public static void main(String[] args) throws IOException { // Use a valid path with a filename (not just a directory) File file = new File("D:/project/my_output.pdf"); PdfWriter writer = new PdfWriter(file); PdfDocument pdfDocument = new PdfDocument(writer); Document doc = new Document(pdfDocument); // Add sample content to the document doc.add(new Paragraph("Success! Your iText7 Document is working.")); // Always close the document and PdfDocument to flush content doc.close(); pdfDocument.close(); } }
A quick note: your original file path D/project is missing a slash and a filename—make sure you point to a specific .pdf file, not just a directory, to avoid file access errors.
内容的提问来源于stack exchange,提问作者Szabolcs Fekete

