所以我正在用iText练习创建一个小文档。 pdf是在我的下载文件夹中创建的,但是当我尝试打开它时,我收到一条消息并显示错误:
消息:
it is either not a support file or it has been damaged
跟踪:
ExceptionConverter: java.io.IOException: No message found for the.document.has.no.pages
at com.lowagie.text.pdf.PdfPages.writePageTree(Unknown Source)
at com.lowagie.text.pdf.PdfWriter.close(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.close(Unknown Source)
at com.lowagie.text.Document.close(Unknown Source)
at iTextTester.tester.main(tester.java:26)
代码:
package iTextTester;
import com.lowagie.text.Anchor;
import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Section;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class tester {
private static Font catFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD);
private static Font subFont = new Font(Font.TIMES_ROMAN, 12, Font.BOLD);
public static void main(String[] args) {
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("C:/Users/me/Downloads/FirstPdf.pdf"));
document.open();
document.addTitle("TITLE");
document.addAuthor("AUTHOR");
document.close();
addContent(document);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addContent(Document document) throws DocumentException {
Anchor anchor = new Anchor("First Chapter", catFont);
anchor.setName("First Chapter");
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph subPara = new Paragraph("Subcategory 1", subFont);
Section subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Hello"));
}
}
知道我做错了什么吗?
答案 0 :(得分:1)
我正在关注一个非常糟糕的教程,并发现了一个更好的教程here。
此代码已简化且运行良好:
package iTextTester;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class tester {
public static final String RESULT = "C:/Users/me/Downloads/text.pdf";
public static void main(String[] args) throws DocumentException,
IOException {
new tester().createPdf(RESULT);
}
public void createPdf(String filename) throws DocumentException,
IOException {
Document document = new Document(PageSize.LETTER);
PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();
document.add(new Paragraph("Hello World!"));
document.close();
}
}