首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java iText 動態生成 Word 下載:動態路徑解決方案與 Servlet 輸出流實戰

     編輯:程式設計綜合問答

需求分析

點擊按鈕從數據庫讀取數據生成 Word 文檔,瀏覽器彈出「另存為」對話框,用戶自選保存路徑。

核心誤區

服務端不能直接寫入客戶端本地路徑:
Web 應用運行在服務器,FileOutputStream 只能寫服務器磁盤。下載本質是 HTTP 響應輸出流 + Content-Disposition 頭。

標準 Servlet 實現

@WebServlet("/downloadWord")
public class WordDownloadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        // 1. 設置響應頭
        resp.setContentType("application/msword");
        resp.setHeader("Content-Disposition", 
            "attachment; filename=\"" + URLEncoder.encode("報告.doc", "UTF-8") + "\"");
        
        // 2. 獲取輸出流
        try (OutputStream out = resp.getOutputStream()) {
            // 3. 生成文檔直接寫入輸出流
            Document document = new Document();
            PdfWriter.getInstance(document, out);  // iText 7 用 PdfWriter
            document.open();
            
            // 動態數據填充
            document.add(new Paragraph("動態生成的 Word 內容"));
            // ... 從數據庫讀取數據添加表格、圖片等
            
            document.close();
        }
    }
}

關鍵點

  • Content-Disposition: attachment 觸發瀏覽器下載對話框
  • filename 需 URLEncoder.encode 處理中文
  • 直接寫 resp.getOutputStream(),無臨時文件、無路徑依賴
  • 項目部署路徑變更完全不影響

iText 版本注意

  • iText 5:PdfWriter.getInstance(doc, out)
  • iText 7:PdfWriter writer = new PdfWriter(out); PdfDocument pdf = new PdfDocument(writer); Document doc = new Document(pdf);
  • 真正的 Word (.docx) 需用 Apache POI (XWPFDocument),iText 主攻 PDF

Web 下載 = 設置響應頭 + 寫 ServletOutputStream。拒絕服務端本地文件落地,擁抱流式傳輸。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved