首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

iText 入門:Java 動態產生 PDF 完整教學

     編輯:Java 相關知識

iText 簡介

iText 是知名開源 Java PDF 庫(核心 itext-2.1.5.jar),支援:

  • 動態產生 PDF 至瀏覽器下載或伺服器檔案
  • 書籤、頁碼、浮水印、加密、數位簽章
  • PDF 分割、合併、旋轉、縮放
  • 表單填寫、XML 資料綁定

官網下載:lowagie.com,需 JDK 1.4+。

基礎範例:產生檔案

import java.io.*;
import java.util.Date;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;

public class GeneratePDF {
    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream("C:\\Test.pdf");
            Document document = new Document();
            PdfWriter.getInstance(document, file);
            document.open();
            document.add(new Paragraph("Hello Kiran"));
            document.add(new Paragraph(new Date().toString()));
            document.close();
            file.close();
        } catch (Exception e) { e.printStackTrace(); }
    }
}

Web 環境:直接輸出至瀏覽器 (Struts Action 範例)

public class PdfHelloWorldAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest req, HttpServletResponse res) throws Exception {
        Document document = new Document();
        try {
            res.setContentType("application/pdf");
            PdfWriter.getInstance(document, res.getOutputStream());
            document.open();
            document.add(new Paragraph("Hello Kiran"));
            document.add(new Paragraph(new Date().toString()));
        } catch (Exception e) { e.printStackTrace(); }
        document.close();
        return null;
    }
}

關鍵點:PdfWriter.getInstance(document, response.getOutputStream()) + response.setContentType("application/pdf")。

設定 PDF 文件屬性

document.addAuthor("Kiran Hegde");
document.addCreationDate();
document.addCreator("iText library");
document.addTitle("Hello World PDF");
document.addSubject("Dynamic PDF Generation");
document.addKeywords("iText, PDF, Java");
document.addHeader("Header Text");
document.addFooter("Footer Text");

進階功能速查

需求關鍵類別/方法
中文字體BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED) + Font
表格PdfPTable, PdfPCell
圖片Image.getInstance(path)
書籤/大綱Chapter, Section
加密/權限PdfWriter.setEncryption(userPass, ownerPass, permissions, strength)
數位簽章PdfSignatureAppearance
合併 PDFPdfCopy, PdfReader

版本提示

iText 2.1.7 為 LGPL/MPL 雙授權,5.0+ 版改為 AGPL,商業用途需購買授權或採用 2.1.7 版。專案若需長期維護,建議評估 OpenPDF (iText 2.1.7 社群分支) 或 Apache PDFBox。

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