Itext 生成PDF

Itext生成pdf

  • 添加依赖

     <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.5.13</version>
            </dependency>
    
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itext-asian</artifactId>
                <version>5.2.0</version>
            </dependency>
    
  • PDFUtil类

    package com.qz.soft.sampling.util;
    
    import com.itextpdf.text.*;
    import com.itextpdf.text.pdf.BaseFont;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.tool.xml.XMLWorkerFontProvider;
    
    import java.util.Map;
    
    
    /**
     * @author xuxin
     * @date 2021/10/14
     */
    public class PdfUtil {
    
    
        // main测试
        public static void main(String[] args) throws Exception {
            try {
    /*           // 1.新建document对象
                Document document = new Document(PageSize.A4);// 建立一个Document对象
    
                // 2.建立一个书写器(Writer)与document对象关联
                File file = new File("E:\\PDFDemo.pdf");
                File html = new File("E:\\徐鑫\\项目\\平板抽样\\1.四川纤检\\资料\\bbbb.html");
    
              Resource classPathResource = new ClassPathResource("/static/bbbb.html");
    
    
                file.createNewFile();
                PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
    
                document.open();
                document.addTitle("Title@PDF-Java");// 标题
                document.addAuthor("Author@umiz");// 作者
                document.addSubject("Subject@iText pdf sample");// 主题
                document.addKeywords("Keywords@iTextpdf");// 关键字
                document.addCreator("Creator@umiz`s");// 创建者
    
                XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
                worker.parseXHtml(pdfWriter, document, classPathResource.getInputStream(), Charset.forName("UTF-8"));
                document.close();*/
    
    
    /*
                // 3.打开文档
                document.open();
                document.addTitle("Title@PDF-Java");// 标题
                document.addAuthor("Author@umiz");// 作者
                document.addSubject("Subject@iText pdf sample");// 主题
                document.addKeywords("Keywords@iTextpdf");// 关键字
                document.addCreator("Creator@umiz`s");// 创建者
    
                // 4.向文档中添加内容
                new PdfUtil().generatePDF(document);
    
                // 5.关闭文档
                document.close();*/
    
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        // 定义全局的字体静态变量
        private static Font titlefont;
        private static Font headfont;
        private static Font keyfont;
        private static Font textfont;
        // 最大宽度
        private static int maxWidth = 520;
    
        // 静态代码块
        static {
            try {
                // 不同字体(这里定义为同一种字体:包含不同字号、不同style)
                BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                titlefont = new Font(bfChinese, 16, java.awt.Font.BOLD);
                headfont = new Font(bfChinese, 14, java.awt.Font.BOLD);
                keyfont = new Font(bfChinese, 10, java.awt.Font.BOLD);
                textfont = new Font(bfChinese, 10, Font.NORMAL);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
        // 生成PDF文件
        public void generatePDF(Document document, Map<String,Object> map) throws Exception {
    
            // 段落
            Paragraph paragraph = new Paragraph("产品质量监督抽查/复查抽样单", titlefont);
            paragraph.setAlignment(1); //设置文字居中 0靠左   1,居中     2,靠右
            paragraph.setIndentationLeft(12); //设置左缩进
            paragraph.setIndentationRight(12); //设置右缩进
            paragraph.setFirstLineIndent(24); //设置首行缩进
            paragraph.setLeading(20f); //行间距
            paragraph.setSpacingBefore(5f); //设置段落上空白
            paragraph.setSpacingAfter(5f); //设置段落下空白
    
            //编号
            Paragraph paragraph_No = new Paragraph("编号:"+map.get("record_no").toString(), textfont);
            paragraph_No.setAlignment(2); //设置文字居中 0靠左   1,居中     2,靠右
            paragraph_No.setIndentationLeft(12); //设置左缩进
            paragraph_No.setIndentationRight(12); //设置右缩进
            paragraph_No.setFirstLineIndent(24); //设置首行缩进
            paragraph_No.setLeading(10f); //行间距
            paragraph_No.setSpacingBefore(5f); //设置段落上空白
            paragraph_No.setSpacingAfter(5f); //设置段落下空白
    
            // 表格
            //PdfPTable table = createTable();
            PdfPTable table = new PdfPTable(8);
            table.setWidthPercentage(100);
            table.setWidths(new float[]{40, 40, 40, 60, 100, 120, 80, 80});
    
    
            table.addCell(createCell("任务来源", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("taskSourceDesc").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("抽样依据及文号", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("plan_no").toString(), textfont, Element.ALIGN_LEFT));
            table.addCell(createCell("任务类型", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("taskTypeDesc").toString(), textfont, Element.ALIGN_LEFT));
    
            //抽查对象
            table.addCell(createCell("抽查对象", textfont, Element.ALIGN_LEFT,1,9));
            table.addCell(createCell("名称", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("name").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("抽样环节", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("sample_links").toString(), textfont, Element.ALIGN_LEFT,2));
    
            table.addCell(createCell("地址", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("address").toString(), textfont, Element.ALIGN_LEFT,3));
            table.addCell(createCell("抽查对象类型", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("type").toString(), textfont, Element.ALIGN_LEFT,2));
    
            table.addCell(createCell("邮政编码", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("zip_code").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("经营者所在地", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("operate_location").toString(), textfont, Element.ALIGN_LEFT,2));
    
            table.addCell(createCell("法定代表人", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("legal_person").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("抽查检验场所", textfont, Element.ALIGN_LEFT,1,4));
            table.addCell(createCell(map.get("inspection_place").toString(), textfont, Element.ALIGN_LEFT,3,4));
    
            table.addCell(createCell("联系人", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("contacts").toString(), textfont, Element.ALIGN_LEFT,2));
    
            table.addCell(createCell("联系电话", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("phone").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("统一社会信用代码", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("licence").toString(), textfont, Element.ALIGN_LEFT,2));
    
            table.addCell(createCell("从业人员数", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("employees").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("是否产生购样费", textfont, Element.ALIGN_LEFT,1));
    
            table.addCell(createCell(map.get("purchase_fee").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("营业收入", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("income").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("无偿提供样品", textfont, Element.ALIGN_LEFT,1));
            table.addCell(createCell(map.get("provide_sample").toString(), textfont, Element.ALIGN_LEFT,3));
    
    
            //生产单位
            table.addCell(createCell("生产单位", textfont, Element.ALIGN_LEFT,1,2));
            table.addCell(createCell("单位名称", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("name").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("联系人", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("contacts").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("单位地址", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("address").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("联系电话", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("phone").toString(), textfont, Element.ALIGN_LEFT,3));
    
    
            //受检产品
            table.addCell(createCell("受检产品", textfont, Element.ALIGN_LEFT,1,10));
            table.addCell(createCell("工业产品生产许可证", textfont, Element.ALIGN_LEFT,4));
            table.addCell(createCell("抽查通知书", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("file1_url").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("产品名称", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("product_name").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("规格型号", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("version_sample").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("生产日期/批号", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("batch_number").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("商标", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("logo").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("抽样数量", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("sample_amount").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("产品等级", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("product_level").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("库存量", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("store_amount").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("标注执行标准/技术文件", textfont, Element.ALIGN_LEFT,1,2));
            table.addCell(createCell(map.get("execute_file").toString(), textfont, Element.ALIGN_LEFT,3,2));
    
            table.addCell(createCell("批量/进货量", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("purchase_amount").toString(), textfont, Element.ALIGN_LEFT,2));
    
            table.addCell(createCell("单价(元)", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("price").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("封样状态", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("storage_state").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("备样量及封存地点", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("count_bak").toString()+" , "+map.get("storage_address"), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("寄送样地点", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("send_address").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("抽样日期", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell((String) map.get("sample_time"), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("寄送样截至日期", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("send_end_time").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("抽样地点", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("sample_address").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("抽样方式", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("sample_mode").toString(), textfont, Element.ALIGN_LEFT,3));
    
            //抽样机构
            table.addCell(createCell("抽样机构", textfont, Element.ALIGN_LEFT,1,3));
            table.addCell(createCell("单位名称", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("cy_company_name").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("联系人", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("cy_company_contact").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("单位地址", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("cy_company_address").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("联系电话", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("cy_company_phone").toString(), textfont, Element.ALIGN_LEFT,3));
    
            table.addCell(createCell("邮政编码", textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell(map.get("cy_company_zip").toString(), textfont, Element.ALIGN_LEFT,2));
            table.addCell(createCell("传真/Email", textfont, Element.ALIGN_LEFT));
            table.addCell(createCell(map.get("cy_company_fax").toString(), textfont, Element.ALIGN_LEFT,3));
    
            //备注
           table.addCell(createCell(map.get("remark").toString(), textfont, Element.ALIGN_LEFT,8,1,60));
    
           //签名
            table.addCell(createCell("抽查对象对抽查过程无异议:确认所抽产品为境内生产、销售的合格待销产品:已阅读并核实抽样单内容,无异议\n抽查对象单位签名(盖章)\n\n\n                                           ______年______月______日 ", textfont, Element.ALIGN_LEFT,5,1,80));
            table.addCell(createCell("抽样人(签名):\n\n\n\n                                           抽样机构(公章)\n\n                                              ______年______月______日", textfont, Element.ALIGN_LEFT,3,6,40));
            document.add(paragraph);
            document.add(paragraph_No);
            document.add(table);
    
        }
    
    
    /**------------------------创建表格单元格的方法start----------------------------*/
        /**
         * 创建单元格(指定字体)
         *
         * @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
         * @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));
            return cell;
        }
    
        /**
         * 创建单元格(指定字体、水平居..、单元格跨x列合并)
         *
         * @param value
         * @param font
         * @param align
         * @param colspan
         * @return
         */
        public PdfPCell createCell(String value, Font font, int align, int colspan) {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(align);
            cell.setColspan(colspan);
            cell.setPhrase(new Phrase(value, font));
            return cell;
        }
    
    
    
        /**
         * 创建单元格(指定字体、水平居..、单元格跨x列 Y列合并)
         *
         * @param value
         * @param font
         * @param align
         * @param colspan
         * @param rowspan
         * @return
         */
        public PdfPCell createCell(String value, Font font, int align, int colspan, int rowspan) {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(align);
            cell.setColspan(colspan);
            cell.setRowspan(rowspan);
            cell.setPhrase(new Phrase(value, font));
            return cell;
        }
    
        public PdfPCell createCell(String value, Font font, int align, int colspan, int rowspan,int height) {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(align);
            cell.setColspan(colspan);
            cell.setRowspan(rowspan);
            cell.setPhrase(new Phrase(value, font));
            cell.setFixedHeight(height);
            return cell;
        }
        /**
         * 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
         *
         * @param value
         * @param font
         * @param align
         * @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);
            } else if (boderFlag) {
                cell.setBorder(0);
                cell.setPaddingTop(0.0f);
                cell.setPaddingBottom(15.0f);
            }
            return cell;
        }
    
        /**
         * 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
         *
         * @param value
         * @param font
         * @param align
         * @param borderWidth
         * @param paddingSize
         * @param flag
         * @return
         */
        public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(align);
            cell.setPhrase(new Phrase(value, font));
            cell.setBorderWidthLeft(borderWidth[0]);
            cell.setBorderWidthRight(borderWidth[1]);
            cell.setBorderWidthTop(borderWidth[2]);
            cell.setBorderWidthBottom(borderWidth[3]);
            cell.setPaddingTop(paddingSize[0]);
            cell.setPaddingBottom(paddingSize[1]);
            if (flag) {
                cell.setColspan(2);
            }
            return cell;
        }
    /**------------------------创建表格单元格的方法end----------------------------*/
    
    
    /**--------------------------创建表格的方法start------------------- ---------*/
        /**
         * 创建默认列宽,指定列数、水平(居中、右、左)的表格
         *
         * @param colNumber
         * @param align
         * @return
         */
        public PdfPTable createTable(int colNumber, int align) {
            PdfPTable table = new PdfPTable(colNumber);
            try {
                table.setTotalWidth(maxWidth);
                table.setLockedWidth(true);
                table.setHorizontalAlignment(align);
                table.getDefaultCell().setBorder(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return table;
        }
    
        /**
         * 创建指定列宽、列数的表格
         *
         * @param widths
         * @return
         */
        public PdfPTable createTable(float[] widths) {
            PdfPTable table = new PdfPTable(widths);
            try {
                table.setTotalWidth(maxWidth);
                table.setLockedWidth(true);
                table.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.getDefaultCell().setBorder(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return table;
        }
    
        /**
         * 创建空白的表格
         *
         * @return
         */
        public PdfPTable createBlankTable() {
            PdfPTable table = new PdfPTable(1);
            table.getDefaultCell().setBorder(0);
            table.addCell(createCell("", keyfont));
            table.setSpacingAfter(20.0f);
            table.setSpacingBefore(20.0f);
            return table;
        }
    /**--------------------------创建表格的方法end------------------- ---------*/
    
    }
    
    class AsianFontProvider extends XMLWorkerFontProvider {
        @Override
        public Font getFont(final String fontname, String encoding, float size, final int style) {
            try {
                BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                return new Font(bfChinese, size, style);
            } catch (Exception e) {
            }
            return super.getFont(fontname, encoding, size, style);
        }
    }
    
    

Html转PDF

  • 添加依赖

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>html2pdf</artifactId>
        <version>4.0.0</version>
    </dependency>
    
  • 代码

    import com.itextpdf.html2pdf.HtmlConverter;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class HtmlToPDF {
        private static final String ORIG = "/uploads/input.html";
        private static final String OUTPUT_FOLDER = "/myfiles/";
    
        public static void main(String[] args) throws IOException {
            File htmlSource = new File(ORIG);
            File pdfDest = new File(OUTPUT_FOLDER + "output.pdf");
            HtmlConverter.convertToPdf(new FileInputStream(htmlSource), new FileOutputStream(pdfDest));
        }
    
    }
    
    
    

官网地址:Convert HTML & CSS to rich, smart PDF documents - iText (itextpdf.com)

原文地址:https://www.cnblogs.com/seanRay/p/15602264.html