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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章