首页 > 解决方案 > ApachePOI pdf 创建

问题描述

我正在尝试在 Maven 项目中使用 ApachePOI 创建一个简单的表。我查看了他们的文档,但没有看到 PDF 的依赖项。ApachePOI 中是否有内置方法来创建 PDF?

我看到了这个教程,它教你如何转换文件,而不是如何从头开始创建文件。 https://rdtschools.com/covert-docx-file-pdf-using-apache-poi-library-java/

然后我在 stackoverflow 上看到了这个问题,答案看起来像是使用Opensagres POI是可行的方法,因为它适用于 Apache POI 3.17,但需要另一个 JAR。

标签: javapdfapache-poipdf-generation

解决方案


如果你想创建pdf文件,你可以试试

new FileOutputStream("path.pdf");

然后使用 pdf writer,将其写入文件。但是,如果您对生成 Pdf 表感兴趣。我想为您提供另一个库。

我使用itextpdf,并在 pdf 文档中创建了表格。

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.12</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.itextpdf.tool/xmlworker -->
    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.4.4</version>
    </dependency>

你应该写这样的东西

public PdfStream opendocument() {
    document = new Document(PageSize.A4);
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(path));
        writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
        document.open();
    } catch (DocumentException | FileNotFoundException e) {
        e.printStackTrace();
    }
    return this;
}

ps 它是我代码的一部分,不关心PdfStream类。

其中writerdocument对象是PdfWriterDocument实例。我认为在这里编写所有代码示例,这不是一个好主意,但您可以阅读更多关于此https://developers.itextpdf.com/examples/itext-action-second-edition/chapter-1

如果你有任何问题,问我)祝你好运!


推荐阅读