工作中有需求需要将回单进行绘制生成pdf以便打印,所以记录下来
准备工作:
相关jar包:
示例:
iText-2.1.7.jar //核心jar
字体包:
iTextAsian.jar
iTextAsianCmaps.jar
ps:不同版本的iText的功能有所差异
Java类示例:
package com.test;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
public class TestCreatePdf {
public static void main(String[] args) throws Exception {
try {
String FileName = "C:\\Users\\Administrator.SC-201606041031\\Desktop\\test.pdf";
Map map = getMap();
File srcFile = new File(FileName);
byte[] fileByte = new byte[1024];
FileName = srcFile.getName();
BufferedInputStream bufferedInputStream;
bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFile));
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (bufferedInputStream.read(fileByte) != -1) {
out.write(fileByte);
}
BaseFont bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//创建字体
Font font = new Font(bf,9,Font.BOLD);//使用字体
Font font1 = new Font(bf,8);//使用字体
Font font2 = new Font(bf,12,Font.BOLD);//使用字体
Document document = new Document();
PdfWriter.getInstance(document, out);
try {
document.open();
Image image = Image.getInstance("C:\\Users\\Administrator.SC-201606041031\\Desktop\\101.png");
//获取印章图片路径
Image image1 = Image.getInstance("C:\\Users\\Administrator.SC-201606041031\\Desktop\\101.png");
image.setAlignment(Image.ALIGN_LEFT);
image.scaleAbsolute(200f, 30f);
image1.setAlignment(Image.ALIGN_LEFT);
image1.scaleAbsolute(75, 55);
float[] widths = {15f,25f,15f ,25f,15f,25f};// 设置表格的列宽和列数 默认是6列
float[] midWidths = {15f,30f,15f,30f};
PdfPTable table = new PdfPTable(widths);
table.setSpacingBefore(20f);
table.setWidthPercentage(100);
float[] widths1 = {10f,10f,40f ,10f,10f,40f};
PdfPTable table1 = new PdfPTable(widths1);
table1.setSpacingBefore(20f);
table1.setWidthPercentage(100);// 设置表格宽度为100%
// 第一行
// 第一行
PdfPCell cell = null;
cell = new PdfPCell(image);//
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_CENTER); //单元垂直对齐方式
cell.setBorderWidth(0);
cell.setPaddingBottom(15);
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("电子回单",font2));