Java項目Maven配置操作Pdf

Java項目Maven配置操作Pdf

效果

maven配置

  • 【版本差異會出現STSong-Light' with 'UniGB-UCS2-H' is not recognized錯誤】
  • 【下面的依賴配置解決了上述的問題】
    <!-- pdf樣式 -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
    </dependency>
    <!--pdf相關操作-->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.4.3</version>
    </dependency>

工具類

public class DataUtil {
    /**
     * 分割路徑
     */
    public static String[] separatePath(String path) {
        if (path == null || "".equals(path.trim())) {
            return null;
        }
        String[] sep = path.split("\\.");
        return new String[]{sep[0], sep[1]};
    }
}

 

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.visionin.framework.db.Util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

public class PdfTempUtil {
    public static void main(String[] args) throws Exception {
        String toPath = "E://";
        String pdfName = "00100200300666";//這裏的名稱隨意
        String suff_fix_name = ".pdf";

        createPDF(toPath, pdfName, suff_fix_name);
    }

    /**
     * 創建PDF文檔
     */
    public static String createPDF(String toPath, String pdfName, String suffFixName) throws Exception {
        //輸出路徑
        String outPath = toPath + pdfName + suffFixName;
        //設置紙張
        Rectangle rect = new Rectangle(PageSize.A4);
        //創建文檔實例
        Document doc = new Document(rect);
        //添加中文字體
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        //設置字體樣式
        Font textFont = new Font(bfChinese, 11, Font.NORMAL); //正常
        Font redTextFont = new Font(bfChinese, 11, Font.NORMAL, BaseColor.RED); //正常,紅色
        Font boldFont = new Font(bfChinese, 11, Font.BOLD); //加粗
        Font redBoldFont = new Font(bfChinese, 11, Font.BOLD, BaseColor.RED); //加粗,紅色
        Font firsetTitleFont = new Font(bfChinese, 22, Font.BOLD); //一級標題
        Font secondTitleFont = new Font(bfChinese, 15, Font.BOLD); //二級標題
        Font underlineFont = new Font(bfChinese, 11, Font.UNDERLINE); //下劃線斜體
        //創建輸出流
        PdfWriter.getInstance(doc, new FileOutputStream(new File(outPath)));
        //打開文檔
        doc.open();
        //創建新的一頁
        doc.newPage();
        //段落
        Paragraph p1 = new Paragraph();
        //短語
        Phrase ph1 = new Phrase();

        //報告編號
        Chunk c1 = new Chunk("報告編號:", boldFont);
        Chunk c1_1 = new Chunk("" + pdfName, textFont);
        ph1.add(c1);
        ph1.add(c1_1);
        p1.add(ph1);
        doc.add(p1);

        //報告標題
        p1 = new Paragraph("人臉識別門禁出入記錄", firsetTitleFont);
        p1.setLeading(50);
        p1.setAlignment(Element.ALIGN_CENTER);
        doc.add(p1);

        //報告版本
        p1 = new Paragraph("(測試版)", textFont);
        p1.setLeading(20);
        p1.setAlignment(Element.ALIGN_CENTER);
        doc.add(p1);

        //報告時間和查詢的賬號
        p1 = new Paragraph();
        p1.setLeading(20);
        p1.setAlignment(Element.ALIGN_CENTER);
        ph1 = new Phrase();
        Chunk c2 = new Chunk("查詢時間:", boldFont);
        Chunk c2_1 = new Chunk(Calendar.getInstance().getTime() + "", textFont);
        Chunk c3 = new Chunk(leftPad("查詢人:", 10), boldFont);
        Chunk c3_1 = new Chunk("peng", textFont);
        ph1.add(c2);
        ph1.add(c2_1);
        ph1.add(c3);
        ph1.add(c3_1);
        p1.add(ph1);
        doc.add(p1);

        //報告說明
        p1 = new Paragraph("報告說明", secondTitleFont);
        p1.setLeading(50);
        p1.setAlignment(Element.ALIGN_CENTER);
        doc.add(p1);
        p1 = new Paragraph(" ");
        p1.setLeading(30);
        doc.add(p1);
        p1 = new Paragraph();
        ph1 = new Phrase();
        Chunk c4 = new Chunk("本報告由", textFont);
        Chunk c5 = new Chunk("XX科技有限公司", underlineFont);
        c5.setSkew(0, 30);
        Chunk c6 = new Chunk(" 出具,依據截止報告時間中數據庫記錄的信息生成,", textFont);
        Chunk c7 = new Chunk("不保證其真實性和準確性,但承諾在信息整合、彙總、展示的全過程中保持客觀、中立的地位。", textFont);
        ph1.add(c4);
        ph1.add(c5);
        ph1.add(c6);
        ph1.add(c5);
        ph1.add(c7);
        p1.add(ph1);
        doc.add(p1);

        //記錄概況
        p1 = new Paragraph("記錄概況", secondTitleFont);
        p1.setSpacingBefore(30);
        p1.setSpacingAfter(30);
        p1.setAlignment(Element.ALIGN_CENTER);
        doc.add(p1);

        // 創建一個有4列的表格
        PdfPTable table = new PdfPTable(7);
        table.setTotalWidth(new float[]{80, 80, 80, 80, 80, 80, 80}); //設置列寬
        table.setLockedWidth(true); //鎖定列寬

        table = createCell(table, new String[]{"位置", "組別", "設備", "工號", "姓名", "截圖", "時間"}, 1, 7, -1);
        for (int i = 1; i < 1000; i++) {
            table = createCell(table, new String[]{"深圳", "東莞工廠", "001002003004", "00" + i, "a" + i, "E://demo.jpg", "時間"}, 1, 7, 5);
        }
        doc.add(table);

        doc.close();
        return outPath;
    }

    /**
     * 創建單元格
     */
    private static PdfPTable createCell(PdfPTable table, String[] title, int row, int cols, int img_col_num) throws DocumentException, IOException {
        //添加中文字體
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font font = new Font(bfChinese, 11, Font.BOLD);
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < cols; j++) {
                PdfPCell cell = new PdfPCell();
                if (i == 0 && title != null) {//設置表頭
                    if (img_col_num == j) {//添加圖片列
                        Image img = Image.getInstance(title[img_col_num]);
                        img.setBorderWidth(0);
                        img.scaleToFit(50, 70);// 大小
                        cell = new PdfPCell(img);
                        cell.setPadding(5);
                    } else {
                        cell = new PdfPCell(new Phrase(title[j], font)); //這樣表頭才能居中
                    }
                    if (table.getRows().size() == 0) {
                        cell.setBorderWidthTop(3);
                    }
                }
                if (row == 1 && cols == 1) { //只有一行一列
                    cell.setBorderWidthTop(3);
                }
                if (j == 0) {//設置左邊的邊框寬度
                    cell.setBorderWidthLeft(3);
                }
                if (j == (cols - 1)) {//設置右邊的邊框寬度
                    cell.setBorderWidthRight(3);
                }
                if (i == (row - 1)) {//設置底部的邊框寬度
                    cell.setBorderWidthBottom(3);
                }
                cell.setMinimumHeight(40); //設置單元格高度
                cell.setUseAscender(true); //設置可以居中
                cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); //設置水平居中
                cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); //設置垂直居中
                table.addCell(cell);
            }
        }
        return table;
    }

    /**
     * 加水印(字符串)
     */
    public static void stringWaterMark(String inputFile, String waterMarkName) {
        try {
            String[] spe = DataUtil.separatePath(inputFile);
            String outputFile = spe[0] + "_WM." + spe[1];
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //添加中文字體
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte under;
            int j = waterMarkName.length();
            char c = 0;
            int rise = 0;
            //給每一頁加水印
            for (int i = 1; i < total; i++) {
                rise = 400;
                under = stamper.getUnderContent(i);
                under.beginText();
                under.setFontAndSize(bfChinese, 30);
                under.setTextMatrix(200, 120);
                for (int k = 0; k < j; k++) {
                    under.setTextRise(rise);
                    c = waterMarkName.charAt(k);
                    under.showText(c + "");
                }
                // 添加水印文字
                under.endText();
            }
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加水印(圖片)
     */
    public static void imageWaterMark(String inputFile, String imageFile) {
        try {
            String[] spe = DataUtil.separatePath(inputFile);
            String outputFile = spe[0] + "_WM." + spe[1];
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            int total = reader.getNumberOfPages() + 1;
            Image image = Image.getInstance(imageFile);
            image.setAbsolutePosition(-100, 0);//座標
            image.scaleAbsolute(800, 1000);//自定義大小
            //image.setRotation(-20);//旋轉 弧度
            //image.setRotationDegrees(-45);//旋轉 角度
            //image.scalePercent(50);//依照比例縮放
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.2f);// 設置透明度爲0.2
            PdfContentByte under;
            //給每一頁加水印
            for (int i = 1; i < total; i++) {
                under = stamper.getUnderContent(i);
                under.beginText();
                // 添加水印圖片
                under.addImage(image);
                under.setGState(gs);
            }
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 設置左邊距
     */
    public static String leftPad(String str, int i) {
        int addSpaceNo = i - str.length();
        String space = "";
        for (int k = 0; k < addSpaceNo; k++) {
            space = " " + space;
        }
        String result = space + str;
        return result;
    }

    /**
     * 設置間距
     */
    public static String printBlank(int tmp) {
        String space = "";
        for (int m = 0; m < tmp; m++) {
            space = space + " ";
        }
        return space;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章