java springboot 生成pdf 的方式有哪些

在Spring Boot应用程序中生成PDF文件,‌可以通过以下几种方式实现:‌

一、使用PDFBox库:‌

   PDFBox是一个开源的Java库,‌用于处理PDF文档。‌它支持创建、‌读取和修改PDF文件。‌在Spring Boot应用程序中,‌可以通过PDFBox库来生成PDF文件。‌具体实现包括创建一个PDDocument对象,‌添加页面,‌设置页面内容流,‌设置字体和大小,‌显示文本,‌最后保存并关闭文档。‌

1、添加依赖:

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>

2、使用PDFBox API来创建、读取、编辑PDF文件。

以下是一个简单的例子,展示如何使用PDFBox创建一个PDF文件并添加一些文本:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
 
import java.io.IOException;
 
public class PDFBoxExample {
    public static void main(String[] args) {
        try {
            // 创建一个PDF文档
            PDDocument document = new PDDocument();
            // 创建一页
            PDPage page = new PDPage();
            document.addPage(page);
            // 创建一个内容流
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            // 设置字体
            contentStream.setFont(PDType1Font.HELVETICA_BOLD);
            // 将文本添加到PDF页面
            contentStream.drawString("PDFBox! This is a PDF document.");
            // 关闭内容流
            contentStream.close();
            // 保存文档
            document.save("PDFBox.pdf");
            // 关闭文档
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

二、使用ReportLab库:‌

   ReportLab是一个开源的PDF生成库,‌支持多种编程语言,‌包括Java和Python。‌在Spring Boot应用程序中,‌可以通过集成ReportLab库来实现PDF的生成。‌这需要在项目的pom.xml文件中添加ReportLab依赖。‌

1、添加依赖:

<dependency>
    <groupId>com.reportlab</groupId>
    <artifactId>reportlab</artifactId>
    <version>4.5.3</version>
</dependency>

2、创建一个服务来生成 PDF

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import org.springframework.stereotype.Service;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
 
@Service
public class PdfGenerationService {
 
    public void generatePdf(String filePath) throws DocumentException, FileNotFoundException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(filePath));
        document.open();
        document.add(new Paragraph("Hello, ReportLab!"));
        document.close();
    }
}

3、在一个控制器中调用服务生成 PDF

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.FileNotFoundException;
import java.io.IOException;
 
@RestController
public class PdfController {
 
    @Autowired
    private PdfGenerationService pdfGenerationService;
 
    @GetMapping("/generatePdf")
    public String generatePdf() {
        try {
            pdfGenerationService.generatePdf("output.pdf");
            return "PDF generated successfully";
        } catch (FileNotFoundException | DocumentException e) {
            e.printStackTrace();
            return "Error generating PDF";
        }
    }
}

三、使用iText库:‌

    iText是一个流行的PDF处理库,‌支持创建、‌编辑和提取PDF文件的内容。‌在Spring Boot中,‌可以通过集成iText库来生成PDF文件。‌这需要在pom.xml文件中添加iText依赖,‌并编写代码来生成PDF文件,‌例如创建一个Document对象,‌添加内容,‌然后保存为PDF文件。‌

1、添加依赖:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.1.9</version>
</dependency>

2、创建一个服务来生成 PDF

import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.*;
import com.itextpdf.layout.element.Paragraph;
import org.springframework.stereotype.Service;
import java.io.IOException;
 
@Service
public class PdfService {
 
    public void generatePdf(String dest) throws IOException {
        // Initialize PDF writer
        PdfWriter writer = new PdfWriter(dest);
        // Initialize PDF document
        PdfDocument pdf = new PdfDocument(writer);
        // Initialize document
        Document document = new Document(pdf);
        // Add content
        document.add(new Paragraph("Hello, Spring Boot and iText7!"));
        // Close document
        document.close();
        System.out.println("PDF created successfully!");
    }
}

3、创建一个控制器来调用服务生成 PDF

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
 
@RestController
public class PdfController {
 
    @Autowired
    private PdfService pdfService;
 
    @GetMapping("/generatePdf")
    public String generatePdf() {
        try {
            pdfService.generatePdf("target/test.pdf");
            return "PDF generated";
        } catch (IOException e) {
            e.printStackTrace();
            return "Error generating PDF";
        }
    }
}

四、使用动态HTML转换:‌

   先创建一个动态HTML文件,‌然后使用HTML转PDF的工具或库将其转换为PDF。‌这种方法适用于需要从HTML内容生成PDF的情况。‌可以在Spring Boot应用程序中实现这种转换,‌例如通过将HTML内容保存为文件,‌然后使用外部工具或库将其转换为PDF。‌
   在Spring Boot中,可以使用OpenPDF库(一个开源的iText分支)来动态生成PDF文件。

1、添加依赖:

<dependency>
    <groupId>com.openhtmltopdf</groupId>
    <artifactId>openhtmltopdf-core</artifactId>
    <version>1.0.10</version>
</dependency>

2、创建一个服务来生成PDF

import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
 
@Service
public class PdfService {
 
    public byte[] generatePdfFromHtml(String htmlContent) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfRendererBuilder builder = new PdfRendererBuilder();
 
        builder.useFastMode();
        builder.withHtmlContent(htmlContent, null);
        builder.toStream(outputStream);
        builder.run();
 
        return outputStream.toByteArray();
    }
}

3、创建一个控制器来提供PDF文件的下载

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
 
import java.io.IOException;
 
@Controller
@RequestMapping("/pdf")
public class PdfController {
 
    @Autowired
    private PdfService pdfService;
 
    @GetMapping
    public ResponseEntity<byte[]> generatePdf() throws IOException {
        String htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
        byte[] pdfBytes = pdfService.generatePdfFromHtml(htmlContent);
 
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.set("Content-Disposition", "attachment; filename=example.pdf");
 
        return new ResponseEntity<>(pdfBytes, headers, org.springframework.http.HttpStatus.CREATED);
    }
}

五、使用itextpdf根据模板动态生成:‌

   这种方法适用于需要根据特定模板生成PDF的情况。‌通过集成itextpdf库,‌可以根据合同模板动态生成包含合同标签、‌合同方以及签约时间等信息的PDF文件。

1、添加依赖:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.1.9</version>
    <type>pom</type>
</dependency>

2、创建 PDF 文档

创建一个 PDF 文档并添加一些内容:

import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.*;
import com.itextpdf.layout.element.Paragraph;
 
public void createPdf(String dest) throws Exception {
    //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();
    System.out.println("PDF Created");
}

3、调用 createPdf 方法

在你的 Spring Boot 应用中,你可以在任何需要的地方调用 createPdf 方法来创建 PDF 文档。

  • 11
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cesske

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值