java使用IText生成表格到PDF中

 

1.生成pdf的表格

package com.me.test;

import java.awt.Color;
import java.io.FileOutputStream;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

/**
 * 生成表格到硬盘
 * 
 * @author admin
 * 
 */
public class ITextTest {
	public void getTable(){
		try {
			Document document = new Document(PageSize.A4, 20, 20, 20, 20);
			PdfWriter writer = PdfWriter.getInstance(document,
					new FileOutputStream("f:/IText/table.pdf"));
			document.open();

			BaseFont bfChinese;
			bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
					false);
			Font fontChinese = new Font(bfChinese, 9, Font.BOLD, Color.black);

			Table t = new Table(12, 2);
			// t.setBorderColor(new Color(220, 255, 100));
			int width[] = { 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, };
			t.setWidths(width);

			t.setWidth(100); // 占页面宽度 %
			t.setPadding(1);
			t.setSpacing(0);
			t.setBorderWidth(2);

			Cell c1 = new Cell("header1");
			t.addCell(c1);
			c1 = new Cell("Header2");
			t.addCell(c1);
			c1 = new Cell("Header3");
			t.addCell(c1);
			c1 = new Cell("Header4");
			t.addCell(c1);
			c1 = new Cell("Header5");
			t.addCell(c1);
			c1 = new Cell("Header6");
			t.addCell(c1);
			c1 = new Cell("Header7");
			t.addCell(c1);
			c1 = new Cell("Header8");
			t.addCell(c1);
			c1 = new Cell("Header9");
			t.addCell(c1);
			c1 = new Cell("Header10");
			t.addCell(c1);
			c1 = new Cell("Header11");
			t.addCell(c1);
			c1 = new Cell("Header12");
			t.addCell(c1);

			int k = 0;
			while (k < 3) {
				for (int q = 0; q < 12; q++) {
					Paragraph par = new Paragraph(k + "-" + q, fontChinese);
					c1 = new Cell(par);
					c1.setHorizontalAlignment(Element.ALIGN_CENTER);
					t.addCell(c1);
				}
				k++;
			}

			for (int i = 0; i < 24; i++) {
				String num = Integer.toString(i);
				c1.setHorizontalAlignment(Element.ALIGN_CENTER);
				c1 = new Cell(num);
				c1.setColspan(2);
				c1.setRowspan(1);
				t.addCell(c1);
			}
			
			c1 = new Cell("26");
			t.addCell(c1);
			document.add(t);
			// 创建一个新页面
			document.newPage();
			document.add(t);
			document.close();
		} catch (Exception e2) {
			e2.printStackTrace();
		}
		
	}

}

 2.将网页中的信息,用pdf格式文件弹出

package com.me.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
/**
 * 在网页上获取信息,查看pdf格式文件
 * @author admin
 *
 */
public class PdfServlet extends HttpServlet {
 
    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        try {
            // Get the text that will be added to the PDF
            String text = request.getParameter("text");
            if (text == null || text.trim().length() == 0) {
                 text = "You didn't enter any text.";
            }
            // step 1
            Document document = new Document();
            // step 2
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);
            // step 3
            document.open();
            // step 4
            document.add(new Paragraph(String.format(
                "You have submitted the following text using the %s method:",
                request.getMethod())));
            document.add(new Paragraph(text));
            // step 5
            document.close();
 
            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            // setting the content type
            response.setContentType("application/pdf");
            // the contentlength
            response.setContentLength(baos.size());
            // write ByteArrayOutputStream to the ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();
        }
        catch(DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }
 
    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 6067021675155015602L;
 
}

 3.在网页上直接以pdf的形式显示

package com.me.test;

import java.io.IOException;



import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfPTable;


/**
 * 直接在网页中生成PDF格式 查看
 */
/**
 * Hello World example as a Servlet.
 *
 * @author blowagie
 */
public class HelloWorldServlet extends HttpServlet {  
    /**
	 * 
	 */
	private static final long serialVersionUID = 3710911016238241119L;

	/**
     * Returns a PDF, RTF or HTML document.
     *
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public void doGet (HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
          System.out.println("document.add(BigTable)");
  // step1
  Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);  //定义纸张类型及方向,页边距
       
        // step 1
       
        try {
            // step 2: we set the ContentType and create an instance of the corresponding Writer
                response.setContentType("application/pdf");
                PdfWriter.getInstance(document, response.getOutputStream());
   // step3
   document.open();
   // step4 定义表格填充内容
   String[] bogusData = { "M0065920", "SL", "FR86000P", "PCGOLD",
     "119000", "96 06", "2001-08-13", "4350", "6011648299",
     "FLFLMTGP", "153", "119000.00" };
   int NumColumns = 12; //定义表格列数



   PdfPTable datatable = new PdfPTable(NumColumns); //创建新表.
   int headerwidths[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 }; // percentage 定义表格头宽度
   datatable.setWidths(headerwidths);
   datatable.setWidthPercentage(100); // percentage
   datatable.getDefaultCell().setPadding(3);
   datatable.getDefaultCell().setBorderWidth(2);
   datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
   //以下是填充表头
   datatable.addCell("Clock #");
   datatable.addCell("Trans Type");
   datatable.addCell("Cusip");
   datatable.addCell("Long Name");
   datatable.addCell("Quantity");
   datatable.addCell("Fraction Price");
   datatable.addCell("Settle Date");
   datatable.addCell("Portfolio");
   datatable.addCell("ADP Number");
   datatable.addCell("Account ID");
   datatable.addCell("Reg Rep ID");
   datatable.addCell("Amt To Go ");



   datatable.setHeaderRows(1); // this is the end of the table header



   datatable.getDefaultCell().setBorderWidth(1);
   for (int i = 1; i < 750; i++) {
    if (i % 2 == 1) {
     datatable.getDefaultCell().setGrayFill(0.9f);
    }
    for (int x = 0; x < NumColumns; x++) {
     datatable.addCell(bogusData[x]);
    }
    if (i % 2 == 1) {
     datatable.getDefaultCell().setGrayFill(0.0f);
    }
   }
   document.add(datatable);  //加载新表
        }
        catch(DocumentException de) {
            de.printStackTrace();
            System.err.println("document: " + de.getMessage());
        }
       
        // step 5: we close the document (the outputstream is also closed internally)
        document.close();
    }
}

  4.生成PDF到计算机中

package com.me.test;

import java.awt.*;
import java.io.*;

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
/**
 * 通过给定的短语生成pdf文件,并且加密
 */
/**
 * First iText example: Hello World.
 */
public class HelloWorld {

	/** Path to the resulting PDF file. */
	public static final String RESULT = "f:/hello.pdf";
	public static final String pwd = "123456";
	public static final String result = "f:/Itext/b.gif";

	/**
	 * Creates a PDF file: hello.pdf
	 * 
	 * @param args
	 *            no arguments needed
	 */
	public static void main(String[] args) throws DocumentException,
			IOException {
		new HelloWorld().createPdf(RESULT);
	}

	/**
	 * Creates a PDF document.
	 * 
	 * @param filename
	 *            the path to the new PDF document
	 * @throws DocumentException
	 * @throws IOException
	 */
	public void createPdf(String filename) throws DocumentException,
			IOException {
		// 设定文本样式
		Rectangle rec = new Rectangle(PageSize.A4);
		rec.setBackgroundColor(Color.GRAY);
		rec.setBorder(Rectangle.TOP);
		rec.setBorderColor(Color.black);
		rec.setBorderWidth(50);
		// 创建本文
		Document doc = new Document(rec, 100, 201, 20, 20);
		// 设定路径
		PdfWriter pdf = PdfWriter.getInstance(doc, new FileOutputStream(
				HelloWorld.RESULT));
		// 设定布局
		pdf.setViewerPreferences(PdfWriter.PageModeUseThumbs
				| PdfWriter.PageLayoutTwoColumnLeft | PdfWriter.HideMenubar);
		// 加密
		pdf.setEncryption(pwd.getBytes(), pwd.getBytes(), PdfWriter.ALLOW_COPY
				| PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_40);
		// 设置中文
		BaseFont base = null;
		Font fontChinese = null;
		try {
			base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
					BaseFont.EMBEDDED);
			fontChinese = new Font(base, 18, Font.BOLD);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		doc.open();

		doc.add(new Paragraph("你好我是Pro", fontChinese));

		doc.close();
	}
}

 

你可能感兴趣的:(itext)