Class Document

java.lang.Object
io.leandev.appfuse.document.Document
All Implemented Interfaces:
AutoCloseable

public class Document extends Object implements AutoCloseable

Word 文件(.docx

文件產生入口,封裝底層 Apache POI 的 XWPFDocument,不洩漏 POI/OOXML 型別。 一般以 open(InputStream) 載入既有 .docx 範本,於其上編排後 write(OutputStream) 輸出。

範本套印

try (Document doc = Document.open(templateStream)) {
    doc.body().findParagraphByText("[customer]").ifPresent(p -> p.setText("玫瑰花坊"));

    Table items = doc.body().tables().get(0);
    for (OrderLine line : order.getLines()) {
        TableRow row = items.appendRow();
        row.cell(0).setText(line.name());
        row.cell(1).setText(line.amount());
    }

    doc.write(outputStream);
}
Since:
4.0.0
  • Method Details

    • open

      public static Document open(InputStream template)
      從輸入串流載入既有文件(範本)
      Parameters:
      template - .docx 輸入串流
      Returns:
      文件
    • create

      public static Document create()
      建立空白文件
      Returns:
      文件
    • body

      public Body body()
      取得文件本文容器
      Returns:
      本文 Body
    • header

      public Body header()
      取得預設頁首(不存在則建立)
      Returns:
      頁首 Body
    • firstHeader

      public Body firstHeader()
      取得首頁頁首(不存在則建立)
      Returns:
      首頁頁首 Body
    • sectionHeader

      public Body sectionHeader()
      取得當前章節頁首(單章節文件等同 header()
      Returns:
      頁首 Body
    • footer

      public Body footer()
      取得預設頁尾(不存在則建立)
      Returns:
      頁尾 Body
    • firstFooter

      public Body firstFooter()
      取得首頁頁尾(不存在則建立)
      Returns:
      首頁頁尾 Body
    • sectionFooter

      public Body sectionFooter()
      取得當前章節頁尾(單章節文件等同 footer()
      Returns:
      頁尾 Body
    • setPageSize

      public void setPageSize(Paper paper)
      設定頁面大小(紙張預設)
      Parameters:
      paper - 紙張
    • setPageSize

      public void setPageSize(Length width, Length height)
      設定頁面大小
      Parameters:
      width - 寬
      height - 高
    • setOrientation

      public void setOrientation(Orientation orientation)
      設定頁面方向
      Parameters:
      orientation - 方向
    • setMargins

      public void setMargins(Length top, Length right, Length bottom, Length left)
      設定頁面四邊邊界
      Parameters:
      top - 上
      right - 右
      bottom - 下
      left - 左
    • setMarginHeader

      public void setMarginHeader(Length h)
      設定頁首邊界
      Parameters:
      h - 頁首邊界
    • setMarginFooter

      public void setMarginFooter(Length f)
      設定頁尾邊界
      Parameters:
      f - 頁尾邊界
    • addPageBreak

      public void addPageBreak()
      在文件末端加入分頁
    • addSectionBreak

      public void addSectionBreak()
      在文件末端加入分節(下一頁)
    • restartPageNumber

      public void restartPageNumber(int from)
      重設頁碼起始值
      Parameters:
      from - 起始頁碼
    • write

      public void write(OutputStream out)
      將文件寫出
      Parameters:
      out - 輸出串流
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable