利用itext生成pdf表格(java)

利用itext生成pdf表格(java)

package com.test.generator;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfGenerator {
	
	static BaseFont bfSun = null;
	static {
        try {
        	//引入字体库
        	 bfSun = BaseFont.createFont("templates/font/simhei.ttf", BaseFont.IDENTITY_H, 				         				BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
    
    //合成多个pdf文件为一个
	public static InputStream concatPDFs(List<InputStream> streamOfPDFFiles, boolean paginate) {
        Document document = new Document();
        ByteArrayOutputStream productOutputStream = null;
        try {
            List<InputStream> pdfs = streamOfPDFFiles;
            List<PdfReader> readers = new ArrayList<>();
            int totalPages = 0;
            Iterator<InputStream> iteratorPDFs = pdfs.iterator();

            // Create Readers for the pdfs.
            while (iteratorPDFs.hasNext()) {
                InputStream pdf = iteratorPDFs.next();
                PdfReader pdfReader = new PdfReader(pdf);
                readers.add(pdfReader);
                totalPages += pdfReader.getNumberOfPages();
            }
            // Create a writer for the outputstream
            productOutputStream = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, productOutputStream);

            document.open();
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                    BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
            // data

            PdfImportedPage page;
            int currentPageNumber = 0;
            int pageOfCurrentReaderPDF = 0;
            Iterator<PdfReader> iteratorPDFReader = readers.iterator();

            // Loop through the PDF files and add to the output.
            while (iteratorPDFReader.hasNext()) {
                PdfReader pdfReader = iteratorPDFReader.next();

                // Create a new page in the target for each source page.
                while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                    document.newPage();
                    pageOfCurrentReaderPDF++;
                    currentPageNumber++;
                    page = writer.getImportedPage(pdfReader,
                            pageOfCurrentReaderPDF);
                    cb.addTemplate(page, 0, 0);

                    // Code for pagination.
                    if (paginate) {
                        cb.beginText();
                        cb.setFontAndSize(bf, 9);
                        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
                                        + currentPageNumber + " of " + totalPages, 520,
                                5, 0);
                        cb.endText();
                    }
                }
                pageOfCurrentReaderPDF = 0;
            }
            //outputStream.flush();
            document.close();
            //outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document.isOpen())
                document.close();
        }
        return new ByteArrayInputStream(productOutputStream.toByteArray());
    }
    
    //生成表格
    public static PdfPTable getPdfPTable(int column, int[] tableWidth) throws Exception {
        PdfPTable table = new PdfPTable(column);
        table.setWidths(tableWidth);
        table.getDefaultCell().setBorder(0);
        table.setWidthPercentage(100);
        return table;
    }
    
    //划斜线,详细了解可见http://www.anyrt.com/blog/list/line.html#1
    public static void drawLine(PdfContentByte canvas, float left, float top, int x, int y) {
    	canvas.saveState();
    	canvas.moveTo(left, top);
    	canvas.lineTo(left + x * 0.75f, top - y * 0.75f);
    	canvas.stroke();
    	canvas.restoreState();
    }
    
	private static byte[] InputStream2ByteArray(String filePath) throws IOException {
		InputStream in = new FileInputStream(filePath);
		byte[] data = toByteArray(in);
		in.close();
		return data;
	}
  
	private static byte[] toByteArray(InputStream in) throws IOException { 
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
		out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}
    
    //通过图片url路径获取字节流
    private static byte[] getImageByUrl(String url) {
    	ByteArrayOutputStream baos = null;
    	 try{
		   URL u = new URL(url);
		   BufferedImage image = ImageIO.read(u);
		   //convert BufferedImage to byte array
		   baos = new ByteArrayOutputStream();
		   ImageIO.write( image, "png", baos);
		   baos.flush();
    	 }catch (Exception e){
    		 e.printStackTrace();
    	 }finally{
    	   if(baos != null){
    		   try {
    			   baos.close();
    		   }catch (IOException e) {
    			   e.printStackTrace();
    		   }
		   }
    	 }
    	 return baos.toByteArray();
    }
	
	
	public static void main(String[] args) throws Exception {
		//List<InputStream> files = new ArrayList<>();
		String file = "C:\\Users\\sandy\\Desktop\\dome.pdf";
		//创建文本对象 Document
		Document document = new Document(PageSize.A4);
		//构建字节输出流
		//ByteArrayOutputStream objectOutputStream = new ByteArrayOutputStream();
		//初始化 pdf输出对象 PdfWriter  
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
		//打开 Document 
		document.open();
		//编辑一标题
		//段落
		Paragraph firstParagraph = new Paragraph();
		firstParagraph.setAlignment(Element.ALIGN_CENTER);
		firstParagraph.setSpacingAfter(15);
		//文本块
		Chunk firstChunk = new Chunk("标题一", new Font(bfSun, 24, Font.BOLD));
		firstChunk.setLineHeight(30);
		firstParagraph.add(firstChunk);
		document.add(firstParagraph);
		//编辑二标题
		Paragraph secondParagraph = new Paragraph();
		secondParagraph.setAlignment(Element.ALIGN_CENTER);
		secondParagraph.setSpacingAfter(15);
		//文本块
		Chunk secondChunk = new Chunk("标题二", new Font(bfSun, 24, Font.BOLD));
		secondChunk.setLineHeight(30);
		secondParagraph.add(secondChunk);
		document.add(secondParagraph);
		//编辑三标题
		Paragraph thirdParagraph = new Paragraph();
		thirdParagraph.setAlignment(Element.ALIGN_CENTER);
		thirdParagraph.setSpacingAfter(15);
		//文本块
		Chunk thirdChunk = new Chunk("标题三", new Font(bfSun, 24, Font.BOLD));
		thirdChunk.setLineHeight(25);
		thirdParagraph.add(thirdChunk);
		document.add(thirdParagraph);
		
		//编辑会议时间
		Paragraph meetParagraph = new Paragraph();
		meetParagraph.setAlignment(Element.ALIGN_RIGHT);
		meetParagraph.setSpacingAfter(20);
		//文本块
		Chunk meetChunk = new Chunk("会议时间:2019年12月24日", new Font(bfSun, 20, Font.BOLD));
		meetChunk.setLineHeight(20);
		meetParagraph.add(meetChunk);
		document.add(meetParagraph);
		
		int[] table1Width = { 50, 5, 5, 5, 50 };
        PdfPTable table1 = getPdfPTable(5, table1Width);
        table1.setSpacingAfter(80);
        PdfContentByte canvas = writer.getDirectContent();
        //设计表头
        PdfPCell pdfCell1 = new PdfPCell();
        //设置表格行高
        pdfCell1.setMinimumHeight(40);
        Paragraph titleParagraph = new Paragraph("                         意见\n议案",new Font(bfSun, 15, Font.NORMAL));
        pdfCell1.setPhrase(titleParagraph);
        table1.addCell(pdfCell1);
        PdfPCell pdfCell2 = new PdfPCell();
        pdfCell2.setMinimumHeight(40);
        pdfCell2.setPhrase(new Paragraph("同意",new Font(bfSun, 15, Font.NORMAL)));
        table1.addCell(pdfCell2);
        PdfPCell pdfCell3 = new PdfPCell();
        pdfCell3.setMinimumHeight(40);
        pdfCell3.setPhrase(new Paragraph("反对",new Font(bfSun, 15, Font.NORMAL)));
        table1.addCell(pdfCell3);
        PdfPCell pdfCell4 = new PdfPCell();
        pdfCell4.setMinimumHeight(40);
        pdfCell4.setPhrase(new Paragraph("弃权",new Font(bfSun, 15, Font.NORMAL)));
        table1.addCell(pdfCell4);
        PdfPCell pdfCell5 = new PdfPCell();
        //垂直居中
        pdfCell5.setUseAscender(true);
        pdfCell5.setVerticalAlignment(Element.ALIGN_MIDDLE); 
        pdfCell5.setMinimumHeight(40);
        pdfCell5.setPhrase(new Paragraph("情况说明",new Font(bfSun, 15, Font.NORMAL)));
        table1.addCell(pdfCell5);
        //划斜杠
        int x1 = 302, y1 = 53;
        drawLine(canvas, 36, 636, x1, y1);           
        PdfPCell pdfCell6 = new PdfPCell();
        //垂直居中
        pdfCell6.setUseAscender(true);
        pdfCell6.setVerticalAlignment(Element.ALIGN_MIDDLE); 
        pdfCell6.setMinimumHeight(40);
        pdfCell6.setPhrase(new Paragraph("一、《×××项目立项申请》",new Font(bfSun, 10, Font.NORMAL)));
        table1.addCell(pdfCell6);
        
        PdfPCell pdfCell7 = new PdfPCell();
        //垂直居中
        pdfCell7.setUseAscender(true);
        pdfCell7.setVerticalAlignment(Element.ALIGN_MIDDLE); 
        pdfCell7.setMinimumHeight(40);
        pdfCell7.setPhrase(new Paragraph("",new Font(bfSun, 10, Font.NORMAL)));
        table1.addCell(pdfCell7);

        PdfPCell pdfCell8 = new PdfPCell();
        //垂直居中
        pdfCell8.setUseAscender(true);
        pdfCell8.setVerticalAlignment(Element.ALIGN_MIDDLE); 
        pdfCell8.setMinimumHeight(40);
        pdfCell8.setPhrase(new Paragraph("",new Font(bfSun, 10, Font.NORMAL)));
        table1.addCell(pdfCell8);
        //本地勾图片
  		byte[] b =InputStream2ByteArray("C:\\hook.png");
  		//通过图片ur获取
        //byte[] b = getImageByUrl(imageUrl);
        Image img = Image.getInstance(b);
        PdfPCell pdfCell9 = new PdfPCell(img,true);
        table1.addCell(pdfCell9);
        
        PdfPCell pdfCell10 = new PdfPCell();
        //垂直居中
        pdfCell10.setUseAscender(true);
        pdfCell10.setVerticalAlignment(Element.ALIGN_MIDDLE); 
        pdfCell10.setMinimumHeight(40);
        pdfCell10.setPhrase(new Paragraph("",new Font(bfSun, 10, Font.NORMAL)));
        table1.addCell(pdfCell10);
        document.add(table1);
        
        int[] table2Width = { 40, 80, 80, 40 };
        PdfPTable table2 = getPdfPTable(4, table2Width);
        PdfPCell pdfCell11 = new PdfPCell();
        //设置表格行高
        pdfCell11.setMinimumHeight(40);
        //无边框
        pdfCell11.disableBorderSide(15);
        pdfCell11.setUseAscender(true);
        //水平居中
        pdfCell11.setHorizontalAlignment(Element.ALIGN_RIGHT);
        //垂直居中
        pdfCell11.setVerticalAlignment(Element.ALIGN_MIDDLE);
        pdfCell11.setPhrase(new Paragraph("委员签字:",new Font(bfSun, 15, Font.BOLD)));
        table2.addCell(pdfCell11);
        //本地签字图片
		byte[] a = InputStream2ByteArray("C:\\sign.png");
       // byte[] a = getImageByUrl(signUrl);
        Image imga = Image.getInstance(a);
        imga.scalePercent(10);
        imga.setRotationDegrees(90);
        PdfPCell pdfCell12 = new PdfPCell(imga,true);
        table2.addCell(pdfCell12);
                
        PdfPCell pdfCell13 = new PdfPCell();
        //设置表格行高
        pdfCell13.setMinimumHeight(40);
        pdfCell13.disableBorderSide(15);
        pdfCell13.setHorizontalAlignment(Element.ALIGN_RIGHT);
        pdfCell13.setVerticalAlignment(Element.ALIGN_MIDDLE);
        pdfCell13.setPhrase(new Paragraph("签名时间:",new Font(bfSun, 15, Font.BOLD)));
        table2.addCell(pdfCell13);
        
        PdfPCell pdfCell14 = new PdfPCell();
        //设置表格行高
        pdfCell14.setMinimumHeight(40);
        pdfCell14.disableBorderSide(15);
        pdfCell14.setHorizontalAlignment(Element.ALIGN_LEFT);
        pdfCell14.setVerticalAlignment(Element.ALIGN_MIDDLE);
        pdfCell14.setPhrase(new Paragraph("2019.03.22",new Font(bfSun, 15, Font.BOLD)));
        table2.addCell(pdfCell14);
        document.add(table2);
        //pd合成
        //files.add(new ByteArrayInputStream(objectOutputStream.toByteArray()));
        //InputStream is = concatPDFs(files, true);
		document.close();
	}
}

如图
效果图

发布了1 篇原创文章 · 获赞 0 · 访问量 10
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览