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

java操作pdf

程序员文章站 2024-03-21 14:41:10
...

新项目里有个pdf的生成文件,折腾了两天,终于可以 用了,现在 记下来,方便后来者。

有些代码重复的地方,大家凑合着看了,项目太急,也不想优化了。

里面大部分地方都做了注释,一看就会明白了。

废话不多说,直接上代码

先添加依赖

<itextpdf.version>5.5.12</itextpdf.version>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>${itextpdf.version}</version>
</dependency>
 
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.util.ResourceUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

 
public class PdfUtil {
    
    public static final Document document = new Document(PageSize.A4, 36, 72, 58, 100);

    public void createPdf() {
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("b.pdf"));
            document.open();
            document.newPage();
            // 标题
            document.add(new Paragraph("Customer Name and DL Number in header"));
            // 中间段落
            document.add(midelParagraph());
            document.add(getParagraph2("1801W Jefferson"));
            document.add(getParagraph2("Phonenix AZ 85007"));
            document.add(new Paragraph("\n"));
            //第一个table
            document.add(firstTable(null, null, null, null, null, null));
            document.add(new Paragraph("\n"));
            //第二个table
            document.add(secondTable(null, null, null, null, null, null, null));
            document.add(new Paragraph("\n"));
            //第三个table
            document.add(thirdTable(null, null, null, null, null,
                    null, null, null, null, null, null, null, null,
                    null, null, null));
            document.add(new Paragraph("\n"));
            document.newPage();
            document.add(new Paragraph("Customer Name and DL Number in header"));
            document.add(new Paragraph("\n"));
            document.add(fourth(null, null, null, null, null, null));
            document.add(new Paragraph("\n"));
            document.add(new Paragraph("\n"));
            document.add(fifthTitle());
            document.add(fifth());
            document.add(new Paragraph("\n"));
            document.add(new Paragraph("\n"));
            document.add(sixthTitle());
            document.add(sixth());
            document.add(new Paragraph("\n"));
            document.add(new Paragraph("\n"));
            document.add(seventhTitle("Saturday,July 15,2017"));
            document.add(sixth());
            document.add(new Paragraph("\n"));
            document.add(new Paragraph("\n"));
            document.add(seventhTitle("Thursday,Auguest17,2017"));
            List<String> strs = new ArrayList<>();
            strs.add("Event Row");
            strs.add("Time");
            strs.add("Description");
            strs.add("BAC");
            document.add(titleListFour(strs));


            document.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 设置下划线
     *
     * @return
     */
    public static Chunk getChunk(String str) {
        // 创建Chunk对象,设置下划线的厚度为0.1
        Chunk underline = new Chunk(str);
        underline.setUnderline(0.1f, -1f);
        // 创建Chunk对象,设置下划线的厚度为1
        Chunk strike = new Chunk(str);
        strike.setUnderline(1f, 3f);
        return underline;
    }

    /**
     * 设置段落居中
     *
     * @return
     */
    public static Paragraph getParagraph(String str) {
        Paragraph pg = new Paragraph(str, FontFactory.getFont(FontFactory.COURIER, 16, Font.BOLD));
        pg.setAlignment(1);
        return pg;
    }

    /**
     * 设置下划线段落居中
     *
     * @param str
     * @return
     */
    public static Paragraph getParagraph2(String str) {
        Paragraph pg = new Paragraph(getChunk(str));
        pg.setAlignment(1);
        return pg;
    }

    /**
     * 设置下划线段落居中加大字体
     *
     * @param str
     * @return
     */
    public static Paragraph getParagraph3(String str) {
        Paragraph pg = new Paragraph(getChunk(str));
        pg.setFont(FontFactory.getFont(FontFactory.COURIER, 18, Font.BOLD));
        pg.setAlignment(1);
        return pg;
    }


    /**
     * 中间段落
     *
     * @return
     * @throws
     */
    public static Paragraph midelParagraph() {
        Paragraph manufacturer = getParagraph2("Manufacturer");
        manufacturer.setSpacingBefore(25); // 设置行距
        return manufacturer;
    }


    /**
     * 照片
     *
     * @throws
     * @throws
     * @throws DocumentException
     */
    public static Document headPicDocument() {
        try {
            Image jpg = Image.getInstance("/home/acer/upload/1c98260a-1e10-44ba-8d62-cde4b782d8cb.png");
            jpg.setAlignment(Image.ALIGN_CENTER);
            document.add(jpg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return document;


    }


    //第getChunk一个table
    public static PdfPTable firstTable(String name, String dl, String address, String phoneNumber, String orderingAgency, String pic) {


        // PDFTable类似于html的表格文件,但是只有列的概念,定义列的数量,不能定义行的数量。
        // 创建一个两列的表格
        PdfPTable table = new PdfPTable(2);
        int width11[] = {70, 30};
        try {
            table.setWidths(width11);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 3、创建左边数据表格PdfPTable iTable,划分为N列
        PdfPTable leftTable = new PdfPTable(1);// 创建左边表格
        // 4、往左边表格中写入数据,加入iTable中
        leftTable.setWidthPercentage(10f);
        Paragraph customer_Information = new Paragraph();
        customer_Information.add(getChunk("Customer Information:"));
        PdfPCell leftCell = new PdfPCell(customer_Information);
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Name:" + name));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("DL#:" + dl));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Address:" + address));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Phone Number:" + phoneNumber));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Ordering Agency:" + orderingAgency));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        // 将表格加入到第一列中
        PdfPCell cell = new PdfPCell(leftTable);
        table.getDefaultCell().setBorder(0);  //去除边框
        cell.setBorder(0);
        table.addCell(cell);
        int count = pic.indexOf(".");
        // 5、创建图片对象,加入headerTable中,此处写入图片路径
        try {
            Image image = null;
            if (-1 != count) {
                image = Image.getInstance(pic);
            } else {
                String url = ResourceUtils.getURL("classpath:").getPath();
                image = Image.getInstance(url + "/headPic/headPic.jpg");
            }
            table.addCell(image);
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将主要的表格headerTable加入document文档对象中
        return table;
    }


    //第二个table
    public static PdfPTable secondTable(String name, String mpi, String address,
                                        String phoneNumber, String technician_Information, String name2, String id) {
        // PDFTable类似于html的表格文件,但是只有列的概念,定义列的数量,不能定义行的数量。
        // 创建一个两列的表格
        PdfPTable table2 = new PdfPTable(2);
        int width11[] = {50, 50};
        try {
            table2.setWidths(width11);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 3、创建左边数据表格PdfPTable iTable,划分为N列
        PdfPTable leftTable = new PdfPTable(1);// 创建左边表格
        // 4、往左边表格中写入数据,加入iTable中
        leftTable.setWidthPercentage(10f);
        Paragraph ServiceCenter = new Paragraph();
        ServiceCenter.add(getChunk("ServiceCenter:"));
        PdfPCell leftCell = new PdfPCell(ServiceCenter);
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Name:" + name));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("MPI :" + mpi));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Address: " + address));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Phone Number: " + phoneNumber));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        // 将表格加入到第一列中
        PdfPCell cell = new PdfPCell(leftTable);
        table2.getDefaultCell().setBorder(0);  //去除边框
        cell.setBorder(0);
        table2.addCell(cell);
        PdfPTable rightTable = new PdfPTable(1);// 创建左边表格
        rightTable.setWidthPercentage(10f);
        Paragraph technicianInformation = new Paragraph();
        technicianInformation.add(getChunk("Technician Information:" + technician_Information));
        PdfPCell rightCell = new PdfPCell(technicianInformation);
        rightCell.setBorder(0);
        rightTable.addCell(rightCell);
        rightCell = new PdfPCell(new Paragraph("(For Callbration Checks/Installs/Removals only)"));
        rightCell.setBorder(0);
        rightTable.addCell(rightCell);
        rightCell = new PdfPCell(new Paragraph("Name:" + name2));
        rightCell.setBorder(0);
        rightTable.addCell(rightCell);
        rightCell = new PdfPCell(new Paragraph("ID#:" + name2));
        rightCell.setBorder(0);
        rightTable.addCell(rightCell);
        PdfPCell cell2 = new PdfPCell(rightTable);
        table2.getDefaultCell().setBorder(0);  //去除边框
        cell2.setBorder(0);
        table2.addCell(rightTable);
        // 将主要的表格headerTable加入document文档对象中
        return table2;
    }


    /**
     * 第三个table
     *
     * @return
     */
    public static Element thirdTable(String device_Model, String device_Firmware_Version, String Device_software_Version,
                                     String install_Date, String date_of_Service, String removal_Date, String report_Period,
                                     String next_Service_Date, String as_Found, String reference_Check, String reference_Check2, String handset_or_Relay_In,
                                     String handset_or_relay_Out, String year_Make_Model, String plate, String vin) {
        PdfPTable table3 = new PdfPTable(2);
        int width11[] = {50, 50};
        // 3、创建左边数据表格PdfPTable iTable,划分为N列
        PdfPTable leftTable = new PdfPTable(1);// 创建左边表格
        // 4、往左边表格中写入数据,加入iTable中
        leftTable.setWidthPercentage(10f);
        Paragraph ServiceCenter = new Paragraph();
        ServiceCenter.add(getChunk("Device Information:"));
        PdfPCell leftCell = new PdfPCell(ServiceCenter);
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Device/Model:" + device_Model));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Device Firmware Version :" + device_Firmware_Version));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Device software Version: " + Device_software_Version));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Install Date: " + install_Date));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Date of Service : " + date_of_Service));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Removal Date: " + removal_Date));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Report Period: " + report_Period));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Next Service Date: " + next_Service_Date));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("As Found: " + as_Found));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Reference Check: " + reference_Check));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("reference Check: " + reference_Check2));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Handset or Relay# In: " + handset_or_Relay_In));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Handset or Relay# Out: " + handset_or_relay_Out));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        // 将表格加入到第一列中
        PdfPCell cell = new PdfPCell(leftTable);
        table3.getDefaultCell().setBorder(0);  //去除边框
        cell.setBorder(0);
        table3.addCell(cell);

        PdfPTable rightTable = new PdfPTable(1);// 创建左边表格
        rightTable.setWidthPercentage(10f);
        Paragraph technicianInformation = new Paragraph();
        technicianInformation.add(getChunk("Vehicle Information:"));
        PdfPCell rightCell = new PdfPCell(technicianInformation);
        rightCell.setBorder(0);
        rightTable.addCell(rightCell);
        rightCell = new PdfPCell(new Paragraph("Year/Make/Model :" + year_Make_Model));
        rightCell.setBorder(0);
        rightTable.addCell(rightCell);
        rightCell = new PdfPCell(new Paragraph("Plate:" + plate));
        rightCell.setBorder(0);
        rightTable.addCell(rightCell);
        rightCell = new PdfPCell(new Paragraph("Vin:" + vin));
        rightCell.setBorder(0);
        rightTable.addCell(rightCell);
        PdfPCell cell2 = new PdfPCell(rightTable);
        table3.getDefaultCell().setBorder(0);  //去除边框
        rightCell.setBorder(0);
        table3.addCell(rightTable);
        // 将主要的表格headerTable加入document文档对象中
        return table3;
    }


    //第四个table
    public static Element fourth(String reportable_Violations, String bypass_Code, String temportary_Lock_Out,
                                 String recall_Lock_Out, String failed_Rolling_Retest, String aborts) {

        // PDFTable类似于html的表格文件,但是只有列的概念,定义列的数量,不能定义行的数量。
        // 创建一个两列的表格
        PdfPTable table4 = new PdfPTable(1);
        // 3、创建左边数据表格PdfPTable iTable,划分为N列
        PdfPTable leftTable = new PdfPTable(1);// 创建左边表格
        // 4、往左边表格中写入数据,加入iTable中
        leftTable.setWidthPercentage(10f);
        Paragraph customer_Information = new Paragraph();
        customer_Information.add(getChunk("Summary of Events:"));
        PdfPCell leftCell = new PdfPCell(customer_Information);
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Reportable Violations: " + reportable_Violations));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Bypass_Code:" + bypass_Code));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Temportary Lock out:" + temportary_Lock_Out));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Recall Lock Out:" + recall_Lock_Out));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Failed Rolling Retest:" + failed_Rolling_Retest));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Aborts:" + aborts));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        // 将表格加入到第一列中
        PdfPCell cell = new PdfPCell(leftTable);
        cell.setBorder(0); //去除边框
        table4.addCell(cell);
        return table4;
    }

    /**
     * 第五个表title
     *
     * @return
     */
    public static Element fifthTitle() {
        PdfPTable table5 = new PdfPTable(1);
        PdfPTable leftTable = new PdfPTable(1);// 创建左边表格
        leftTable.setWidthPercentage(10f);
        Paragraph customer_Information = new Paragraph();
        customer_Information.add(getChunk("Summary of Violations:"));
        PdfPCell leftCell = new PdfPCell(customer_Information);
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        PdfPCell cell = new PdfPCell(leftTable);
        cell.setBorder(0);
        table5.getDefaultCell().setBorder(0);  //去除边框
        table5.addCell(cell);
        return table5;
    }

    /**
     * 第五个表内容
     *
     * @return
     */

    public static Element fifth() {
        PdfPTable table5 = new PdfPTable(6);
        int width3[] = {30, 20, 20, 20, 30, 20};
        try {
            table5.setWidths(width3);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        PdfPCell cell1 = new PdfPCell(new Paragraph("Event Row"));
        PdfPCell cell2 = new PdfPCell(new Paragraph("Evemt ID"));
        PdfPCell cell3 = new PdfPCell(new Paragraph("Date"));
        PdfPCell cell4 = new PdfPCell(new Paragraph("Time"));
        PdfPCell cell5 = new PdfPCell(new Paragraph("Description"));
        PdfPCell cell6 = new PdfPCell(new Paragraph("BAC"));
        cell1.setBorder(0);
        cell2.setBorder(0);
        cell3.setBorder(0);
        cell4.setBorder(0);
        cell5.setBorder(0);
        cell6.setBorder(0);
        table5.addCell(cell1);
        table5.addCell(cell2);
        table5.addCell(cell3);
        table5.addCell(cell4);
        table5.addCell(cell5);
        table5.addCell(cell6);

        for (int i = 0; i < 120; i++) {
            cell1 = new PdfPCell(new Paragraph("data"));
            cell1.setBorder(0);
            table5.addCell(cell1);
        }
        return table5;
    }


    /**
     * 第六个表title
     *
     * @return
     */
    public static Element sixthTitle() {
        PdfPTable table6 = new PdfPTable(1);
        PdfPTable leftTable = new PdfPTable(1);// 创建左边表格
        leftTable.setWidthPercentage(10f);
        Paragraph customer_Information = new Paragraph();
        customer_Information.add(getChunk("Detailed Events: "));
        PdfPCell leftCell = new PdfPCell(customer_Information);
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        leftCell = new PdfPCell(new Paragraph("Thursday,June 29,2017"));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        PdfPCell cell = new PdfPCell(leftTable);
        cell.setBorder(0);
        table6.getDefaultCell().setBorder(0);  //去除边框
        table6.addCell(cell);
        return table6;
    }

    /**
     * 第六个表
     *
     * @return
     */

    public static Element sixth() {
        PdfPTable table6 = new PdfPTable(6);
        int width3[] = {30, 20, 30, 20, 20, 40};
        try {
            table6.setWidths(width3);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        PdfPCell cell1 = new PdfPCell(new Paragraph("Event Row"));
        PdfPCell cell2 = new PdfPCell(new Paragraph("Time"));
        PdfPCell cell3 = new PdfPCell(new Paragraph("Description"));
        PdfPCell cell4 = new PdfPCell(new Paragraph("BAC"));
        PdfPCell cell5 = new PdfPCell(new Paragraph("Photo"));
        PdfPCell cell6 = new PdfPCell(new Paragraph("GPS Coordinates"));
        cell1.setBorder(0);
        cell2.setBorder(0);
        cell3.setBorder(0);
        cell4.setBorder(0);
        cell5.setBorder(0);
        cell6.setBorder(0);
        table6.addCell(cell1);
        table6.addCell(cell2);
        table6.addCell(cell3);
        table6.addCell(cell4);
        table6.addCell(cell5);
        table6.addCell(cell6);

        for (int i = 0; i < 120; i++) {
            cell1 = new PdfPCell(new Paragraph("data"));
            cell1.setBorder(0);
            table6.addCell(cell1);
        }
        return table6;
    }

    /**
     * 第七个表
     *
     * @return
     */
    public static Element seventhTitle(String str) {
        PdfPTable table7 = new PdfPTable(1);
        PdfPTable leftTable = new PdfPTable(1);// 创建左边表格
        PdfPCell leftCell = new PdfPCell(new Paragraph(str));
        leftCell.setBorder(0);
        leftTable.addCell(leftCell);
        table7.getDefaultCell().setBorder(0);  //去除边框
        table7.addCell(leftTable);
        return table7;

    }


    public static Element titleListFour(List<String> strs) {
        PdfPTable table6 = new PdfPTable(4);
        try {
            int width3[] = {30, 20, 30, 20};
            PdfPCell cell = null;
            try {
                table6.setWidths(width3);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            for (String str : strs) {
                cell = new PdfPCell(new Paragraph(str));
                cell.setBorder(0);
                table6.addCell(cell);
            }
            for (int i = 0; i < 40; i++) {
                cell = new PdfPCell(new Paragraph("data"));
                cell.setBorder(0);
                Image jpg = Image.getInstance("/home/acer/upload/1c98260a-1e10-44ba-8d62-cde4b782d8cb.png");
                jpg.setAlignment(Image.ALIGN_CENTER);
                table6.addCell(jpg);
            }
        } catch (IOException i) {
            i.printStackTrace();
        } catch (BadElementException b) {
            b.printStackTrace();
        }

        return table6;
    }

}

 

 

 

相关标签: java生成pdf