itext设置字体间距_Java使用iText生成pdf

iText 是一个非常著名的能够快速产生 PDF 文件的 Java 类库。支持文本,表格,图形的操作,可以方便的跟 Servlet 进行结合

pom.xml

<dependency>        <groupId>com.itextpdfgroupId>        <artifactId>itextpdfartifactId>       <version>5.5.13version>dependency><dependency>        <groupId>com.itextpdfgroupId>        <artifactId>itext-asianartifactId>        <version>5.2.0version>dependency>

Test

快速创建一个pdf

// 创建一个Document对象(pdf文档) A4纸张大小Document document = new Document(PageSize.A4);// 建立一个书写器(Writer)与document对象关联PdfWriter.getInstance(document, new FileOutputStream("D:\\Test.pdf"));// 打开文档document.open();// 向文档中输入一个内容 document.add(new Paragraph("Hello World"));// 关闭文档document.close();

《itext设置字体间距_Java使用iText生成pdf》

PDF文档中添加内容

全局字体设置

/*** 定义全局的字体静态变量 */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, Font.BOLD);                headfont = new Font(bfChinese, 14, Font.BOLD);                keyfont = new Font(bfChinese, 10, Font.BOLD);                textfont = new Font(bfChinese, 10, Font.NORMAL);        } catch (Exception e) {                e.printStackTrace();        }}

段落

// 段落Paragraph paragraph = new Paragraph("Hello I Text 5", titlefont);//设置文字居中 0靠左 1,居中 2,靠右paragraph.setAlignment(1);//设置左缩进paragraph.setIndentationLeft(12);//设置右缩进paragraph.setIndentationRight(12);//设置首行缩进paragraph.setFirstLineIndent(24);//行间距paragraph.setLeading(20f);//设置段落上空白paragraph.setSpacingBefore(5f);//设置段落下空白paragraph.setSpacingAfter(10f);

直线/点线

// 直线Paragraph p1 = new Paragraph();p1.add(new Chunk(new LineSeparator()));// 点线Paragraph p2 = new Paragraph();p2.add(new Chunk(new DottedLineSeparator()));

超链接

// 超链接Anchor anchor = new Anchor(new Paragraph("超链接", titlefont));anchor.setReference("www.baidu.com");

图片

// 添加图片Image image = Image.getInstance("http://devb2b.hosjoy.com/img/hosjoy_logo48@2x.595a425a.png");// 位置image.setAlignment(Image.ALIGN_CENTER);// 依照比例 缩放image.scalePercent(20);

表格PdfPTable

// 创建一个包含5列的表格PdfPTable table = new PdfPTable(5);// 创建一个宽度比例表格PdfPTable table = new PdfPTable(new float[]{
    10, 12, 12, 10, 10});// 表格最大像素table.setTotalWidth(maxWidth);// 锁定宽度table.setLockedWidth(true);// 水平居中table.setHorizontalAlignment(Element.ALIGN_CENTER);// 表格边框 配合 单元格设置table.getDefaultCell().setBorder(1);// 创建单元格PdfPCell cell = new PdfPCell();// 垂直对齐设置cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 水平对齐设置cell.setHorizontalAlignment();// 合并单元格cell.setColspan(1);// 合并单元格cell.setRowspan(1);// 内容cell.setPhrase(new Phrase(value, font));// 边框设置cell.setBorder(Rectangle.NO_BORDER);// 背景颜色设置cell.setBackgroundColor(baseColor);// 将单元格加入表格table.addCell(cell)    // 表格添加图片Image image = Image.getInstance("http://devb2b.hosjoy.com/img/hosjoy_logo48@2x.595a425a.png");image.setAlignment(Image.ALIGN_LEFT);Phrase listOfDots = new Phrase();// 位置设置listOfDots.add(new Chunk(image, 0, 0));// 表格添加图片table.addCell(listOfDots);

页眉页脚 和 水印

继承 PdfPageEventHelper

/*** 打开文档时,创建一个总页数的模版 */@Overridepublic void onOpenDocument(PdfWriter writer, Document document) {                   PdfContentByte cb = writer.getDirectContent();        totalPage = cb.createTemplate(30, 12);}/** * 一页加载完成触发,写入页眉和页脚   * 添加水印 */@Overridepublic void onEndPage(PdfWriter writer, Document document) {
            // 水印    for(int i=0 ; i<4; i++) {
            for(int j=0; j<7; j++) {
                ColumnText.showTextAligned(writer.getDirectContentUnder(),                    Element.ALIGN_CENTER,                    new Phrase("好享家", watermarkFont),                    (50.5f+i*150),                    (40.0f+j*150),                    writer.getPageNumber() % 2 == 1 ? 45 : -45);        }    }            // 页眉和页脚     PdfPTable table = new PdfPTable(3);    try {
            // 总宽        table.setTotalWidth(PageSize.A4.getWidth()-80);        // 设置表格宽3列        table.setWidths(new int[]{
    24, 24, 3});        table.setLockedWidth(true);        table.getDefaultCell().setFixedHeight(0);        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);        // 可以直接使用addCell(str),不过不能指定字体,中文无法显示        table.addCell(new Paragraph("hosjoy", Font));        // 水平对齐        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);        table.addCell(new Paragraph("第" + writer.getPageNumber() + "页/", hfFont));        // 总页数        PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));        // 去掉表格边框        cell.setBorder(Rectangle.BOTTOM);        table.addCell(cell);        // 将页眉写到document中,位置可以指定,指定到下面就是页脚        table.writeSelectedRows(0, -1, 40, 20 , writer.getDirectContent());    } catch (Exception de) {
            throw new ExceptionConverter(de);    }}/*** 全部完成后,将总页数的pdf模版写到指定位置*/@Overridepublic void onCloseDocument(PdfWriter writer, Document document) {
        String text = "总" + (writer.getPageNumber()) + "页";    ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,           hfFont), 2, 2, 0);}

实例
建一个Product 对象

package com.example.demo.pdf;import java.util.ArrayList;import java.util.List;import lombok.Data;/** * Product * * @author wangjun */@Datapublic class Product {
        private String productName;    private String productCode;    private Integer price;    private String color;    private String remark;    public Product() {
        }    public Product(String productName, String productCode, Integer price, String color, String remark) {
            this.productName = productName;        this.productCode = productCode;        this.price = price;        this.color = color;        this.remark = remark;    }    public List getProductList() {
          List products = new ArrayList<>();        for(int i=1;i<100;i++){
                Product product1 = new Product("产品"+i, "cp"+i, 120+i, "红色"+i, "大卖"+i);            products.add(product1);        }        Product product = new Product();        product.setColor("222");        products.add(product);        return products;    }}

页眉页脚

package com.example.demo.pdf;import java.io.IOException;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Element;import com.itextpdf.text.ExceptionConverter;import com.itextpdf.text.Font;import com.itextpdf.text.Image;import com.itextpdf.text.PageSize;import com.itextpdf.text.Paragraph;import com.itextpdf.text.Phrase;import com.itextpdf.text.Rectangle;import com.itextpdf.text.pdf.BaseFont;import com.itextpdf.text.pdf.ColumnText;import com.itextpdf.text.pdf.GrayColor;import com.itextpdf.text.pdf.PdfContentByte;import com.itextpdf.text.pdf.PdfPCell;import com.itextpdf.text.pdf.PdfPTable;import com.itextpdf.text.pdf.PdfPageEventHelper;import com.itextpdf.text.pdf.PdfTemplate;import com.itextpdf.text.pdf.PdfWriter;/** * 页眉页脚&水印 * * @author wangjun */public class MyHeaderFooter extends PdfPageEventHelper {
        /**     * 总页数     */    private PdfTemplate totalPage;    private Font hfFont;    private Font watermarkFont;    {
            try {
                BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);            hfFont = new Font(bfChinese, 8, Font.NORMAL);            watermarkFont = new Font(bfChinese, 40, Font.BOLD, new GrayColor(0.95f));        } catch (DocumentException | IOException e) {
                e.printStackTrace();        }    }    /**     * 打开文档时,创建一个总页数的模版     */    @Override    public void onOpenDocument(PdfWriter writer, Document document) {
            PdfContentByte cb = writer.getDirectContent();        totalPage = cb.createTemplate(30, 12);    }    /**     * 一页加载完成触发,写入页眉和页脚     */    @Override    public void onEndPage(PdfWriter writer, Document document) {
            // 水印        for(int i=0 ; i<4; i++) {
                for(int j=0; j<7; j++) {
                    ColumnText.showTextAligned(writer.getDirectContentUnder(),                        Element.ALIGN_CENTER,                        new Phrase("好享家", watermarkFont),                        (50.5f+i*150),                        (40.0f+j*150),                        writer.getPageNumber() % 2 == 1 ? 45 : -45);            }        }        PdfPTable table = new PdfPTable(3);        try {
                // 总宽            table.setTotalWidth(PageSize.A4.getWidth()-80);            // 设置表格宽3列            table.setWidths(new int[]{
    24, 24, 3});            table.setLockedWidth(true);            table.getDefaultCell().setFixedHeight(0);            table.getDefaultCell().setBorder(Rectangle.NO_BORDER);            // 可以直接使用addCell(str),不过不能指定字体,中文无法显示            table.addCell(new Paragraph("hosjoy", hfFont));            // 水平对齐            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);            table.addCell(new Paragraph("第" + writer.getPageNumber() + "页/", hfFont));            // 总页数            PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));            // 去掉表格边框            cell.setBorder(Rectangle.BOTTOM);            table.addCell(cell);            // 将页眉写到document中,位置可以指定,指定到下面就是页脚            table.writeSelectedRows(0, -1, 40, 20 , writer.getDirectContent());        } catch (Exception de) {
                throw new ExceptionConverter(de);        }    }    /**     * 全部完成后,将总页数的pdf模版写到指定位置     */    @Override    public void onCloseDocument(PdfWriter writer, Document document) {
            String text = "总" + (writer.getPageNumber()) + "页";        ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text, hfFont), 2, 2, 0);    }}

测试

package com.example.demo.pdf;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.itextpdf.text.Anchor;import com.itextpdf.text.BaseColor;import com.itextpdf.text.Chunk;import com.itextpdf.text.Document;import com.itextpdf.text.Element;import com.itextpdf.text.Font;import com.itextpdf.text.Image;import com.itextpdf.text.PageSize;import com.itextpdf.text.Paragraph;import com.itextpdf.text.Phrase;import com.itextpdf.text.pdf.BaseFont;import com.itextpdf.text.pdf.PdfPCell;import com.itextpdf.text.pdf.PdfPTable;import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.text.pdf.draw.DottedLineSeparator;import com.itextpdf.text.pdf.draw.LineSeparator;import lombok.extern.slf4j.Slf4j;/** * 标题 * * @author wangjun */@Slf4j@RestController@RequestMapping("/api")public class PdfTest {
        /**     * 定义全局的字体静态变量     */    private static Font titlefont;    private static Font headfont;    private static Font keyfont;    private static Font textfont;    private static Font font;    /* 静态代码块*/    static {
            try {
                // 不同字体(这里定义为同一种字体:包含不同字号、不同style)            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);            titlefont = new Font(bfChinese, 16, Font.BOLD);            headfont = new Font(bfChinese, 14, Font.BOLD);            keyfont = new Font(bfChinese, 10, Font.BOLD);            textfont = new Font(bfChinese, 10, Font.NORMAL);            font = new Font(bfChinese, 14, Font.BOLD);        } catch (Exception e) {
                e.printStackTrace();        }    }    @RequestMapping("download-pdf")    public void downloadFileAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
            String fileName = "hello.pdf";        // attachment; 下载附件方式        response.setCharacterEncoding(request.getCharacterEncoding());        response.setContentType("application/pdf");        response.setHeader("Content-Disposition", "filename=" + fileName);        // 1.新建document对象        Document document = new Document(PageSize.A4);        // 2.建立一个书写器(Writer)与document对象关联        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());        // 水印 页眉/页脚        writer.setPageEvent(new MyHeaderFooter());        // 3.打开文档        document.open();        // 标题        document.addTitle("hosjoy@pdf");        // 作者        document.addAuthor("wangjun");        // 主题        document.addSubject("iText pdf test");        // 关键字        document.addKeywords("test");        // 创建者        document.addCreator("Creator");        // 4.向文档中添加内容        generatePDF(document);        // 5.关闭文档        document.close();    }    /**     * 生成PDF文件     */    private void generatePDF(Document document) throws Exception {
            // 段落        Paragraph paragraph = new Paragraph("Hello I Text 5", titlefont);        //设置文字居中 0靠左   1,居中     2,靠右        paragraph.setAlignment(1);        //设置左缩进        paragraph.setIndentationLeft(12);        //设置右缩进        paragraph.setIndentationRight(12);        //设置首行缩进        paragraph.setFirstLineIndent(24);        //行间距        paragraph.setLeading(20f);        //设置段落上空白        paragraph.setSpacingBefore(5f);        //设置段落下空白        paragraph.setSpacingAfter(10f);        // 直线        Paragraph p1 = new Paragraph();        p1.add(new Chunk(new LineSeparator()));        // 点线        Paragraph p2 = new Paragraph();        p2.add(new Chunk(new DottedLineSeparator()));        // 超链接        Anchor anchor = new Anchor(new Paragraph("超链接", titlefont));        anchor.setReference("www.baidu.com");        // 添加图片        Image image = Image.getInstance("http://xx.hosjoy.com/img/hosjoy_logo.png");        image.setAlignment(Image.ALIGN_LEFT);        // 依照比例缩放        image.scalePercent(20);        // 表格        PdfPTable table = createTable(new float[]{
    10, 12, 12, 10, 10});        table.addCell(createCell("测试PDF表头标题", headfont, Element.ALIGN_CENTER, 6, false));        table.addCell(createCell("编码", keyfont, Element.ALIGN_CENTER, BaseColor.GRAY));        table.addCell(createCell("名称", keyfont, Element.ALIGN_CENTER, BaseColor.GRAY));        table.addCell(createCell("价格", keyfont, Element.ALIGN_CENTER, BaseColor.GRAY));        table.addCell(createCell("颜色", keyfont, Element.ALIGN_CENTER, BaseColor.GRAY));        table.addCell(createCell("备注", keyfont, Element.ALIGN_CENTER, BaseColor.GRAY));        int totalQuantity = 0;        List list = new Product().getProductList();        for (Product product : list) {
                table.addCell(createCell(product.getProductCode(), textfont));            table.addCell(createCell(product.getProductName(), textfont));            table.addCell(createCell(String.valueOf(product.getPrice()), textfont));            table.addCell(createCell(product.getColor(), textfont));            table.addCell(createCell(product.getRemark(), textfont));            totalQuantity++;        }        table.addCell(createCell("总计", keyfont));        table.addCell(createCell("", textfont, Element.ALIGN_CENTER, 3));        table.addCell(createCell(totalQuantity + "", textfont, Element.ALIGN_CENTER));        document.add(paragraph);        document.add(anchor);        document.add(p2);        document.add(image);        document.add(p1);        document.add(table);    }    /**     * 创建单元格     */    private PdfPCell createCell(String value) {
            PdfPCell cell = new PdfPCell();        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);        cell.setHorizontalAlignment(Element.ALIGN_CENTER);        cell.setPhrase(new Phrase(value, font));        return cell;    }    /**     * 创建单元格(指定字体)     */    private PdfPCell createCell(String value, Font font) {
            PdfPCell cell = createCell(value);        cell.setPhrase(new Phrase(value, font));        return cell;    }    /**     * 创建单元格(指定字体、水平)     */    private PdfPCell createCell(String value, Font font, int align) {
            PdfPCell cell = createCell( value,  font);        cell.setHorizontalAlignment(align);        return cell;    }    /**     * 创建单元格(指定字体、水平)     */    private PdfPCell createCell(String value, Font font, int align, BaseColor baseColor) {
            PdfPCell cell = createCell( value,  font,align);        cell.setBackgroundColor(baseColor);        return cell;    }    /**     * 创建单元格(指定字体、水平居..、单元格跨x列合并)     */    private PdfPCell createCell(String value, Font font, int align, int colspan) {
            PdfPCell cell = createCell( value,  font,align);        cell.setColspan(colspan);        return cell;    }    /**     * 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)     */    private PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
            PdfPCell cell = createCell( value,  font,align,colspan);        cell.setPadding(3.0f);        if (!boderFlag) {
                cell.setBorder(0);            cell.setPaddingTop(15.0f);            cell.setPaddingBottom(8.0f);        } else {
                cell.setBorder(0);            cell.setPaddingTop(0.0f);            cell.setPaddingBottom(15.0f);        }        return cell;    }    /**     * 创建指定列宽、列数的表格     */    private PdfPTable createTable(float[] widths) {
            PdfPTable table = new PdfPTable(widths);        table.setTotalWidth(520);        table.setLockedWidth(true);        table.setHorizontalAlignment(Element.ALIGN_CENTER);        table.getDefaultCell().setBorder(1);        return table;    }}

启动Spring Boot项目访问 /api/download-pdf

《itext设置字体间距_Java使用iText生成pdf》

    原文作者:weixin_39774044
    原文地址: https://blog.csdn.net/weixin_39774044/article/details/109994952
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞