欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 使用Itext 生成 PDF

程序员文章站 2022-04-19 20:24:52
...

Itext:https://itextpdf.com/en

有问题:qq :185624592

Maven地址: 版本和版本之间 这边要注意冲突 

 

效果图:

 

java 使用Itext 生成 PDF

 


        <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.lowagie.text</groupId>
            <artifactId>com.springsource.com.lowagie.text</artifactId>
            <version>2.0.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>4.2.2</version>
            <type>pom</type>
        </dependency>

 

 

代码 注释很详细


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.zq.common.core.utils.EncodeUtils;
import com.zq.common.core.utils.time.DateTimeUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Date;

public class pdfStu {

    //全局表格高度
    private static final float TABLE_HEIGHT=30;

    public static void pdfStu(String waterMark, String payUrl, HttpServletResponse response) throws Exception {
        // 生成PDF
        Document document = new Document(PageSize.A4);
        //文件设置微软字体
        //字体文件
        /*File file=HouseActualTemplateUtils.getFileByUrl(OBSUtils.getFileVisiturl("poly-collection","info_collection/font/yahei.ttf"),"ttf");
        BaseFont bfChinese = BaseFont.createFont(file.getPath(),BaseFont.IDENTITY_H, false);
        OBSUtils.deleteDirectory(file);*/
        //代码设置字体
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
        Font fontChineseBig = new Font(bfChinese, 14, Font.NORMAL);
        Font fontMoney = new Font(bfChinese, 13, Font.BOLD, BaseColor.RED);
        Font BlodFont = new Font(bfChinese, 12, Font.BOLD, BaseColor.BLACK);

        // 写入器
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
        // 只读 (设置不能复制)
        writer.setEncryption(null, null, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
        // 通过PDF页面事件模式添加文字水印功能
        writer.setPageEvent(new TextWaterMarkPdfPageEvent(waterMark));

        // 添加页脚功能
        document.open();
        PdfPTable pdfPTable = new PdfPTable(1);
        PdfFooterEvent footerTable = new PdfFooterEvent(pdfPTable, payUrl);
        footerTable.setTableFooter(writer);
        document.add(pdfPTable);


        // 添加PDF属性
        document.open();
        Paragraph pph1 = new Paragraph("大标题", new Font(bfChinese, 16, Font.BOLD, BaseColor.BLACK));
        pph1.setAlignment(Element.ALIGN_CENTER);
        pph1.setSpacingAfter(10);
        pph1.setSpacingBefore(5);
        document.add(pph1);
        // 6列的表.
        PdfPTable table = new PdfPTable(6);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);
        //设置每竖的宽度 默认可以不设置
        float[] widths = new float[] { 50, 50, 50, 50, 50, 50};
        table.setWidths(widths);

        PdfPCell cell0 = new PdfPCell(new Phrase("小标题",new Font(bfChinese, 14,
                Font.BOLD, BaseColor.BLACK)));
        cell0.setColspan(6);
        cell0=putStyle(cell0);
        table.addCell(cell0);

        PdfPCell cell1 = new PdfPCell(new Phrase("一" , fontChineseBig));
        //合并 列
        cell1.setRowspan(2);
        cell1=putStyle(cell1);
        table.addCell(cell1);

        PdfPCell cell2 = new PdfPCell(new Phrase("二", fontChineseBig));
        cell2=putStyle(cell2);
        cell2.setRowspan(2);
        table.addCell(cell2);

        PdfPCell cell3 = new PdfPCell(new Phrase("三", fontChineseBig));
        //合并行
        cell3.setColspan(4);
        cell3=putStyle(cell3);
        table.addCell(cell3);

        PdfPCell s1 =new PdfPCell(new Phrase("三1", fontChineseBig));
        //设置样式
        s1 = putStyle(s1);
        PdfPCell s2 =new PdfPCell(new Phrase("三2", fontChineseBig));
        s2 = putStyle(s2);
        PdfPCell s3 =new PdfPCell(new Phrase("三3", fontChineseBig));
        s3 = putStyle(s3);
        PdfPCell s4 =new PdfPCell(new Phrase("三4", fontChineseBig));
        s4 = putStyle(s4);

        table.addCell(s1);
        table.addCell(s2);
        table.addCell(s3);
        table.addCell(s4);

        cell1 =new PdfPCell(new Phrase("内容1", fontChinese));
        //设置样式
        cell1 = putStyle(cell1);
        cell2 =new PdfPCell(new Phrase("内容2", fontChinese));
        cell2 = putStyle(cell2);
        s1 =new PdfPCell(new Phrase("内容31", fontChinese));
        s1 = putStyle(s1);
        s2 =new PdfPCell(new Phrase("内容32", fontChinese));
        s2 = putStyle(s2);
        s3 =new PdfPCell(new Phrase("内容33", fontChinese));
        s3 = putStyle(s3);
        s4 =new PdfPCell(new Phrase("内容34", fontChinese));
        s4 = putStyle(s4);

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(s1);
        table.addCell(s2);
        table.addCell(s3);
        table.addCell(s4);

        cell1 =new PdfPCell(new Phrase("内容1", fontChinese));
        //设置样式
        cell1 = putStyle(cell1);
        cell2 =new PdfPCell(new Phrase("内容2", fontChinese));
        cell2 = putStyle(cell2);
        s1 =new PdfPCell(new Phrase("内容31", fontChinese));
        s1 = putStyle(s1);
        s2 =new PdfPCell(new Phrase("内容32", fontChinese));
        s2 = putStyle(s2);
        s3 =new PdfPCell(new Phrase("内容33", fontChinese));
        s3 = putStyle(s3);
        s4 =new PdfPCell(new Phrase("内容34", fontChinese));
        s4 = putStyle(s4);

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(s1);
        table.addCell(s2);
        table.addCell(s3);
        table.addCell(s4);


        cell1 =new PdfPCell(new Phrase("内容1", fontChinese));
        //设置样式
        cell1 = putStyle(cell1);
        cell2 =new PdfPCell(new Phrase("内容2", fontChinese));
        cell2 = putStyle(cell2);
        s1 =new PdfPCell(new Phrase("内容31", fontChinese));
        s1 = putStyle(s1);
        s2 =new PdfPCell(new Phrase("内容32", fontChinese));
        s2 = putStyle(s2);
        s3 =new PdfPCell(new Phrase("内容33", fontChinese));
        s3 = putStyle(s3);
        s4 =new PdfPCell(new Phrase("内容34", fontChinese));
        s4 = putStyle(s4);

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(s1);
        table.addCell(s2);
        table.addCell(s3);
        table.addCell(s4);


        //将tabel 添加到document
        document.add(table);

        // 读入并设置印章图片
        Image image = Image.getInstance("E:\\yz.png");
        image.setScaleToFitLineWhenOverflow(true);
        image.setAlignment(Element.ALIGN_RIGHT);
        //定位
        float x = table.getTotalWidth();
        float y = 600 - table.getTotalHeight();
        while (y < 0) {
            y = 550 - (table.getTotalHeight() - 550);
        }
        image.setAbsolutePosition(x - 60, y);
        image.scaleAbsolute(100, 100);
        PdfContentByte pcb = writer.getDirectContentUnder();
        pcb.addImage(image);
        document.add(image);
        document.add(Chunk.NEWLINE);

        // 特别提醒
        Paragraph paragraphRemark = new Paragraph();
        Font remarkFont = new Font(bfChinese, 10, Font.NORMAL);
        paragraphRemark.add(new Chunk("特别提醒:", BlodFont));
        paragraphRemark.add(Chunk.NEWLINE);
        paragraphRemark.add(new Chunk("1.一二三四五六", remarkFont));
        paragraphRemark.add(new Chunk("一二三四五六七八九十", fontMoney));
        paragraphRemark.add(new Chunk("。一二三四五六七八九十。", remarkFont));
        paragraphRemark.add(Chunk.NEWLINE);
        paragraphRemark.add(Chunk.NEWLINE);
        paragraphRemark.add(new Chunk("2.一二三四五六七八九十", remarkFont));
        paragraphRemark.add(new Chunk(DateTimeUtil.getFormatDate(new Date(),DateTimeUtil.TIME_FORMAT), fontMoney));
        paragraphRemark.add(new Chunk("一二三四五六七八九十。", remarkFont));
        paragraphRemark.add(Chunk.NEWLINE);
        paragraphRemark.add(Chunk.NEWLINE);
        paragraphRemark.add(new Chunk("4.一二三四五六七八九十。", remarkFont));
        paragraphRemark.add(Chunk.NEWLINE);
        document.add(paragraphRemark);

        /**
         * 图片测试
         */
        /*String imagePath = "E:\\1a.png";
        // 声明图片对象
        Image image;
        try {
            // 取得图片对象
            image = Image.getInstance(imagePath);
        } catch (BadElementException | IOException e) {
            return;
        }
        image.scaleAbsolute(ImageTools.getImgWidth(new File(imagePath)), ImageTools.getImgHeight(new File(imagePath)));
        // (以左下角为原点)设置图片的坐标
        image.setAbsolutePosition(80f, 140f);
        //设置图片的宽度和高度
        image.scaleAbsolute(500, 370);
        try {
            document.add(image);
        } catch (DocumentException e) {
        }*/


        pph1 = new Paragraph("打印日期:" + DateTimeUtil.getFormatDate(new Date(),DateTimeUtil.TIME_FORMAT), fontChinese);
        pph1.setAlignment(Element.ALIGN_RIGHT);
        pph1.setSpacingBefore(20);

        document.add(pph1);

        response.setContentType("application/pdf; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + EncodeUtils.urlEncode("pdf测试" + ".pdf"));
        document.close();
        writer.close();
        OutputStream out = response.getOutputStream();
        out.flush();
        response.flushBuffer();
    }


    /**
     * @Author GuoZG
     * @Description 设置样式
     * @Date 17:16 2019/7/30
     * @Param [pdfPCell]
     * @return com.itextpdf.text.pdf.PdfPCell
     **/
    public static PdfPCell putStyle(PdfPCell pdfPCell){
        //设置字体居中
        pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        pdfPCell.setFixedHeight(TABLE_HEIGHT);
        return pdfPCell;
    }
}