Bootstrap

Spring Boot 简单预览PDF例子

目录

前言

一、引入依赖

二、使用步骤

1.创建 Controller 处理 PDF 生成和预览

2.创建预览页面

总结



前言

使用 Spring Boot 创建一个生成 PDF 并进行预览的项目,你可以按以下步骤进行。我们将使用 Spring BootThymeleafiText 等技术来完成这个任务。


一、引入依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>com.example</groupId>
    <artifactId>pdf-preview</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>pdf-preview</name>
    <description>Spring Boot PDF Preview</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Starter Thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- iText PDF Library for PDF generation -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.2.6</version>
            <type>pom</type>
        </dependency>

        <!-- Spring Boot Starter Test (for unit tests) -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

二、使用步骤

1.创建 Controller 处理 PDF 生成和预览

        

package com.example.pdfpreview;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
public class PdfController {

    @GetMapping("/generate-pdf/{text}")
    public ResponseEntity<InputStreamResource> generatePdf(@PathVariable String text) throws IOException {
        // Step 1: Create a PDF document
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PdfWriter writer = new PdfWriter(byteArrayOutputStream);
        PdfDocument pdfDocument = new PdfDocument(writer);
        Document document = new Document(pdfDocument);
        document.add(new Paragraph(text));

        // Close document to finish writing
        document.close();

        // Step 2: Prepare the response as a downloadable PDF
        InputStreamResource resource = new InputStreamResource(byteArrayOutputStream.toInputStream());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=generated.pdf")
                .contentType(org.springframework.http.MediaType.APPLICATION_PDF)
                .contentLength(byteArrayOutputStream.size())
                .body(resource);
    }

    @GetMapping("/preview-pdf")
    public String previewPdf(Model model) {
        // This page can be used for simple preview before generating the PDF
        model.addAttribute("previewText", "Hello, this is a sample preview text for your PDF!");
        return "preview";
    }
}

2.创建预览页面

src/main/resources/templates 目录下创建一个名为 preview.html 的 Thymeleaf 页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF Preview</title>
</head>
<body>
    <h1>PDF Preview</h1>
    <p>Preview Text: <strong th:text="${previewText}"></strong></p>
    <form action="/generate-pdf/{text}" method="get">
        <input type="text" name="text" value="Hello, World!" />
        <button type="submit">Generate PDF</button>
    </form>
</body>
</html>

 


总结

;