锋盈数科-知识库 Logo
首页
软件开发
计算机基础
Hello Halo
新手必读
关于本知识库
登录 →
锋盈数科-知识库 Logo
首页 软件开发 计算机基础 Hello Halo 新手必读 关于本知识库
登录
  1. 首页
  2. 软件开发
  3. JAVA
  4. java springboot 生成pdf 的方式有哪些

java springboot 生成pdf 的方式有哪些

0
  • JAVA
  • 发布于 2024-08-16
  • 0 次阅读
黄健
黄健

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

在 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; file);
 
        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 文档。

标签: #软件开发 1171 #JAVA 991
相关文章

Spring 实现 3 种异步接口 2024-10-18 09:07

大家好,我是苏三~ 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable、WebAsyncTask 和 DeferredResult、CompletableFuture等均可实现。 但这些方法有局限性,处理结果仅返回单个值。在某些场景下,如果需要接口异步处理的同时,还持续不断地

重学SpringBoot3-集成Redis(五)之布隆过滤器 2024-10-08 11:24

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》 期待您的点赞👍收藏⭐评论✍ 重学SpringBoot3-集成Redis(五)之布隆过滤器 1. 什么是布隆过滤器? * 基本概念 适用场景 2. 使用 Redis 实现布隆过滤器 * 项目依赖 Redis 配置

SpringBoot整合异步任务执行 2024-10-08 11:24

同步任务: 同步任务是在单线程中按顺序执行,每次只有一个任务在执行,不会引发线程安全和数据一致性等 并发问题 同步任务需要等待任务执行完成后才能执行下一个任务,无法同时处理多个任务,响应慢,影响用 户体验 异步任务: 异步任务是在多线程中同时执行,多个任务可以并发执行,同时处理多个请求,响应快,资源

springboot kafka多数据源,通过配置动态加载发送者和消费者 2024-10-08 11:24

前言 最近做项目,需要支持kafka多数据源,实际上我们也可以通过代码固定写死多套kafka集群逻辑,但是如果需要不修改代码扩展呢,因为kafka本身不处理额外逻辑,只是起到削峰,和数据的传递,那么就需要对架构做一定的设计了。 准备test kafka本身非常容易上手,如果我们需要单元测试,引入ja

SpringBoot 集成 Redis 2024-10-08 11:24

一:SpringBoot 集成 Redis ①Redis是一个 NoSQL(not only)数据库, 常作用缓存 Cache 使用。 ②Redis是一个中间件、是一个独立的服务器;常用的数据类型: string , hash ,set ,zset , list ③通过Redis客户端可以使用多种语

SpringBoot整合QQ邮箱 2024-10-08 11:24

SpringBoot可以通过导入依赖的方式集成多种技术,这当然少不了我们常用的邮箱,现在本章演示SpringBoot整合QQ邮箱发送邮件…. 下面按步骤进行: 1.获取QQ邮箱授权码 1.1 登录QQ邮箱 1.2 开启SMTP服务 找到下图中的SMTP服务区域,如果当前账号未开启的话自己手动开启。

目录

IT 外包服务商

  • 意见投递
  • zyf6619

软件开发应用

主菜单

  • 首页
  • 软件开发
  • 计算机基础
  • Hello Halo
  • 新手必读
  • 关于本知识库
Copyright © 2024 your company All Rights Reserved. Powered by Halo.