【Java & PDF】使用Java生成PDF

写这篇博客的原因:

1、项目需求:NT客户为什么就不能对页面直接 Ctrl + P ? 点击另存为PDF他不好用吗?

2、前端JavaScript提供了对应的PDF生成的工具库,但是效果不理想,无法满足现实需求

3、使用Jsoup解析HTML,通过HTML代码转换PDF,当然实现的过程中被XML-Worker迫害到自闭【对不起,我说的标签必须有闭合标签才算】

4、综上所述,走投无路

 

于是二次看到这篇博客:

https://www.cnblogs.com/liaojie970/p/7132475.html

现在算是完全自行学习这技术了

创建IDEA项目编写案例:

普通Maven无骨架工程

导入坐标:

<dependencies>
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency>
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency
>
</dependencies>

快速入门上手的测试类:

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Echo42
 * @file PDF-Project
 * @create 2020年09月11日19:52
 * @description
 */
public class PdfTest {

    @Test
    public void testSample() {
        
        // 扩大指针作用域
        FileOutputStream fileOutputStream = null;
        Document document = null;

        try {
            // 文件名称
            final String pdfDocName = "quick-start.pdf";
            // 系统路径
            final String systemPath = "C:\\Users\\User-Dai\\Desktop\\Temp-File\\";
            
            // 创建PDF文档对象 com.itextpdf.text.Document 
            document = new Document();
            
            // 创建文件输出流,注入输出路径位置
            fileOutputStream = new FileOutputStream(systemPath + pdfDocName);

            // 由 com.itextpdf.text.pdf.PdfWriter类的获取实例方法得到PDF文档对象和文件输出流对象
            PdfWriter.getInstance(document, fileOutputStream);
            
            // open方法似乎是表示允许写入内容
            document.open();

            // 添加文本内容 com.itextpdf.text.Paragraph表示文本段落实例
            document.add(new Paragraph("Hello Itext PDF !!!"));

        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 资源释放
            document.close();
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

生成的效果:

一些文档描述信息,不重要:

    @Test
    public void sortOfSettings() throws Exception {

        final String pdfDocName = "quick-start.pdf";
        final String systemPath = "C:\\Users\\User-Dai\\Desktop\\Temp-File\\";

        // 设置页面大小
        Rectangle rectangle = new Rectangle(PageSize.A4);
        // 页面对象可以设置背景色
        rectangle.setBackgroundColor(BaseColor.GRAY);

        Document document = new Document(rectangle);

        FileOutputStream fileOutputStream = new FileOutputStream(systemPath + pdfDocName);

        PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOutputStream);
        // 设置PDF版本
        pdfWriter.setPdfVersion(PdfWriter.VERSION_1_4);
        // 加密设置
//        pdfWriter.setEncryption(
//                "123".getBytes(),
//                "456".getBytes(),
//                PdfWriter.ALLOW_SCREENREADERS,
//                PdfWriter.STANDARD_ENCRYPTION_128
//        );

        // 标题设置
        document.addTitle("Title@How to use Java Create PDF");
        // 作者设置
        document.addAuthor("Author@Echo42Zone");
        // 主题设置
        document.addSubject("Subject@Create PDF Settings");
        // 关键字设置
        document.addKeywords("Keywords@Java Itext PDF ");
        // 创建时间
        document.addCreationDate();
        // 创建人
        document.addCreator("Creator@Echo42Zone");
        // 页边距
        document.setMargins(10,10,10,10);

        document.open();

        document.add(new Paragraph("Hello Itext PDF !!!"));

        // 加页
        document.newPage();

        document.close();
        fileOutputStream.close();
    }

 

文本设置:

块,短语,段落,列表:

    @Test
    public void sortOfSettings3() throws Exception {

        final String pdfDocName = "quick-start.pdf";
        final String systemPath = "C:\\Users\\User-Dai\\Desktop\\Temp-File\\";

        Rectangle rectangle = new Rectangle(PageSize.A4);
        Document document = new Document(rectangle);
        FileOutputStream fileOutputStream = new FileOutputStream(systemPath + pdfDocName);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOutputStream);
        pdfWriter.setPdfVersion(PdfWriter.VERSION_1_4);


        document.addAuthor("Author@Echo42Zone");
        document.addCreationDate();
        document.addCreator("Creator@Echo42Zone");
        document.setMargins(10,10,10,10);

        document.open();
        document.add(new Paragraph("Hello Itext PDF !!!"));

        //Chunk对象: a String, a Font, and some attributes
        document.add(new Chunk("China"));
        document.add(new Chunk(" "));
        Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
        Chunk id = new Chunk("chinese", font);
        id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
        id.setTextRise(6);
        document.add(id);
        document.add(Chunk.NEWLINE);

        document.add(new Chunk("Japan"));
        document.add(new Chunk(" "));
        Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
        Chunk id2 = new Chunk("japanese", font2);
        id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
        id2.setTextRise(6);
        id2.setUnderline(0.2f, -2f);
        document.add(id2);
        document.add(Chunk.NEWLINE);

        //Phrase对象: a List of Chunks with leading
        document.newPage();
        document.add(new Phrase("Phrase page"));

        Phrase director = new Phrase();
        Chunk name = new Chunk("China");
        name.setUnderline(0.2f, -2f);
        director.add(name);
        director.add(new Chunk(","));
        director.add(new Chunk(" "));
        director.add(new Chunk("chinese"));
        director.setLeading(24);
        document.add(director);

        Phrase director2 = new Phrase();
        Chunk name2 = new Chunk("Japan");
        name2.setUnderline(0.2f, -2f);
        director2.add(name2);
        director2.add(new Chunk(","));
        director2.add(new Chunk(" "));
        director2.add(new Chunk("japanese"));
        director2.setLeading(24);
        document.add(director2);

        //Paragraph对象: a Phrase with extra properties and a newline
        document.newPage();
        document.add(new Paragraph("Paragraph page"));

        Paragraph info = new Paragraph();
        info.add(new Chunk("China "));
        info.add(new Chunk("chinese"));
        info.add(Chunk.NEWLINE);
        info.add(new Phrase("Japan "));
        info.add(new Phrase("japanese"));
        document.add(info);

        //List对象: a sequence of Paragraphs called ListItem
        document.newPage();
        List list = new List(List.ORDERED);
        for (int i = 0; i < 10; i++) {
            ListItem item = new ListItem(String.format("%s: %d movies",
                    "country" + (i + 1), (i + 1) * 100), new Font(
                    Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
            List movielist = new List(List.ORDERED, List.ALPHABETICAL);
            movielist.setLowercase(List.LOWERCASE);
            for (int j = 0; j < 5; j++) {
                ListItem movieitem = new ListItem("Title" + (j + 1));
                List directorlist = new List(List.UNORDERED);
                for (int k = 0; k < 3; k++) {
                    directorlist.add(String.format("%s, %s", "Name1" + (k + 1),
                            "Name2" + (k + 1)));
                }
                movieitem.add(directorlist);
                movielist.add(movieitem);
            }
            item.add(movielist);
            list.add(item);
        }
        document.add(list);

        document.newPage();

        document.close();
        fileOutputStream.close();
    }

水平分割线:

Paragraph info = new Paragraph();
info.add(new Chunk(new LineSeparator()));

 

posted @ 2020-09-11 21:18  emdzz  阅读(1731)  评论(0编辑  收藏  举报