Java iText操作PDF文檔 – JAVA編程語言程序開發技術文章

1.Action
[java]
//在線打印PDF 
String path = servlet.getServletContext().getRealPath("");  //得到項目根目錄 
CreatePdf checkPdf = new CreatePdf(); 
String filepath = checkPdf.printImportAndPtExpert(path,"expertBase",importList,putongtList); 
request.setAttribute("filepath", path+File.separator+"community"+File.separator+"pdfile"+File.separator+filepath); 
return mapping.findForward("downLoad"); 
 
2.公用類CreatPDF
[java]
import java.io.File; 
import java.io.FileOutputStream; 
import java.util.List; 
 
import com.lowagie.text.Cell; 
import com.lowagie.text.Document; 
import com.lowagie.text.DocumentException; 
import com.lowagie.text.Element; 
import com.lowagie.text.Font; 
import com.lowagie.text.FontFactory; 
import com.lowagie.text.HeaderFooter; 
import com.lowagie.text.Image; 
import com.lowagie.text.PageSize; 
import com.lowagie.text.Paragraph; 
import com.lowagie.text.Phrase; 
import com.lowagie.text.Rectangle; 
import com.lowagie.text.Table; 
import com.lowagie.text.Watermark; 
import com.lowagie.text.pdf.BaseFont; 
import com.lowagie.text.pdf.PdfPageEventHelper; 
import com.lowagie.text.pdf.PdfWriter; 
 
public class CopyOfCreatePdf extends PdfPageEventHelper { 
 
    /**
     * 打印專傢評審基地(重點基地和普通基地)
     * 
     * @param path
     *            獲得項目根目錄 String path =
     *            servlet.getServletContext().getRealPath("");
     * @param filename
     *            文件名
     * @param importList
     *            重點基地集合
     * @param putongList
     *            普通基地集合
     * @return
     * @throws Exception
     */ 
    @SuppressWarnings("unchecked") 
    public String printImportAndPtExpert(String path, String filename, 
            List importList, List putongList) throws Exception { 
        // 創建報表大小,不能夠指定頁邊距。 
        // Document document = new Document(PageSize.A4, 85, 71, 72, 72); 
        Document document = new Document(PageSize.A4, 30, 30, 72, 72); 
        try { 
            BaseFont bfFS = BaseFont.createFont(path + File.separator 
                    + "WEB-INF" + File.separator + "classes" + File.separator 
                    + "fonts" + File.separator + "SIMFANG.TTF", 
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); 
            // 華文細黑 
            BaseFont bfHWXH = BaseFont.createFont(path + File.separator 
                    + "WEB-INF" + File.separator + "classes" + File.separator 
                    + "fonts" + File.separator + "STXIHEI.TTF", 
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); 
            // 黑體 
            BaseFont bfHT = BaseFont.createFont(path + File.separator 
                    + "WEB-INF" + File.separator + "classes" + File.separator 
                    + "fonts" + File.separator + "SIMHEI.TTF", 
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); 
 
            Font htFontB = new Font(bfHT, 14, Font.BOLD); 
 
            PdfWriter writer = PdfWriter.getInstance(document, 
                    new FileOutputStream(path + File.separator + "community" 
                            + File.separator + "pdfile" + File.separator 
                            + filename + ".pdf")); 
 
            // 插入水印 
            if (new File(path + File.separator + "image006.gif") != null) { 
                Watermark watermark = new Watermark(Image.getInstance(path 
                        + File.separator + "image006.gif"), 0f, 0f); 
                document.add(watermark); 
            } else { 
                System.out.println("添加水印失敗"); 
            } 
            com.lowagie.text.Font ST3 = FontFactory.getFont("STSong-Light", 
                    "UniGB-UCS2-H"); 
            ST3.setSize(10f); 
            HeaderFooter footer = new HeaderFooter(new Phrase("第", ST3), 
                    new Phrase("頁", ST3)); 
            footer.setBorder(Rectangle.NO_BORDER); 
            footer.setAlignment(Element.ALIGN_CENTER); 
            document.setFooter(footer); 
            // 加密 
            writer.setEncryption(PdfWriter.STRENGTH128BITS, null, 
                    "hujichen0928", PdfWriter.AllowPrinting 
                            | PdfWriter.AllowCopy); 
            // 添加元信息 
 
            document.addAuthor("北京科學技術委員會"); 
            document.addSubject("評審基地項目列表"); 
            document.open(); 
 
            com.lowagie.text.Font ST = FontFactory.getFont("STSong-Light", 
                    "UniGB-UCS2-H"); 
            com.lowagie.text.Font ST22 = FontFactory.getFont("STSong-Light", 
                    "UniGB-UCS2-H"); 
 
            BaseFont baseFont2 = ST22.getBaseFont(); 
            Font ST2 = new Font(baseFont2, 14, Font.BOLD); 
            com.lowagie.text.Font cnFont = new Font(bfHWXH); 
            ST.setSize(10); 
            ST2.setSize(12); 
 
            Table proinfoTab = new Table(8); 
            proinfoTab.setWidth(100.0f); 
            float[] twidth = { 6f, 8f, 14f, 14f, 14f, 6f, 6f, 28f }; 
            proinfoTab.setWidths(twidth); 
            proinfoTab.setCellspacing(4); 
            // 設置表框屬性 
            Cell proinfoCell = new Cell(new Paragraph("2011年北京市第五批基地申報專傢評審表", 
                    ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setColspan(8); 
            proinfoTab.addCell(proinfoCell); 
 
            proinfoCell = new Cell(new Paragraph("重點評審項目", ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoCell.setColspan(8); 
            proinfoTab.addCell(proinfoCell); 
 
            proinfoCell = new Cell(new Paragraph("序號", ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoTab.addCell(proinfoCell); 
 
            proinfoCell = new Cell(new Paragraph("區縣", ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoTab.addCell(proinfoCell); 
 
            proinfoCell = new Cell(new Paragraph("基地名稱", ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoTab.addCell(proinfoCell); 
 
            proinfoCell = new Cell(new Paragraph("單位名稱", ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoTab.addCell(proinfoCell); 
 
            proinfoCell = new Cell(new Paragraph("基地類別", ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoTab.addCell(proinfoCell); 
 
            proinfoCell = new Cell(new Paragraph("分值", ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoTab.addCell(proinfoCell); 
 
            proinfoCell = new Cell(new Paragraph("等級", ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoTab.addCell(proinfoCell); 
 
            proinfoCell = new Cell(new Paragraph("專傢評語", ST2)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
            proinfoTab.addCell(proinfoCell); 
 
            if (importList.size() > 0 && importList != null) { 
                for (int i = 0; i < importList.size(); i++) { 
 
                    BBasePoint bbp = (BBasePoint) importList.get(i); 
                    BBaseDocument doc = bbp.getBBaseDocument(); 
 
                    // 序號 
                    proinfoCell = new Cell(new Paragraph(String.valueOf(i + 1), 
                            ST)); 
                    proinfoCell.setUseAscender(true); 
                    proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
                    proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
                    proinfoTab.addCell(proinfoCell); 
 
                    // 區縣 
                    if (doc.getDocCorpSection() == null) { 
                        proinfoCell = new Cell(new Paragraph("無", ST)); 
                    } else { 
                        proinfoCell = new Cell(new Paragraph(doc 
                                .getDocCorpSection(), ST)); 
                    } 
                    proinfoCell.setUseAscender(true); 
                    proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
                    proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
                    proinfoTab.addCell(proinfoCell); 
 
                    // 基地名稱 
                    if (doc.getBaseName() == null) { 
                        proinfoCell = new Cell(new Paragraph("無", ST)); 
                    } else { 
                        proinfoCell = new Cell(new Paragraph(doc.getBaseName(), 
                                ST)); 
                    } 
                    proinfoCell.setUseAscender(true); 
                    proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
                    proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
                    proinfoTab.addCell(proinfoCell); 
 
                    // 單位名稱 
                    if (doc.getDocCorpName() == null) { 
                        proinfoCell = new Cell(new Paragraph("無", ST)); 
                    } else { 
                        proinfoCell = new Cell(new Paragraph(doc 
                                .getDocCorpName(), ST)); 
                    } 
                    proinfoCell.setUseAscender(true); 
                    proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
                    proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
                    proinfoTab.addCell(proinfoCell); 
 
                    // 基地類型 
                    if (doc.getDocCorpKind().equals("0")) { 
                        proinfoCell = new Cell(new Paragraph("科普教育基地", ST)); 
                    } else if (doc.getDocCorpKind().equals("1")) { 
                        proinfoCell = new Cell(new Paragraph("科普培訓基地", ST)); 
                    } else if (doc.getDocCorpKind().equals("2")) { 
                        proinfoCell = new Cell(new Paragraph("科普傳媒基地", ST)); 
                    } else if (doc.getDocCorpKind().equals("3")) { 
                        proinfoCell = new Cell(new Paragraph("科普研發基地", ST)); 
                    } else { 
                        proinfoCell = new Cell(new Paragraph("無基地類型", ST)); 
                    } 
                    proinfoCell.setUseAscender(true); 
                    proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
                    proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
                    proinfoTab.addCell(proinfoCell); 
 
                    // 基地評分 
                    if (bbp.getZongpoint() == null) { 
                        proinfoCell = new Cell(new Paragraph("0", ST)); 
                    } else { 
                        proinfoCell = new Cell(new Paragraph(String 
                                .valueOf(Math.round(bbp.getZongpoint())), ST)); // 基地分數 
                    } 
                    proinfoCell.setUseAscender(true); 
                    proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
                    proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
                    proinfoTab.addCell(proinfoCell); 
 
                    // 分數等級 
                    if (bbp.getGrade() == null) { 
                        proinfoCell = new Cell(new Paragraph("無", ST)); 
                    } else { 
                        proinfoCell = new Cell( 
                                new Paragraph(bbp.getGrade(), ST)); 
                    } 
                    proinfoCell.setUseAscender(true); 
                    proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
                    proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER); 
                    proinfoTab.addCell(proinfoCell); 
 
                    // 專傢評語 
                    String opinion = bbp.getOpinion(); 
                    if (opinion != null) { 
                        opinion = opinion.replaceAll("<p>", "\r\n"); 
                        opinion = opinion.replaceAll("</p>", "\r\n"); 
                        opinion = opinion.replaceAll(" ", " "); 
                    } else { 
                        opinion = "無"; 
                    } 
                    proinfoCell = new Cell(new Paragraph(opinion, ST)); 
                    proinfoCell.setUseAscender(true); 
                    proinfoCell.setVerticalAlignment(Cell.LEFT); 
                    proinfoCell.setHorizontalAlignment(Cell.LEFT); 
                    proinfoTab.addCell(proinfoCell); 
                } 
            } 
 
            proinfoCell = new Cell( 
                    new Paragraph( 
                            "專 傢 簽 字:\n\n" 
                                    + "                                                                                                                                           年      月     日\n", 
                            ST)); 
            proinfoCell.setUseAscender(true); 
            proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE); 
            proinfoCell.setHorizontalAlignment(Cell.ALIGN_LEFT); 
            proinfoCell.setColspan(8); 
            proinfoTab.addCell(proinfoCell); 
 
            document.add(proinfoTab); 
        } catch (DocumentException de) { 
            System.err.println(de.getMessage()); 
            de.printStackTrace(); 
        } 
        document.close(); 
        return filename + ".pdf"; 
    } 

3.downLoad.jsp
[html]
<%@ page contentType="text/html;charset=UTF-8" import="com.jspsmart.upload.*" %> 
<% 
  Object obj = request.getAttribute("filepath"); 
  String filepath = ""; 
  if(obj != null){ 
      filepath = (String)obj; 
  }else{ 
      filepath = request.getParameter("filepath"); 
  } 
  System.out.println("**********"+filepath); 
  //filepathfilepath = filepath.replaceAll("/","\\"); 
  // 新建一個SmartUpload對象 
  SmartUpload su = new SmartUpload(); 
  // 初始化 
  su.initialize(pageContext); 
  su.setContentDisposition(null); 
  // 下載文件 
  su.downloadFile(filepath); 
  out.clear(); 
%> 

下面的是在網上看到的一個例子,與大傢分享
[java]
package com.thuram.test; 
 
import java.awt.Color; 
import java.io.FileOutputStream; 
 
import com.lowagie.text.Cell; 
import com.lowagie.text.Chapter; 
import com.lowagie.text.Document; 
import com.lowagie.text.Font; 
import com.lowagie.text.FontFactory; 
import com.lowagie.text.List; 
import com.lowagie.text.ListItem; 
import com.lowagie.text.PageSize; 
import com.lowagie.text.Paragraph; 
import com.lowagie.text.Section; 
import com.lowagie.text.Table; 
import com.lowagie.text.pdf.PdfWriter; 
 
public class ITextTest …{ 
    public static void main(String[] args) …{ 
        try …{ 
            /** *//**
             * 首先,創建一個document。
             * document是PDF文檔中所有元素的容器。
             * 第一個參數表示頁的大小,其後的參數分別表示左、右、上、下的邊距。
             */ 
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);  
             
            /** *//** 
             * 此處創建的write定義瞭上面創建的document的類型。
             * 除瞭PdfWriter以為,還有HtmlWriter, RtfWriter, XmlWriter和一些別的類型。
             * 第一個參數引用document對象,第二個參數指定瞭輸出文件的絕對路徑。
             * 接著,我們open這個document往裡邊寫入數據。
             */ 
            PdfWriter writer = PdfWriter.getInstance(document, 
                    new FileOutputStream("c:/ITextTest.pdf")); 
            writer.setViewerPreferences(PdfWriter.HideMenubar 
                    | PdfWriter.HideToolbar); // 隱藏菜單欄和工具欄 
            document.open(); 
             
            /** *//**
             * 現在,我們往document的第一頁中加入一些文本內容。
             * 所有的文本都要使用com.lowagie.text.Paragraph才能添加。
             * 可以創建一個默認的paragraph,使用默認的字體,顏色,尺寸等屬性,也可使使用自己定義的字體。
             * 下面分別進行瞭這兩種操作。
             */ 
            document.add(new Paragraph("First page of the document.")); 
            document.add(new Paragraph( 
                            "Some more text on the first page with different color and font type.", 
                            FontFactory.getFont(FontFactory.COURIER, 14, 
                                    Font.BOLD, new Color(255, 150, 200)))); 
 
            /** *//**
             * 接下來,我們往document中添加一些復雜的元素。
             * 讓我們從創建一個新的chapter開始。
             * chapter是一個特殊的部分,它將從新的一頁開始,默認顯示數字序號。
             */ 
            Paragraph title1 = new Paragraph("Chapter 1", FontFactory.getFont( 
                    FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 
                            255))); 
            Chapter chapter1 = new Chapter(title1, 1);  
            chapter1.setNumberDepth(0);  
             
            /** *//**
             * Section是chapter的一個子元素。
             * 在下面的代碼中我們創建瞭一個題為"This is Section 1 in Chapter 1" 的Section。
             * 為瞭在Section下添加文本,我們再創建一個Paragraph對象,將其增加到Section對象中。
             */ 
            Paragraph title11 = new Paragraph("This is Section 1 in Chapter 1", 
                    FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, 
                            new Color(255, 0, 0))); 
            Section section1 = chapter1.addSection(title11); 
            Paragraph someSectionText = new Paragraph( 
                    "This text comes as part of section 1 of chapter 1."); 
            section1.add(someSectionText); 
            someSectionText = new Paragraph("Following is a 3 X 2 table."); 
            section1.add(someSectionText); 
             
            /** *//** 
             * 接著,再創建一個表格(table)對象。
             * 表格中含有一個行和列的矩陣。
             * 一行中的單元格(cell)可以延伸到多列。
             * 同樣的,一列中的單元格可以延伸到多行。
             * 因此,一個3×2的表格不需要6個單元格。
             */ 
            Table t = new Table(3, 2); 
            //設置邊框顏色。如果顏色和背景色一樣,則邊框不會顯示出來 
            t.setBorderColor(Color.white); 
            //設置單元格內文本的間距 
            t.setPadding(5); 
            //設置相鄰單元格的間距 
            t.setSpacing(5); 
            t.setBorderWidth(1); 
             
            /** *//** 
             * 然後,創建3個單元格對象,包含不同的內容。
             * 依次將其放入表格中。
             * 先放在第一行第一列,再放在同一行的下一列中,……
             * 當一行填滿之後,下一個單元格將放在下一行的第一列中。
             * 隻給定單元格的內容(不新建單元格)也可以新增一個單元格,比如t.addCell("1.1");。
             * 最後,將表格添加到Section對象中。
             */ 
            Cell c1 = new Cell("Header1"); 
            //設置單元格邊框顏色,設置方法和表格邊框一樣 
            c1.setBorderColor(Color.WHITE); 
            t.addCell(c1); 
            c1 = new Cell("Header2"); 
            t.addCell(c1); 
            c1 = new Cell("Header3"); 
            t.addCell(c1); 
            t.addCell("1.1"); 
            t.addCell("1.2"); 
            t.addCell("1.3"); 
            section1.add(t); 
 
            /** *//**
             * 接下來,往PDF文檔中添加一個列表(List)。
             * 一個列表包含許多列表項(ListItem)。
             * 列表可以編號也可以不編號。
             * 將List的第一個參數置true表示創建的是一個編號的列表;
             * 第二個參數表示是否使用字母編號,true為使用字母,false為使用數字
             * 第三個參數為縮進值。
             */ 
            List l = new List(true, false, 10); 
            l.add(new ListItem("First item of list")); 
            l.add(new ListItem("Second item of list")); 
            section1.add(l); 
 
            /** *//**
             * 將chapter放入document中。
             * 關閉document。
             */ 
            document.add(chapter1); 
            document.close(); 
        } catch (Exception e) …{ 
            System.out.println(e.getMessage()); 
        } 
    } 

摘自 那年那月那天

發佈留言