美文网首页Java技术分享Java 杂谈
Java 借助第三方jar包操作PDF工具类

Java 借助第三方jar包操作PDF工具类

作者: 墨迹嘿嘿 | 来源:发表于2019-01-21 21:59 被阅读24次

一直以来说写一个关于Java操作PDF的工具类,也没有时间去写,今天抽空写一个简单的工具类,拥有PDF中 换行,字体大小,字体设置,字体颜色,首行缩进,居中,居左,居右,增加新一页等功能,如果需要Table表格的可以用Cell这个方法就可以实现,这个工具类参数也比较多点,自己想优化的,可以写一个实体类来封装。

好了,废话不多说了。

首先我们引入需要的第三方jar包

  <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>

iText是著名的开放项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。

下面我们直接就用代码来描述。

package com.herbert.test;

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Herbert on 2019/1/21.
 */
public class PDFUtil {

    /**
     * document对象
     */
    private static Document document =  null;

    /**
     *  创建一个书写器,布局文本位置
     * @param leftSize 居左
     * @param rightSize 居右
     * @param onSize 居上
     * @param underSize 居下
     * @param path 存储位置
     * @throws Exception 初始化PDF错误
     */
    public PDFUtil(Integer leftSize , Integer rightSize , Integer onSize , Integer underSize, String path) throws Exception {
        try{
            // 新建document对象 第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
            document = new Document(PageSize.A4, leftSize, rightSize, onSize, underSize);
            // 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
            // 打开文件
            document.open();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("PDF初始化错误");
        }
    }

    /**
     *  书写每一个段落选择的字体
     *
     * @param fontType
     *             0 //楷体字
     *             1 //仿宋体
     *             2 //黑体
     *             字体需要可在追加
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public BaseFont addFontType(Integer fontType)  {
        BaseFont baseFont = null;
        try{

            switch (fontType){
                case 0:
                    //楷体字
                    baseFont = BaseFont.createFont("c://windows//fonts//simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    break;
                case 1:
                    //仿宋体
                    baseFont = BaseFont.createFont("c://windows//fonts//SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    break;
                case 2:
                    //黑体
                    baseFont = BaseFont.createFont("c://windows//fonts//SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    break;
            }
            return baseFont;
        }catch (Exception e){
            System.out.println("选择字体异常");
            e.printStackTrace();

        }
        return baseFont;
    }

    /**
     *  添加段落 -  段落位置( 0 居左  1 居中 2 居右)
     * @param fontType 选择字体
     *             0 //楷体字
     *             1 //仿宋体
     *             2 //黑体
     * @param fontSize 字体大小
     * @param color 字体颜色
     * @param alignment   0 居左  1 居中 2 居右
     * @param text 文本内容
     */
    public void addParagraph(Integer fontType , Integer fontSize,Color color ,Integer alignment ,String text){
        try{
            BaseFont chinese =addFontType(fontType);
            Font font = new Font(chinese, fontSize, Font.COURIER,color);
            Paragraph paragraph =new Paragraph(text,font);
            //居中显示
            paragraph.setAlignment(alignment);
            document.add(paragraph);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("添加段落异常");
        }
    }

    /**
     *  添加段落 -  首行缩进
     * @param fontType 选择字体
     *             0 //楷体字
     *             1 //仿宋体
     *             2 //黑体
     * @param fontSize 字体大小
     * @param color 字体颜色
     * @param index  首行缩进
     * @param text 文本内容
     */
    public void addTextIndent(Integer fontType , Integer fontSize,Color color ,Integer index ,String text){
        try{
            BaseFont chinese =addFontType(fontType);
            Font font = new Font(chinese, fontSize, Font.COURIER,color);
            Paragraph paragraph =new Paragraph(text,font);
            //设置首行缩进
            paragraph.setFirstLineIndent(index);
            document.add(paragraph);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("添加段落异常");
        }
    }

    /**
     *  添加新的一页
     */
    public void addPage(){
        try{
          document.newPage();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("添加段落异常");
        }
    }

    /**
     *  换行
     *  传入1是一行,以此递增
     * @param lineNum 换的行数
     */
    public void newLine(Integer lineNum) {
        try{
            for(int i =0 ; i<lineNum ; i++){
                document.add(new Paragraph("\n"));
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("换行错误");
        }
    }

    /**
     *  关闭文档
     */
    public void close (){

        // 关闭文档
        document.close();
    }

    public static void main(String args[]) throws Exception {
        PDFUtil pdfUtil = new PDFUtil(80, 80, 120, 120,"E:\\herbert\\test.pdf");
        pdfUtil.addParagraph(1,24,new Color(179, 91, 68),0,"我是0个测试案例--居左");
        pdfUtil.newLine(10);
        pdfUtil.addParagraph(1,24,new Color(75, 108, 179),1,"我是1个测试案例--居中 空行");
        pdfUtil.addParagraph(1,24,new Color(140, 109, 179),2,"我是2个测试案例--居右");
        pdfUtil.addPage();
        pdfUtil.addParagraph(1,24,new Color(73, 179, 130),1,"我是3个测试案例--新增页");
        pdfUtil.addParagraph(1,24,new Color(179, 91, 68),0,"我是0个测试案例--居左");
        pdfUtil.addTextIndent(1,24,new Color(41, 124, 179),28,"我是3个测试案例--首行缩进");
        pdfUtil.close();

    }

}

测试截图

image image image

注意事项:

1:这个方法目前只能在window上进行操作,如果在其他服务器上,由于使用window自带中文字体,需要对方法进行改进

2:目前只是对段落进行简单的操作,如果写发票那样的PDF文件,建议通过模板来实现,这样格式比较规整

猜您喜欢往期精选▼

1:POI对Excel进行读取操作

2:POI实现Excel导入数据库

3:二维码生成,包含文本,网址,图片等

4:自定义数据库连接池实现方式

5:开发中我们需要遵循的几个设计原则!

♡ 大 · 家 · 都 · 爱 ♡

1:【爬虫】广度优先遍历抓取数据概述

2:【爬虫】网络爬虫入门获取信息

3:【爬虫】数据结构实现折半查找的算法

4:“无形”战争:爬虫技术是武器,你的手机是一名不知情的士兵

1.jpg

相关文章

网友评论

    本文标题:Java 借助第三方jar包操作PDF工具类

    本文链接:https://www.haomeiwen.com/subject/qjohjqtx.html