<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 在 Spring Boot 中創建 PDF 報告 > 原文: [http://zetcode.com/springboot/servepdf/](http://zetcode.com/springboot/servepdf/) Spring Boot 創建 PDF 報告教程展示了如何在 Spring Boot Web 應用中提供 PDF 文件。 該報告是使用 iText 庫生成的。 iText 是一個開放源代碼庫,用于在 Java 中創建和處理 PDF 文件。 Spring 是用于開發 Java 企業應用的 Java 應用框架。 它還有助于集成各種企業組件。 Spring Boot 使創建具有 Spring 動力的生產級應用和服務變得很容易,而對安裝的要求卻最低。 H2 是完全用 Java 實現的開源關系數據庫管理系統。 它可以嵌入 Java 應用中或以客戶端-服務器模式運行。 它占地面積小,易于部署和安裝。 它包含一個基于瀏覽器的控制臺應用,用于查看和編輯數據庫表。 Spring Data JPA 是總括性 Spring Data 項目的一部分,該項目使實現基于 JPA 的存儲庫變得更加容易。 Spring Data JPA 使用 JPA 將數據存儲在關系數據庫中。 它可以在運行時從存儲庫接口自動創建存儲庫實現。 ## Spring Boot 服務 PDF 示例 以下 Spring Boot 應用從數據庫表中加載數據,并使用 iText 庫從中生成 PDF 報告。 它使用`ResponseEntity`和`InputStreamResource`將 PDF 數據發送到客戶端。 ```java pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ │ Application.java │ │ ├───controller │ │ │ MyController.java │ │ ├───model │ │ │ City.java │ │ ├───repository │ │ │ CityRepository.java │ │ ├───service │ │ │ CityService.java │ │ │ ICityService.java │ │ └───util │ │ GeneratePdfReport.java │ └───resources │ application.yml │ import.sql └───test └───java ``` 這是項目結構。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <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.zetcode</groupId> <artifactId>springbootservepdf</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>4.2.2</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 這是 Maven 構建文件。 Spring Boot 啟動器是一組有用的依賴項描述符,可大大簡化 Maven 配置。 `spring-boot-starter-parent`具有 Spring Boot 應用的一些常用配置。 `spring-boot-starter-web`是使用 Spring MVC 構建 Web 應用的入門工具。 它使用 Tomcat 作為默認的嵌入式容器。 `spring-boot-starter-data-jpa`是將 Spring Data JPA 與 Hibernate 結合使用的入門工具。 此外,我們還包括 H2 數據庫和 iText 庫的依賴項。 `spring-boot-maven-plugin`在 Maven 中提供了 Spring Boot 支持,使我們可以打包可執行的 JAR 或 WAR 檔案。 它的`spring-boot:run`目標運行 Spring Boot 應用。 `com/zetcode/model/City.java` ```java package com.zetcode.model; import java.util.Objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "cities") public class City { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int population; public City() { } public City(String name, int population) { this.name = name; this.population = population; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + Objects.hashCode(this.id); hash = 79 * hash + Objects.hashCode(this.name); hash = 79 * hash + this.population; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final City other = (City) obj; if (this.population != other.population) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } return Objects.equals(this.id, other.id); } @Override public String toString() { var builder = new StringBuilder(); builder.append("City{id=").append(id).append(", name=") .append(name).append(", population=") .append(population).append("}"); return builder.toString(); } } ``` 這是`City`實體。 每個實體必須至少定義兩個注解:`@Entity`和`@Id`。 `spring.jpa.hibernate.ddl-auto`屬性的默認值為`create-drop`,這意味著 Hibernate 將根據該實體創建表架構。 ```java @Entity @Table(name = "cities") public class City { ``` `@Entity`注解指定該類是一個實體,并映射到數據庫表。 `@Table`實體指定要用于映射的數據庫表的名稱。 ```java @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; ``` `@Id`注解指定實體的主鍵,`@GeneratedValue`提供規范主鍵值的生成策略。 `resources/application.yml` ```java spring: main: banner-mode: "off" logging: level: org: springframework: ERROR ``` `application.yml`是主要的 Spring Boot 配置文件。 使用`banner-mode`屬性,我們可以關閉 Spring 橫幅。 Spring 框架日志記錄設置為`ERROR`。 `resources/import.sql` ```java INSERT INTO cities(name, population) VALUES('Bratislava', 432000); INSERT INTO cities(name, population) VALUES('Budapest', 1759000); INSERT INTO cities(name, population) VALUES('Prague', 1280000); INSERT INTO cities(name, population) VALUES('Warsaw', 1748000); INSERT INTO cities(name, population) VALUES('Los Angeles', 3971000); INSERT INTO cities(name, population) VALUES('New York', 8550000); INSERT INTO cities(name, population) VALUES('Edinburgh', 464000); INSERT INTO cities(name, population) VALUES('Suzhou', 4327066); INSERT INTO cities(name, population) VALUES('Zhengzhou', 4122087); INSERT INTO cities(name, population) VALUES('Berlin', 3671000); INSERT INTO cities(name, population) VALUES('Brest', 139163); INSERT INTO cities(name, population) VALUES('Bucharest', 1836000); ``` 模式是由 Hibernate 自動創建的。 之后,將執行`import.sql`文件以將數據填充到表中。 `com/zetcode/repository/CityRepository.java` ```java package com.zetcode.repository; import com.zetcode.model.City; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface CityRepository extends CrudRepository<City, Long> { } ``` 通過從 Spring `CrudRepository`擴展,我們為數據庫實現了一些方法,包括`findAll()`和`findOne()`。 這樣,我們不必編寫很多樣板代碼。 `com/zetcode/service/ICityService.java` ```java package com.zetcode.service; import com.zetcode.model.City; import java.util.List; public interface ICityService { List<City> findAll(); } ``` `ICityService`提供了一種從數據庫中獲取所有城市的契約方法。 `com/zetcode/service/CityService.java` ```java package com.zetcode.service; import com.zetcode.model.City; import com.zetcode.repository.CityRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CityService implements ICityService { @Autowired private CityRepository repository; @Override public List<City> findAll() { return (List<City>) repository.findAll(); } } ``` `CityService`包含`findAll()`方法的實現。 我們使用存儲庫從數據庫檢索數據。 ```java @Autowired private CityRepository repository; ``` 注入`CityRepository`。 ```java return (List<City>) repository.findAll(); ``` 存儲庫的`findAll()`方法返回城市列表。 `com/zetcode/controller/MyController.java` ```java package com.zetcode.controller; import com.zetcode.model.City; import com.zetcode.service.ICityService; import com.zetcode.util.GeneratePdfReport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; 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.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.io.ByteArrayInputStream; import java.util.List; @Controller public class MyController { @Autowired private ICityService cityService; @RequestMapping(value = "/pdfreport", method = RequestMethod.GET, produces = MediaType.APPLICATION_PDF_VALUE) public ResponseEntity<InputStreamResource> citiesReport() { var cities = (List<City>) cityService.findAll(); ByteArrayInputStream bis = GeneratePdfReport.citiesReport(cities); var headers = new HttpHeaders(); headers.add("Content-Disposition", "inline; filename=citiesreport.pdf"); return ResponseEntity .ok() .headers(headers) .contentType(MediaType.APPLICATION_PDF) .body(new InputStreamResource(bis)); } } ``` `citiesReport()`方法返回生成的 PDF 報告。 `Resource`接口抽象了對低級資源的訪問; `InputStreamResource`是它對流資源的實現。 ```java @Autowired private ICityService cityService; ``` 我們將`ICityService`對象注入到屬性中。 服務對象用于從數據庫檢索數據。 ```java var cities = (List<City>) cityService.findAll(); ``` 我們使用`findAll()`方法查找所有城市。 ```java ByteArrayInputStream bis = GeneratePdfReport.citiesReport(cities); ``` `GeneratePdfReport.citiesReport()`使用 iText 庫從城市列表中生成 PDF 文件。 ```java HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "inline; filename=citiesreport.pdf"); ``` 通過將`Content-Disposition`設置為`inline`,PDF 文件將直接顯示在瀏覽器中。 ```java return ResponseEntity .ok() .headers(headers) .contentType(MediaType.APPLICATION_PDF) .body(new InputStreamResource(bis)); ``` 我們使用`ResponseEntity`創建響應。 我們指定標題,內容類型和主體。 內容類型為`MediaType.APPLICATION_PDF`。 身體是`InputStreamResource`。 `com/zetcode/util/GeneratePdfReport.java` ```java package com.zetcode.util; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.zetcode.model.City; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.List; public class GeneratePdfReport { private static final Logger logger = LoggerFactory.getLogger(GeneratePdfReport.class); public static ByteArrayInputStream citiesReport(List<City> cities) { Document document = new Document(); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { PdfPTable table = new PdfPTable(3); table.setWidthPercentage(60); table.setWidths(new int[]{1, 3, 3}); Font headFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD); PdfPCell hcell; hcell = new PdfPCell(new Phrase("Id", headFont)); hcell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(hcell); hcell = new PdfPCell(new Phrase("Name", headFont)); hcell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(hcell); hcell = new PdfPCell(new Phrase("Population", headFont)); hcell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(hcell); for (City city : cities) { PdfPCell cell; cell = new PdfPCell(new Phrase(city.getId().toString())); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase(city.getName())); cell.setPaddingLeft(5); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(String.valueOf(city.getPopulation()))); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setPaddingRight(5); table.addCell(cell); } PdfWriter.getInstance(document, out); document.open(); document.add(table); document.close(); } catch (DocumentException ex) { logger.error("Error occurred: {0}", ex); } return new ByteArrayInputStream(out.toByteArray()); } } ``` `GeneratePdfReport`根據提供的數據創建 PDF 文件。 ```java ByteArrayOutputStream out = new ByteArrayOutputStream(); ``` 數據將被寫入`ByteArrayOutputStream`。 ```java PdfPTable table = new PdfPTable(3); ``` 我們將數據放在表格中; 為此,我們有`PdfPTable`類。 該表具有三列:ID,名稱和人口。 ```java Font headFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD); ``` 對于表頭,我們使用粗體的 Helvetica 字體。 ```java PdfPCell hcell; hcell = new PdfPCell(new Phrase("Id", headFont)); hcell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(hcell); ``` 數據放置在表單元格內,由`PdfPCell`表示。 使用`setHorizontalAlignment()`方法將文本水平對齊。 ```java PdfWriter.getInstance(document, out); ``` 使用`PdfWriter`,將文檔寫入`ByteArrayOutputStream`。 ```java document.open(); document.add(table); ``` 該表將插入到 PDF 文檔中。 ```java document.close(); ``` 為了將數據寫入`ByteArrayOutputStream`,必須關閉文檔。 ```java return new ByteArrayInputStream(out.toByteArray()); ``` 最后,數據返回為`ByteArrayInputStream`。 `com/zetcode/Application.java` ```java package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` `Application`設置 Spring Boot 應用。 ```java $ mvn spring-boot:run ``` 我們啟動 Spring Boot 應用。 我們導航到`http://localhost:8080/pdfreport`以生成報告。 在本教程中,我們展示了如何將生成的 PDF 文件發送回客戶端。 PDF 報告是使用 iText 生成的,數據來自 H2 數據庫。 我們使用 Spring Data JPA 訪問數據。 您可能也對這些相關教程感興趣: [Spring Boot 基本注解](/springboot/annotations/), [Spring Boot H2 教程](/articles/springbooth2/), [Spring Boot JasperReports Web 集成](/articles/jasperspringbootweb/), [Java 教程](/lang/java/)或列出[所有 Spring Boot 教程](/all/#springboot)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看