iText导出PDF经典实现

匿名 (未验证) 提交于 2019-12-03 00:26:01
原文地址为:iText导出PDF经典实现

POIEXCELPDFiTextiText

iText iTextPDFjavaiTextjavajava ServletiTextPDFServlet:http://www.lowagie.com/iText/ 2.0.7

POIhttp://blog.csdn.net/lenotang/archive/2008/08/24/2823230.aspx Student.java Book.java

package org.leno.export.util;

import java.io.UnsupportedEncodingException;

public class StrHelp {

public static String getChinese(String s) {

try {

return new String(s.getBytes("gb2312"), "iso-8859-1");

} catch (UnsupportedEncodingException e) {

return s;

}

}

}

package org.leno.export.util;

import java.io.IOException;

import com.lowagie.text.*;

import com.lowagie.text.pdf.BaseFont;

public class PdfParagraph extends Paragraph {

private static final long serialVersionUID = -244970043180837974L;

public PdfParagraph(String content) {

super(content, getChineseFont(12, false));

}

public PdfParagraph(String content, int fontSize, boolean isBold) {

super(content, getChineseFont(fontSize, isBold));

}

// -

protected static Font getChineseFont(int nfontsize, boolean isBold) {

BaseFont bfChinese;

Font fontChinese = null;

try {

bfChinese = BaseFont.createFont("c://windows//fonts//simsun.ttc,1",

BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

if (isBold) {

fontChinese = new Font(bfChinese, nfontsize, Font.BOLD);

} else {

fontChinese = new Font(bfChinese, nfontsize, Font.NORMAL);

}

} catch (DocumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return fontChinese;

}

//

protected Cell ChangeCell(String str, int nfontsize, boolean isBold)

throws IOException, BadElementException, DocumentException {

Phrase ph = ChangeChinese(str, nfontsize, isBold);

Cell cell = new Cell(ph);

// cell.setBorderWidth(3);

return cell;

}

//

protected Chunk ChangeChunk(String str, int nfontsize, boolean isBold)

throws IOException, BadElementException, DocumentException {

Font FontChinese = getChineseFont(nfontsize, isBold);

Chunk chunk = new Chunk(str, FontChinese);

return chunk;

}

//

protected Phrase ChangeChinese(String str, int nfontsize, boolean isBold)

throws IOException, BadElementException, DocumentException {

Font FontChinese = getChineseFont(nfontsize, isBold);

Phrase ph = new Phrase(str, FontChinese);

return ph;

}

}

iText

package org.leno.export.util;

import java.io.*;

import java.lang.reflect.*;

import java.util.*;

import com.lowagie.text.*;

import com.lowagie.text.pdf.*;

import java.awt.Color;

import javax.swing.JOptionPane;

import java.net.MalformedURLException;

import java.text.SimpleDateFormat;

/**

* IText 2.0.7 PDF

*

* @author leno

* @version v1.0

* @param <T>

*javabean

*booleanxxxgetgetXxx(),isXxx()

*byte[],

*/

public class ExportPdf<T> {

public void exportPdf(Collection<T> dataset, OutputStream out) {

exportPdf("iTextPDF", null, dataset, out, "yyyy-MM-dd");

}

public void exportPdf(String[] headers, Collection<T> dataset,

OutputStream out) {

exportPdf("iTextPDF", headers, dataset, out, "yyyy-MM-dd");

}

public void exportPdf(String[] headers, Collection<T> dataset,

OutputStream out, String pattern) {

exportPdf("iTextPDF", headers, dataset, out, pattern);

}

/**

* JAVAJAVAPDF IO

*

* @param title

*

* @param headers

*

* @param dataset

*,javabean

*javabeanString,Date,byte[]()

* @param out

*PDF

* @param pattern

*"yyy-MM-dd"

*/

@SuppressWarnings("unchecked")

public void exportPdf(String title, String[] headers,

Collection<T> dataset, OutputStream out, String pattern) {

// PDF

Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4

// rectPageSize = rectPageSize.rotate();// A4

Document document = new Document(rectPageSize, 50, 50, 50, 50);// 44

try {

// PDFoutIO

PdfWriter.getInstance(document, out);

//

document.addTitle(StrHelp.getChinese(title));

document.addSubject("export information");

document.addAuthor("leno");

document.addCreator("leno");

document.addKeywords("pdf itext");

//

HeaderFooter header = new HeaderFooter(new PdfParagraph(title, 20,

true), false);

header.setAlignment(Element.ALIGN_CENTER);

HeaderFooter footer = new HeaderFooter(new Phrase(

"Thisispage"), new Phrase("."));

footer.setAlignment(Element.ALIGN_CENTER);

document.setHeader(header);

document.setFooter(footer);

// PDF

document.open();

// TablePdfPTable

// Table table = new Table(headers.length);

// table.setWidth(16*headers.length);

// //table.setWidths(new float[]{20,20,20,30});

// table.setCellsFitPage(true);

// table.setAutoFillEmptyCells(true);

// table.setAlignment(Table.ALIGN_CENTER);

// table.setBackgroundColor(Color.yellow);

// table.setBorderColor(Color.green);

PdfPTable table = new PdfPTable(headers.length);

// table.setHorizontalAlignment(Element.ALIGN_CENTER);

table.setWidthPercentage(16 * headers.length);

//

for (int i = 0; i < headers.length; i++) {

PdfPCell cell = new PdfPCell(new PdfParagraph(headers[i], 14,

true));

cell.setHorizontalAlignment(Cell.ALIGN_CENTER);

cell.setVerticalAlignment(Cell.ALIGN_MIDDLE);

cell.setBackgroundColor(Color.cyan);

cell.setBorderColor(Color.green);

table.addCell(cell);

}

//

Iterator<T> it = dataset.iterator();

int index = 0;

while (it.hasNext()) {

index++;

T t = (T) it.next();

// javabeangetXxx()

Field[] fields = t.getClass().getDeclaredFields();

for (short i = 0; i < fields.length; i++) {

PdfPCell cell = null;

Field field = fields[i];

String fieldName = field.getName();

String getMethodName = "get"

+ fieldName.substring(0, 1).toUpperCase()

+ fieldName.substring(1);

try {

Class tCls = t.getClass();

Method getMethod = tCls.getMethod(getMethodName,

new Class[] {});

Object value = getMethod.invoke(t, new Object[] {});

//

String textValue = null;

if (value instanceof Boolean) {

boolean bValue = (Boolean) value;

textValue = "";

if (!bValue) {

textValue = "";

}

} else if (value instanceof Date) {

Date date = (Date) value;

SimpleDateFormat sdf = new SimpleDateFormat(pattern);

textValue = sdf.format(date);

} else if (value instanceof byte[]) {

byte[] bsValue = (byte[]) value;

Image img = Image.getInstance(bsValue);

cell = new PdfPCell(img);

} else {

textValue = value.toString();

}

// ,

if (textValue != null) {

cell = new PdfPCell(new PdfParagraph(textValue));

}

cell.setHorizontalAlignment(Cell.ALIGN_CENTER);

cell.setVerticalAlignment(Cell.ALIGN_MIDDLE);

cell.setBorderColor(Color.green);

table.addCell(cell);

} catch (SecurityException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (NoSuchMethodException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (MalformedURLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

//

}

}

}

document.add(table);

document.close();

} catch (DocumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static void main(String[] args) {

//

ExportPdf<Student> ex = new ExportPdf<Student>();

String[] headers = { "", "", "", "", "" };

java.util.List<Student> dataset = new ArrayList<Student>();

dataset.add(new Student(10000001, "", 20, true, new Date()));

dataset.add(new Student(20000002, "", 24, false, new Date()));

dataset.add(new Student(30000003, "", 22, true, new Date()));

//

ExportPdf<Book> ex2 = new ExportPdf<Book>();

String[] headers2 = { "", "", "", "", "ISBN",

"", "" };

java.util.List<Book> dataset2 = new ArrayList<Book>();

try {

BufferedInputStream bis = new BufferedInputStream(

new FileInputStream("book.jpg"));

byte[] buf = new byte[bis.available()];

while ((bis.read(buf)) != -1) {

//

}

dataset2.add(new Book(1, "jsp", "leno", 300.33f , "1234567",

"", buf));

dataset2.add(new Book(2, "java", "brucl", 300.33f , "1234567",

"", buf));

dataset2.add(new Book(3, "DOM", "lenotang", 300.33f , "1234567",

"", buf));

dataset2.add(new Book(4, "c++", "leno", 400.33f , "1234567",

"", buf));

dataset2.add(new Book(5, "c#", "leno", 300.33f , "1234567",

"", buf));

OutputStream out = new FileOutputStream("E://a.pdf");

OutputStream out2 = new FileOutputStream("E://b.pdf");

ex.exportPdf(headers, dataset, out);

ex2.exportPdf(headers2, dataset2, out2);

out.close();

out2.close();

JOptionPane.showMessageDialog(null, "pdf!");

System.out.println("pdf");

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

iTextweb

API


转载请注明本文地址:iText导出PDF经典实现
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!