gpt4 book ai didi

java - iText PDF 文档无法打开 : java. io.IOException : No message found for the. document.has.no.pages

转载 作者:行者123 更新时间:2023-12-01 13:09:49 36 4
gpt4 key购买 nike

所以我正在练习使用 iText 创建一个小文档。该 pdf 是在我的下载文件夹中创建的,但是当我尝试打开它时,我收到一条消息和一个错误:

消息:

它不是支持文件或已损坏

追踪:

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"));
}

}

知道我做错了什么吗?

最佳答案

我正在遵循一个非常糟糕的教程,并找到了一个更好的教程 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();
}

}

关于java - iText PDF 文档无法打开 : java. io.IOException : No message found for the. document.has.no.pages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22973376/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com