我正在使用 iText 通过 NetBeans 8.2 从我的 Java 文件创建 PDF 文件。我已经从 here 下载了 iText JAR 文件。我的iText版本是7.0.2。
这是部分代码(我只包含 Java 文件中与 iText 相关的导入文件和代码):
考勤.java
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
.
.
.
.
try {
OutputStream output = new FileOutputStream(new File("C:\\Users\\dell\\Desktop\\Attendance.pdf"));
DefaultListModel model1 = (DefaultListModel)present.getModel();
Document doc = new Document();
PdfWriter.getInstance(doc, output);
doc.open();
for (int i = 0; i < 68; i++) {
doc.add(new Paragraph((String) model1.getElementAt(i)));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Attendance.class.getName()).log(Level.SEVERE, null, ex);
}
问题:
我收到以下 3 个错误:
-
no suitable constructor found for Document(no arguments)
-
cannot find symbol: getInstance(Document, OutputStream)
-
cannot find symbol: open()
我遵循了很多教程,例如 this ,但不知何故,即使我使用了相同的代码,他们也没有遇到我所面临的错误。如果有人使用 iText 做过这样的事情,任何建议将不胜感激。如果您需要更多信息,请告诉我。
最佳答案
您混淆了 iText 5 教程和 iText 7 代码。您正在使用 iText 7,但您正在查看一个描述如何使用 iText 5 的非官方教程。iText 7 是 iText 5 的完全重写,并且 API 完全不同。
请查看官方网站上的以下教程:
可以找到 hello world 示例 here看起来像这样:
//Initialize PDF writer
PdfWriter writer = new PdfWriter(dest);
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf);
//Add paragraph to the document
document.add(new Paragraph("Hello World!"));
//Close document
document.close();
如您所见,它与您使用的 iText 5 代码完全不同。
重要提示:始终转到official web site获取信息!有许多网站包含的示例会给您提供错误的建议,特别是关于数字签名(过时的示例)和合并 PDF(错误的方法)。
至于下载 iText,请始终从 download hub page 开始。因为它包含最新版本的链接,包括附加组件的兼容性矩阵。
关于java - iText PDF 创建错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49715293/