Java生成PDF文件(附PDF文档)

pom依赖

  		<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>

直接上代码

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.sun.prism.paint.Color;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成PDF文件
 *
 */
public class PDFReportUtil {

    private static Font headFont;// 设置字体大小
    private static Font keyFont;// 设置字体大小
    private static Font textFont;// 设置字体大小
    private static Font infoFont;// 设置字体大小
    private static Font redTextFont;// 设置字体大小
    private static Font redInfoFont;// 设置字体大小
    private static Font bigFont;// 设置字体大小
    private static Font titleFont;// 设置字体大小
    private static Font grayFont;// 设置字体大小
    private static Font font2;// 设置字体大小
    private int maxWidth = 540;


    /**
     *  UniGB-UCS2-H:横向字体
     *  UniGB-UCS2-V:竖向字体
     */

    static {
        BaseFont bfChinese;
        try {
            // UniGB-UCS2-H  横向字体
            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            headFont = new Font(bfChinese, 10, Font.BOLD);// 设置字体大小
            bigFont = new Font(bfChinese, 18, Font.BOLD);// 设置字体大小
            keyFont = new Font(bfChinese, 9, Font.BOLD);// 设置字体大小
            titleFont = new Font(bfChinese, 14, Font.NORMAL);// 设置字体大小
            textFont = new Font(bfChinese, 9, Font.NORMAL);// 设置字体大小
            font2 = new Font(bfChinese, 7, Font.NORMAL);// 设置字体大小
            infoFont = new Font(bfChinese, 9, Font.NORMAL);// 设置字体大小
            redTextFont = new Font(bfChinese, 9, Font.NORMAL, BaseColor.RED);// 红色字体
            redInfoFont = new Font(bfChinese, 9, Font.NORMAL, BaseColor.RED);// 红色字体
            grayFont = new Font(bfChinese, 9, Font.NORMAL, BaseColor.GRAY);// 灰色字体

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 生成PDF文件
     *
     * @param map 文件内容
     * @return
     * @throws MalformedURLException
     * @throws IOException
     * @throws DocumentException
     */
    public void generatePDF(File file, Map<String, Object> map)
            throws MalformedURLException, IOException, DocumentException {
        Document doc = null;

        try {
            //创建Document对象
            doc = new Document();
            doc.setMargins(20, 20, 30, 30);

            SimpleDateFormat sf = new SimpleDateFormat("yyyy.MM.dd");

            //创建书写器
            PdfWriter.getInstance(doc, new FileOutputStream(file));


//        // 添加页眉页脚
//        String headertitle = "*****报告" + "         " + "*******";
//        addheaderandfooter(doc, chinese, headertitle);

      		//添加标题作者信息
            doc.addAuthor("java@pdf");
            doc.addTitle("ceshi");

            //打开文档。
            doc.open();


            //初始化pdf基本功能性文本
            Image image = null;
            PdfPTable table;
            PdfPCell cell = null;
            Paragraph paragraph = null;


            // 准备工作结束,进行文档内容填充:
            // 添加公司logo图片
//            table = new PdfPTable(1);
//        String picpath = NewCorpReportMap.get("reportLogoFilePath").toString();
//        addpicture(table, image, picpath, cell, doc);

            // 添加报告信息
            title(paragraph, "某某科技公司", "张三客户", textFont, bigFont, doc);

//        //****************表格
            PdfPTable table2 = new PdfPTable(5);
            table2.setTotalWidth(maxWidth);
            int[] with = {120, 120, 100, 100, 100};
            table2.setWidths(with);
            table2.setLockedWidth(true);
            table2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.getDefaultCell().setBorder(1);

            table2.addCell(createCell("学生信息列表:", keyFont, Element.ALIGN_LEFT, 5, false));
            table2.addCell(createCell("姓名", keyFont, Element.ALIGN_CENTER));
            table2.addCell(createCell("年龄", keyFont, Element.ALIGN_CENTER));
            table2.addCell(createCell("性别", keyFont, Element.ALIGN_CENTER));
            table2.addCell(createCell("住址", keyFont, Element.ALIGN_CENTER));
            table2.addCell(createCell("学生总人数", keyFont, Element.ALIGN_CENTER));

            int count = 5;
            for (int i = 0; i < count; i++) {
                table2.addCell(createCell("姓名" + i, textFont));
                table2.addCell(createCell(i + 15 + "", textFont));
                table2.addCell(createCell((i % 2 == 0) ? "男" : "女", textFont));
                table2.addCell(createCell("地址" + i, textFont));
                if (i == 0) {
                    table2.addCell(createCell2(count + "", textFont, Element.ALIGN_CENTER, count, true));
                }
            }
            doc.add(table2);

//        //****************表格


            // 第三页 报告摘要,每页空2行留给页眉
            doc.add(new Paragraph("       ", keyFont));
            doc.add(new Paragraph("       ", keyFont));

            doc.newPage();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }

    }


    /**
     * 给pdf文件添加水印
     *
     * @param InPdfFile  要加水印的原pdf文件路径
     * @param outPdfFile 加了水印后要输出的路径
     *                   //     * @param object
     *                   //     *            水印图片路径
     *                   //     * @param pageSize
     *                   //     *            原pdf文件的总页数(该方法是我当初将数据导入excel中然后再转换成pdf所以我这里的值是用excel的行数计算出来的,
     *                   //     *            如果不是我这种可以 直接用reader.getNumberOfPages()获取pdf的总页数)
     * @throws Exception
     */
    public static void addPdfMark(String InPdfFile, String outPdfFile, String readpicturepath) throws Exception {
        PdfReader reader = new PdfReader(InPdfFile);
        int pageSize = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));
        Image img = Image.getInstance(readpicturepath);// 插入水印
        img.setAbsolutePosition(0, 0);
        for (int i = 1; i <= pageSize; i++) {
            PdfContentByte under = stamp.getUnderContent(i);
            under.addImage(img);
        }
        stamp.close();// 关闭
        File tempfile = new File(InPdfFile);
        if (tempfile.exists()) {
            tempfile.delete();
        }
    }

    // paragraph的格式
    public static void geshi1(Paragraph paragraph, Document doc) throws DocumentException {// 段落的格式
        paragraph.setIndentationLeft(30);
        paragraph.setIndentationRight(30);
        paragraph.setFirstLineIndent(20f);
        paragraph.setSpacingAfter(10f);
        paragraph.setSpacingBefore(10f);
        doc.add(paragraph);
    }

    // 居右无边框的cell
    public static void geshi3(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_RIGHT);
        table.addCell(cell);
    }

    // 居中无边框的cell
    public static void geshi2(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        table.addCell(cell);
    }

    // 不居中无边框的cell
    public static void geshi12(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
    }

    // 居中有边框的cell
    public static void geshi22(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        table.addCell(cell);
    }

    // 居中有边框的cell
    public static void geshi32(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setColspan(3);
        cell.setBorder(0);
        table.addCell(cell);
    }

    // 设置字体
    public static Font setfont(String fonttype, float fontsize, int fontflag, Color fontcolor, int fontstyle)
            throws DocumentException, IOException {
        BaseFont baseFont5 = BaseFont.createFont(fonttype, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font font = new Font(baseFont5, fontsize, fontflag);
        font.setColor(BaseColor.BLACK);
        if (fontstyle != 0) {// 如果传参为0不设置字体
            font.setStyle(fontstyle);
        }
        return font;
    }

    // 插入图片
    public static void addPicture(PdfPTable table, Image image, String picpath, PdfPCell cell, Document doc)
            throws MalformedURLException, IOException, DocumentException {
        image = Image.getInstance(picpath);
        //图片尺寸
        image.scaleAbsolute(75, 75);
        cell = new PdfPCell(image);
        geshi3(cell, table);
        doc.add(table);
    }

    // 首页--固定格式布局
    public static void title(Paragraph paragraph, String company, String cusName,
                             Font myfont, Font myfont3, Document doc) throws DocumentException {

        paragraph = new Paragraph(cusName + company, myfont3);// 公司名
        paragraph.setAlignment(1);
        doc.add(paragraph);

        doc.add(new Paragraph("       ", myfont));
        doc.add(new Paragraph("       ", myfont));

    }


    //非空判断
    public static String isNull(Object a) {
        if (a == null || a.equals("null")) {
            return "";
        } else {
            return a + "";
        }
    }


    /**
     * 创建单元格
     *
     * @param value 文本
     * @param font  字体
     * @param align 对齐方式 0-左对齐 1-居中 2-右对齐
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setPaddingTop(4.0f);
        cell.setPaddingBottom(5.0f);
        return cell;
    }

    /**
     * 无边框 居左
     *
     * @param value
     * @param font
     * @param
     * @return
     */
    public PdfPCell createCell3(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_LEFT);
        cell.setHorizontalAlignment(0);//居左
        cell.setPhrase(new Phrase(value, font));
        //无边框
        cell.setBorder(0);
        cell.setPaddingTop(1.0f);
        cell.setPaddingBottom(10.0f);
        return cell;
    }

    /**
     * 无边框
     *
     * @param value
     * @param font
     * @param align 0-居左 1-居中 2-居右
     * @return
     */
    public PdfPCell createCell4(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_RIGHT);
        cell.setHorizontalAlignment(align);//居右
        cell.setPhrase(new Phrase(value, font));
        //无边框
        cell.setBorder(0);
        cell.setPaddingTop(1.0f);
        cell.setPaddingBottom(10.0f);
        return cell;
    }

    /**
     * @param value 文本
     * @param font  字体
     * @return
     */
    public PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * @param value     文本
     * @param font      字体
     * @param align     对齐方式 0-左对齐 1-居中 2-右对齐
     * @param colspan   合并列
     * @param boderFlag 是否有边框
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        }
        return cell;
    }

    /**
     * @param value     文本
     * @param font      字体
     * @param align     对齐方式  0-左对齐 1-居中 2-右对齐
     * @param rowspan   合并行
     * @param boderFlag 是否有边框
     * @return
     */
    public PdfPCell createCell2(String value, Font font, int align, int rowspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setRowspan(rowspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        }
        return cell;
    }


    public static void main(String[] args) throws IOException, DocumentException {
        Map<String, Object> map = new HashMap<>();
        new PDFReportUtil().generatePDF(new File("D:/temp/测试.pdf"), map);
        System.out.println("pdf已生成");
    }
}

效果展示:
在这里插入图片描述

PDF中文帮助文档
Paragraph API
Phrase API

开心一刻

不小心把50块钱投进去了,司机说我没权打开,只能收后面上来人的散钱了,收到了48块刚好进站有一人要上车,我马上伸手说给钱,他一愣说不是无人售票么,我说快点,司机和车上的人都说快点(他们知道我怎么回事),后面这大哥直接把钱包扔给我说:你们人多,我就这点钱了。然后就跑了……跑了……了

在这里插入图片描述

相关链接
https://blog.csdn.net/weixin_37848710/article/details/89522862

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值