<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>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Java servlet PDF 教程 > 原文: [http://zetcode.com/articles/javaservletpdf/](http://zetcode.com/articles/javaservletpdf/) Java servlet PDF 教程展示了如何從 Java servlet 返回 PDF 數據。 我們使用 iText 庫處理 PDF。 該 Web 應用已部署在 Tomcat 服務器上。 ## PDF 格式 便攜式文檔格式(PDF)是用于以獨立于應用軟件,硬件和操作系統的方式呈現文檔的文件格式。 PDF 由 Adobe 發明,現在是國際標準化組織(ISO)維護的開放標準。 ## Java Servlet Servlet 是 Java 類,可響應特定類型的網絡請求-最常見的是 HTTP 請求。 Java servlet 用于創建 Web 應用。 它們在 servlet 容器(例如 Tomcat 或 Jetty)中運行。 現代 Java Web 開發使用在 servlet 之上構建的框架。 ## iText iText 是一個開放源代碼庫,用于在 Java 中創建和處理 PDF 文件。 ## Java Servlet PDF 應用 以下 Web 應用使用 Java Servlet 將 PDF 文件發送到客戶端。 它從對象列表生成 PDF。 ```java $ tree . ├── pom.xml └── src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── bean │ │ │ └── City.java │ │ ├── service │ │ │ └── CityService.java │ │ ├── util │ │ │ └── GeneratePdf.java │ │ └── web │ │ └── MyServlet.java │ └── webapp │ ├── index.html │ ├── META-INF │ │ └── context.xml │ └── WEB-INF └── 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>JavaServletPDF</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>JavaServletPDF</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>4.2.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> ``` 這是 Maven POM 文件。 我們有兩個工件:用于 Java 的 servlet 的`javax.servlet-api`和用于 PDF 生成的`itext`。 `maven-war-plugin`負責收集 Web 應用的所有工件依賴項,類和資源,并將它們打包到 Web 應用存檔(WAR)中。 `context.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <Context path="/JavaServletPdf"/> ``` 在 Tomcat `context.xml`文件中,我們定義了上下文路徑。 它是 Web 應用的名稱。 `City.java` ```java package com.zetcode.bean; public class City { private Long id; private String name; private int population; public City() { } public City(Long id, String name, int population) { this.id = id; 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 String toString() { return "City{" + "id=" + id + ", name=" + name + ", population=" + population + '}'; } } ``` 這是`City` bean。 它具有三個屬性:`id`,`name`和`population`。 `MyServlet.java` ```java package com.zetcode.web; import com.zetcode.bean.City; import com.zetcode.service.CityService; import com.zetcode.util.GeneratePdf; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"}) public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/pdf;charset=UTF-8"); response.addHeader("Content-Disposition", "inline; filename=" + "cities.pdf"); ServletOutputStream out = response.getOutputStream(); List<City> cities = CityService.getCities(); ByteArrayOutputStream baos = GeneratePdf.getPdfFile(cities); baos.writeTo(out); } } ``` 這是`MyServlet` servlet。 它從服務類檢索數據,從數據生成 PDF 文件,然后將 PDF 文件返回給客戶端。 ```java response.setContentType("application/pdf;charset=UTF-8"); ``` 我們將響應對象的內容類型設置為`application/pdf`。 ```java response.addHeader("Content-Disposition", "inline; filename=" + "cities.pdf"); ``` `Content-Disposition`響應標頭指示內容應在瀏覽器中顯示為`inline`,即作為 Web 頁面或 Web 頁面的一部分,或作為`attachment`在本地下載和保存。 。 可選的`filename`偽指令指定傳輸文件的名稱。 ```java ServletOutputStream out = response.getOutputStream(); ``` 我們從響應對象獲得`ServletOutputStream`。 ```java List<City> cities = CityService.getCities(); ``` 從`CityService`中,我們可以獲得城市列表。 ```java List<City> cities = CityService.getCities(); ``` 從`CityService`中,我們可以獲得城市列表。 ```java ByteArrayOutputStream baos = GeneratePdf.getPdfFile(cities); baos.writeTo(out); ``` 我們根據數據生成 PDF 文件,并將返回的`ByteArrayOutputStream`寫入`ServletOutputStream`。 `CityService.java` ```java package com.zetcode.service; import com.zetcode.bean.City; import java.util.ArrayList; import java.util.List; public class CityService { public static List<City> getCities() { List<City> cities = new ArrayList<>(); cities.add(new City(1L, "Bratislava", 432000)); cities.add(new City(2L, "Budapest", 1759000)); cities.add(new City(3L, "Prague", 1280000)); cities.add(new City(4L, "Warsaw", 1748000)); cities.add(new City(5L, "Los Angeles", 3971000)); cities.add(new City(6L, "New York", 8550000)); cities.add(new City(7L, "Edinburgh", 464000)); cities.add(new City(8L, "Berlin", 3671000)); return cities; } } ``` `CityService`的`getCities()`方法返回城市對象的列表。 `GeneratePdf.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.bean.City; import java.io.ByteArrayOutputStream; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class GeneratePdf { public static ByteArrayOutputStream getPdfFile(List<City> cities) { Document document = new Document(); ByteArrayOutputStream bout = 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, bout); document.open(); document.add(table); document.close(); } catch (DocumentException ex) { Logger.getLogger(GeneratePdf.class.getName()).log(Level.SEVERE, null, ex); } return bout; } } ``` `GeneratePdf`根據提供的數據創建 PDF 文件。 ```java ByteArrayOutputStream bout = new ByteArrayOutputStream(); ``` 數據將被寫入`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, bout); ``` 使用`PdfWriter`,將文檔寫入`ByteArrayOutputStream`。 ```java document.open(); document.add(table); ``` 該表將插入到 PDF 文檔中。 ```java document.close(); ``` 為了將數據寫入`ByteArrayOutputStream`,必須關閉文檔。 ```java return bout; ``` 最后,數據返回為`ByteArrayOutputStream`。 在本教程中,我們從 Java servlet 發送了 PDF 數據。 您可能也對以下相關教程感興趣: [Java `RequestDispatcher`](/java/requestdispatcher/) , [Java Servlet 圖表教程](/articles/javaservletchart/),[從 Java Servlet 提供純文本](/articles/javaservlettext/), [Java Servlet 檢查框教程](/articles/javaservletcheckbox/), [Java servlet 圖像教程](/articles/javaservletimage/), [Java Servlet HTTP 標頭](/articles/javaservlethttpheaders/)或 [Java 教程](/lang/java/)
                  <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>

                              哎呀哎呀视频在线观看