天天看點

itext 添加

存檔備份。

    研究了好幾天用itext生成word目錄,在别人的指導下終于做到了這一步:生成标題格式和樣式。在生成好的word文檔中還要手工生成,插入->引用->索引和目錄->目錄。如果那位能直接生成目錄省去手工操作請指教。我用的包是iText-2.1.7.jar和iText-rtf-2.1.7.jar兩個。下面是例子: 

package com.zfsoft.test; 

import java.io.FileNotFoundException; 

import java.io.FileOutputStream; 

import com.lowagie.text.Document; 

import com.lowagie.text.DocumentException; 

import com.lowagie.text.Element; 

import com.lowagie.text.Font; 

import com.lowagie.text.PageSize; 

import com.lowagie.text.Paragraph; 

import com.lowagie.text.rtf.RtfWriter2; 

import com.lowagie.text.rtf.style.RtfParagraphStyle; 

public class Test2 { 

public static void main(String[] args) throws DocumentException, FileNotFoundException { 

Document document = new Document(PageSize.A4.rotate()); 

RtfWriter2.getInstance(document, new FileOutputStream("d:\\test.doc")); 

document.open(); 

Font titleFont = new Font(Font.NORMAL,16, Font.BOLD); 

/* 設定标題1格式 */ 

RtfParagraphStyle rtfGsBt1 = RtfParagraphStyle.STYLE_HEADING_1; 

rtfGsBt1.setAlignment(Element.ALIGN_CENTER); 

rtfGsBt1.setStyle(Font.BOLD); 

rtfGsBt1.setSize(14); 

/* 設定标題2格式 */ 

RtfParagraphStyle rtfGsBt2 = RtfParagraphStyle.STYLE_HEADING_2; 

rtfGsBt2.setAlignment(Element.ALIGN_LEFT); 

rtfGsBt2.setStyle(Font.NORMAL); 

rtfGsBt2.setSize(12); 

Paragraph title = new Paragraph("測試"); 

title.setAlignment(Element.ALIGN_CENTER); 

title.setFont(titleFont); 

document.add(title); 

//正文 

title = new Paragraph("1.第一章"); 

title.setFont(rtfGsBt1); 

title = new Paragraph("1.1 第一節"); 

title.setFont(rtfGsBt2); 

title = new Paragraph("1.2 第二節"); 

title = new Paragraph("2.第二章"); 

title = new Paragraph("2.1 第一節"); 

title = new Paragraph("2.2 第二節"); 

document.close(); 

繼續閱讀