Java 实现在word或者pdf上 一页纸打印六块区域数据

    项目中有这样的需求,用户点击导出数据,然后将界面上的数据,打印在一张A4纸上,要求,一页纸有两行三列,每个块固定的格式数据,一开始还真不知道怎么下手,后面同事做了,使用了框架:iText,这个专门用来输出固定格式的word或者pdf,很是强大,不多说了,直接上代码,需要jar包为:itextpdf-5.3.4.jar,itext-asian.jar,如下具体的代码,有注释:


package rms.util.file;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import rms.data.PersonWage;
import rms.util.FileUtil;

import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.List;
import com.lowagie.text.ListItem;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.draw.LineSeparator;

/**
 * 导出PDF 工资条
 * 
 *
 */
public class WageExportPDF {

	private static int sumSize = 0;

	/**
	 * 外部調用的方法
	 * 
	 * @param file
	 * @param heading
	 * @param inscribe
	 * @param table
	 */
	public static void export(File file, String heading,
			ArrayList<PersonWage> personWageList) {
		FileUtil.createFileDire(file.getAbsolutePath());
		heading = heading == null ? "" : heading;
		if (!file.getName().toLowerCase().endsWith(".pdf")) {
			file = new File(file.getAbsolutePath() +File.separator+ "工资.pdf");
		}
		 

		// if (!file.exists()
		// || JOptionPane.OK_OPTION == JOptionPane
		// .showConfirmDialog(null, "档案已经存在,是否要覆盖档案?", "SAVE",
		// JOptionPane.OK_CANCEL_OPTION)) {
		try {
			BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
					BaseFont.NOT_EMBEDDED);

			// BaseFont.createFont(
			// "c:\\windows\\fonts\\msjh.ttf", BaseFont.IDENTITY_H,
			// BaseFont.NOT_EMBEDDED);
			Font fontChinese = new Font(font, 12, Font.BOLD);
			Rectangle rect = new Rectangle(840F, 590F);
			Document doc = new Document(rect, 10, 10, 10, 10);
			// 基本设置
			PdfWriter pdfWriter = PdfWriter.getInstance(doc,
					new FileOutputStream(file));
			pdfWriter.setPdfVersion(PdfWriter.PDF_VERSION_1_2);

			doc.open();

			createBody(heading, fontChinese, doc, pdfWriter, personWageList);

			doc.close();
			pdfWriter.close();
			// int dialog = JOptionPane.showConfirmDialog(null,
			// "表格导出成功,是否现在打开?", "提示", JOptionPane.YES_NO_OPTION);
			// if (dialog == JOptionPane.YES_OPTION) {
			// Runtime.getRuntime().exec(
			// "cmd /c start \"\" \"" + file + "\"");
			// }
		} catch (Exception ex) {
			ex.printStackTrace();
			// JOptionPane.showMessageDialog(null, "导出pdf失败");
		}
		// }
	}

	private static void createBody(String heading, Font fontChinese,
			Document doc, PdfWriter pdfWriter,
			ArrayList<PersonWage> personWageList) throws DocumentException,
			Exception {
		int dataIndex = 0;
		while (sumSize < personWageList.size()) {
			createTitle(heading, fontChinese, doc);
			doc.add(createTable(personWageList, dataIndex));
			doc.newPage();
			pdfWriter.setPageEmpty(false);
		}
	}

	private static void createTitle(String heading, Font fontChinese,
			Document doc) throws DocumentException {
		List listText = new List(false);
		listText.setListSymbol("");
		ListItem firstItem = new ListItem(heading, fontChinese);
		firstItem.setSpacingBefore(10);
		firstItem.setAlignment(1);
		listText.add(firstItem);
		doc.add(listText);
		// Paragraph p1 = new Paragraph();
		// p1.add(new Chunk(new LineSeparator()));
		// doc.add(p1);
	}

	private static Table createTable(ArrayList<PersonWage> personWageList,
			int dataIndex) throws Exception {
		BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
				BaseFont.NOT_EMBEDDED);
		Font fontChinese = new Font(font, 12, Font.NORMAL);

		int colNum = 3;
		int rowNum = 2;
		Table tableTop = new Table(colNum, rowNum);
		tableTop.setWidth(100);
		tableTop.setPadding(1);
		tableTop.setBorder(Rectangle.NO_BORDER);

		for (int row = 0; row < rowNum; row++) {
			for (int col = 0; col < colNum; col++) {
				try {
					PersonWage personWage = personWageList.get(sumSize);
					Cell ce = new Cell();
					// ce.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
					createItem(fontChinese, ce, personWage);
					ce.setBorderWidth(0);
					tableTop.addCell(ce);
					dataIndex++;
					sumSize++;
				} catch (Exception ex) {
					System.out.println("data not enough!");
				}
			}
		}
		dataIndex = 0;

		return tableTop;
	}

	private static void createItem(Font fontChinese, Cell cell,
			PersonWage personWage) {
		Paragraph titleParagraph = new Paragraph();
		titleParagraph.setAlignment(Paragraph.ALIGN_CENTER);
		titleParagraph.setFont(fontChinese);
		titleParagraph.add(new Chunk("测试"));
		titleParagraph.add(Chunk.NEWLINE);
		cell.add(titleParagraph);

		Paragraph topLineSeparator = new Paragraph();
		topLineSeparator.setAlignment(Paragraph.ALIGN_LEFT);
		topLineSeparator.add(new Chunk(new LineSeparator()));
		topLineSeparator.add(Chunk.NEWLINE);
		cell.add(topLineSeparator);

		Paragraph info = new Paragraph();
		info.setIndentationLeft(10);
		info.setFont(fontChinese);
		info.add(new Chunk("测试"));
		info.add(new Chunk("                        "));
		info.add(new Chunk("测试"));
		info.add(Chunk.NEWLINE);
		cell.add(info);

		Paragraph info1 = new Paragraph();
		info1.setIndentationLeft(10);
		info1.setFont(fontChinese);
		info1.add(new Phrase("测试 "));
		info1.add(new Chunk("            "));
		info1.add(new Phrase("序号: 1"));
		info1.add(Chunk.NEWLINE);
		cell.add(info1);

		Paragraph info2 = new Paragraph();
		info2.setIndentationLeft(10);
		info2.setFont(fontChinese);
		info2.add(new Chunk("测试"));
		info2.add(Chunk.NEWLINE);
		cell.add(info2);

		Paragraph info3 = new Paragraph();
		info3.setIndentationLeft(10);
		info3.setFont(fontChinese);
		info3.add(new Chunk("测试"));
		info3.add(Chunk.NEWLINE);
		cell.add(info3);

		Paragraph info4 = new Paragraph();
		info4.setFont(fontChinese);
		info4.add(new Chunk("测试"));
		info4.add(Chunk.NEWLINE);
		cell.add(info4);

		Paragraph lineSeparator = new Paragraph();
		lineSeparator.setAlignment(Paragraph.ALIGN_LEFT);
		lineSeparator.add(new Chunk(new LineSeparator()));
		lineSeparator.add(Chunk.NEWLINE);
		cell.add(lineSeparator);

		Paragraph info5 = new Paragraph();
		info5.setFont(fontChinese);
		info5.add(new Chunk("测试:"));
		info5.add(Chunk.NEWLINE);
		cell.add(info5);

		Paragraph info6 = new Paragraph();
		info6.setFont(fontChinese);
		info6.add(new Chunk(
				"测试"));
		info6.add(Chunk.NEWLINE);
		cell.add(info6);

		Paragraph info7 = new Paragraph();
		info7.setFont(fontChinese);
		info7.add(new Chunk("测试"));
		info7.add(new Chunk("                        "));
		info7.add(new Chunk("测试"));
		info7.add(Chunk.NEWLINE);
		cell.add(info7);

		Paragraph lineParagraph = new Paragraph();
		lineParagraph.add(Chunk.NEWLINE);
		lineParagraph.add(Chunk.NEWLINE);
		cell.add(lineParagraph);
	}

	public static void main(String[] args) {
		String filePath = "D:\\TEST";
		File file = new File(filePath);
		ArrayList<PersonWage> personWageList = new ArrayList<PersonWage>();
		personWageList.add(new PersonWage());
		personWageList.add(new PersonWage());
		personWageList.add(new PersonWage());
		personWageList.add(new PersonWage());
		personWageList.add(new PersonWage());
		personWageList.add(new PersonWage());
		personWageList.add(new PersonWage());
		export(file, "测试", personWageList);
	}

}

================分割线,2016年12月15日17:56:41==============================

     一般输出pdf,其实是为了财务能将A4纸一些工资或者用户的东西进行裁剪,这就需要保证如果是两行两列,每行的高度需要固定,才能在指定的高度处进行裁剪,经过查找资料,原来的Cell类并没有提供固定高度的方法,只有pdfPcell可以的,如下示例代码设置A-Z26行,5列的表格,设置其中某些列为特殊高度:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import sandbox.WrapToTest;

@WrapToTest
public class FixedHeightCell {

	public static final String DEST = "results/tables/fixed_height_cell.pdf";

	public static void main(String[] args) throws IOException,
			DocumentException {
		File file = new File(DEST);
		file.getParentFile().mkdirs();
		new FixedHeightCell().createPdf(DEST);
	}

	public void createPdf(String dest) throws IOException, DocumentException {
		Document document = new Document();
		PdfWriter.getInstance(document, new FileOutputStream(dest));
		document.open();
		PdfPTable table = new PdfPTable(3);//3代表几列的意思
		table.setWidthPercentage(100);
		PdfPCell cell;
		for (int r = 1; r <= 2; r++) {
			for (int c = 1; c <= 3; c++) {
				cell = new PdfPCell();
				cell.addElement(new Paragraph(String.valueOf((char) r)
						+ String.valueOf(c)));
				
				cell.setFixedHeight(285);// 控制每个输出的高度为A4纸上的一半高度
					
				}
				table.addCell(cell);
			}
		}
		document.add(table);
		document.close();
	}
}

         参考的连接如下:http://developers.itextpdf.com/examples/tables-itext5/cell-heights,http://stackoverflow.com/questions/8266554/itext-set-cells-height,http://stackoverflow.com/questions/25279646/how-to-set-height-of-pdfptable-in-itextsharp。

        要注意的是:PdfPTable table = new PdfPTable(3);// 设置一行几列,然后循环遍历两次,就可以在一张A4纸上打印两行三列

    2017年3月17日15:46:47:更新,要有缩进的话,用如下代码:

Cell cell = new Cell();
Paragraph titleParagraph = new Paragraph();
titleParagraph.setAlignment(Paragraph.ALIGN_CENTER);
titleParagraph.setIndentationLeft(5);// 调整每个的间距:Indentation缩进
titleParagraph.setFont(fontChinese);

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:C马雯娟 返回首页