最近公司有需求,希望生成pdf文档并打印。最近研究了一下itext生成pdf方面的东西。

首先我是用的maven,配置好依赖,我准备使用JFREECHART生成图表,ITEXT生成pdf

生成的pdf:

程序生成了几个矩形作为几个区域,用jfreechart生成了图表,最后讲每个区域拼合形成整个pdf。
首先生成一个pdf文档

Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();

由于某些服务器没有中文字体,需要自行安装中文字体。
我是这样解决的。

	
	public final String CHINESE_FONT;
	public final BaseFont BASE_FONT;
	public final Font fontBigTitle;
	public final Font fontSmallTitle;
	public final Font fontText;
	public final Font fontTextUnderLine;
	public final Font fontTextBold;
	public final java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat("0.00");
	public final SimpleDateFormat yyyyMMDDFormat = new SimpleDateFormat("yyyy-MM-dd");
	public final SimpleDateFormat yyyyMMDDHHmmssFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public final SimpleDateFormat HHmmssFormat = new SimpleDateFormat("HH:mm:ss");


	public PDFUtils(String font) throws DocumentException, IOException {
		CHINESE_FONT = font;
		BASE_FONT = BaseFont.createFont(CHINESE_FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		fontBigTitle = new Font(BASE_FONT, 22, Font.BOLD);
		fontSmallTitle = new Font(BASE_FONT, 10, Font.BOLD);
		fontText = new Font(BASE_FONT, 8, Font.NORMAL);
		fontTextUnderLine = new Font(BASE_FONT, 8, Font.UNDERLINE | Font.NORMAL);
		fontTextBold = new Font(BASE_FONT, 8, Font.BOLD);
	}

调用的时候

String font = servletRailPath + "fonts/NotoSansCJKsc-Regular.otf";
new PDFUtils(font)

设置好标题和字体并增加到pdf

	Paragraph t = new Paragraph("标题", 
       new com.itextpdf.text.Font.Font(BASE_FONT, 22, Font.BOLD););
t.setAlignment(Element.ALIGN_CENTER);
document.add(t);

计算位置并画出一个方块,这部分代码可以封装成几个方法自动画出每一块。

	
Rectangle rectangle = drawAndSetRetangle(700, 760, writer);

public Rectangle drawAndSetRetangle(int startY, int endY, PdfWriter writer) {
		drawRectangle(startY, endY, writer);
		return setRectangle(startY, endY, writer);
}

将文字限定在刚画的矩形内

	
ColumnText ct = new ColumnText(writer.getDirectContent());
ct.setSimpleColumn(rectangle);

之后就可以新建段落,并添加文字,增加到矩形内了

	
Paragraph paragraph = new Paragraph();
paragraph.setLeading(12f);
paragraph.setFont(fontSmallTitle);
paragraph.add("xxxx \n");
paragraph.add("xxxx");
ct.addElement(paragraph);
ct.go();

按照如上步骤增加几个区域,之后pdf就生成好了。
最后不要忘了

document.close();

然后就可以去查看pdf的效果了。
以下是我封装的几个常用方法

        /**
	 * @param paragraph
	 */
	public void addDefaultSpace(Paragraph paragraph) {
		addSpace(paragraph, 5);
	}

	public void addTextAndSpaceWithUnderLine(Paragraph paragraph, String text, int length) {
		int textLength = 0;
		try {
			for (int i = 0; i < text.length(); i++) {
				char temp = text.charAt(i);
				if ((temp >= '0' && temp <= '9') || (temp >= 'a' && temp <= 'z') || (temp >= 'A' && temp <= 'Z')) {
					textLength += 2;
				} else {
					textLength += 4;
				}
			}
			length -= textLength;
			addUnderLineText(paragraph, text);
			addSpaceWithUnderLine(paragraph, length);
		} catch (Exception e) {
			addSpaceWithUnderLine(paragraph, length);
		}

	}

	public void addBoldText(Paragraph paragraph, String text) {
		paragraph.setFont(fontTextBold);
		paragraph.add(text);
		paragraph.setFont(fontText);
	}

	public void addNormalText(Paragraph paragraph, String text) {
		paragraph.setFont(fontText);
		paragraph.add(text);
		paragraph.setFont(fontText);
	}

	public void addUnderLineText(Paragraph paragraph, String text) {
		paragraph.setFont(fontTextUnderLine);
		paragraph.add(text);
		paragraph.setFont(fontText);
	}

	public void addSpaceWithUnderLine(Paragraph paragraph, int amonut) {
		paragraph.setFont(fontTextUnderLine);
		for (int i = 0; i < amonut; i++) {
			paragraph.add("\u00a0");
		}
		paragraph.setFont(fontText);
	}

	public void addSpace(Paragraph paragraph, int amonut) {
		paragraph.setFont(fontText);
		for (int i = 0; i < amonut; i++) {
			paragraph.add("\u00a0");
		}
		paragraph.setFont(fontText);
	}

	public void drawRectangle(int startY, int endY, PdfWriter writer) {
		PdfContentByte canvas = writer.getDirectContent();
		canvas.setColorFill(BaseColor.BLACK);
		canvas.moveTo(20, startY);
		canvas.lineTo(20, endY);
		canvas.lineTo(575, endY);
		canvas.lineTo(575, startY);
		canvas.lineTo(20, startY);
		canvas.closePathStroke();
	}

	public Rectangle setRectangle(int startY, int endY, PdfWriter writer) {
		Rectangle r = new Rectangle(25, startY, 575, endY);
		PdfContentByte canvas = writer.getDirectContent();
		canvas.setColorFill(BaseColor.BLACK);
		canvas.rectangle(r);
		canvas.stroke();
		return r;
	}

	public Rectangle drawAndSetRetangle(int startY, int endY, PdfWriter writer) {
		drawRectangle(startY, endY, writer);
		return setRectangle(startY, endY, writer);
	}

maven配置如下:

  
        
            com.itextpdf
            itextpdf
            5.5.8
        

        
            com.itextpdf
            itext-pdfa
            5.5.8
        

        
            com.itextpdf
            itext-xtra
            5.5.8
        

        
            com.itextpdf.tool
            xmlworker
            5.5.8
        

        
            com.itextpdf
            itext-asian
            5.2.0
        
        
            org.jfree
            jfreechart
            1.0.19
        


Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required