龙空技术网

Java PDF导出方案iText 入门教程

DOKER 312

前言:

此刻同学们对“javaitext”大约比较关注,兄弟们都想要分析一些“javaitext”的相关知识。那么小编在网摘上汇集了一些对于“javaitext””的相关知识,希望我们能喜欢,看官们一起来了解一下吧!

iText 7是iText强大的PDF工具包的最新版本,用于PDF生成,PDF编程,处理和操作,如数字签名等。

一、引入依赖

在pom文件中引入如下依赖:

<dependencies>    <dependency>        <groupId>com.itextpdf</groupId>        <artifactId>kernel</artifactId>        <version>7.0.4</version>    </dependency>    <dependency>        <groupId>com.itextpdf</groupId>        <artifactId>io</artifactId>        <version>7.0.4</version>    </dependency>    <dependency>        <groupId>com.itextpdf</groupId>        <artifactId>layout</artifactId>        <version>7.0.4</version>    </dependency>    <dependency>        <groupId>com.itextpdf</groupId>        <artifactId>forms</artifactId>        <version>7.0.4</version>    </dependency>    <dependency>        <groupId>com.itextpdf</groupId>        <artifactId>pdfa</artifactId>        <version>7.0.4</version>    </dependency>    <dependency>        <groupId>com.itextpdf</groupId>        <artifactId>pdftest</artifactId>        <version>7.0.4</version>    </dependency></dependencies>
二、基本示例1、创建一个Hello World
import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Paragraph;import java.io.File;import java.io.IOException;/** * Simple Hello World example. */public class C01E01_HelloWorld {        public static final String DEST = "results/chapter01/hello_world.pdf";        public static void main(String args[]) throws IOException {        File file = new File(DEST);        file.getParentFile().mkdirs();        new C01E01_HelloWorld().createPdf(DEST);    }        public void createPdf(String dest) throws IOException {        //Initialize PDF writer        PdfWriter writer = new PdfWriter(dest);        //Initialize PDF document        PdfDocument pdf = new PdfDocument(writer);                // Initialize document        Document document = new Document(pdf);        //Add paragraph to the document        document.add(new Paragraph("Hello World!"));        //Close document        document.close();    }}

显示了生成的 PDF 文档的外观:

让我们增加一些复杂性。让我们选择一种不同的字体,让我们将一些文本组织为列表;参见图 :

PdfWriter writer = new PdfWriter(dest);PdfDocument pdf = new PdfDocument(writer);Document document = new Document(pdf);// Create a PdfFontPdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);// Add a Paragraphdocument.add(new Paragraph("iText is:").setFont(font));// Create a ListList list = new List()    .setSymbolIndent(12)    .setListSymbol("\u2022")    .setFont(font);// Add ListItem objectslist.add(new ListItem("Never gonna give you up"))    .add(new ListItem("Never gonna let you down"))    .add(new ListItem("Never gonna run around and desert you"))    .add(new ListItem("Never gonna make you cry"))    .add(new ListItem("Never gonna say goodbye"))    .add(new ListItem("Never gonna tell a lie and hurt you"));// Add the listdocument.add(list);document.close();
2、 下面我们处理一些图像:
import com.itextpdf.io.image.ImageDataFactory;import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Image;import com.itextpdf.layout.element.Paragraph;import java.io.File;import java.io.IOException;/** * Simple image example. */public class C01E03_QuickBrownFox {    public static final String DOG = "src/main/resources/img/dog.bmp";    public static final String FOX = "src/main/resources/img/fox.bmp";            public static final String DEST = "results/chapter01/quick_brown_fox.pdf";        public static void main(String args[]) throws IOException {        File file = new File(DEST);        file.getParentFile().mkdirs();        new C01E03_QuickBrownFox().createPdf(DEST);    }        public void createPdf(String dest) throws IOException {        //Initialize PDF writer        PdfWriter writer = new PdfWriter(dest);        //Initialize PDF document        PdfDocument pdf = new PdfDocument(writer);                // Initialize document        Document document = new Document(pdf);                // Compose Paragraph        Image fox = new Image(ImageDataFactory.create(FOX));        Image dog = new Image(ImageDataFactory.create(DOG));        Paragraph p = new Paragraph("The quick brown ")                .add(fox)                .add(" jumps over the lazy ")                .add(dog);        // Add Paragraph to document        document.add(p);                //Close document        document.close();    }}
3、发布数据库

许多开发人员使用 iText 将数据库查询的结果发布到 PDF 文档。假设我们有一个包含美国所有州的数据库,并且我们希望创建一个 PDF,在表格中列出这些州以及每个州的一些信息:

mport com.itextpdf.io.font.constants.StandardFonts;import com.itextpdf.kernel.font.PdfFont;import com.itextpdf.kernel.font.PdfFontFactory;import com.itextpdf.kernel.geom.PageSize;import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Cell;import com.itextpdf.layout.element.Paragraph;import com.itextpdf.layout.element.Table;import com.itextpdf.layout.properties.UnitValue;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.StringTokenizer;/** * Simple table example. */public class C01E04_UnitedStates {    public static final String DATA = "src/main/resources/data/united_states.csv";    public static final String DEST = "results/chapter01/united_states.pdf";    public static void main(String args[]) throws IOException {        File file = new File(DEST);        file.getParentFile().mkdirs();        new C01E04_UnitedStates().createPdf(DEST);    }    public void createPdf(String dest) throws IOException {        //Initialize PDF writer        PdfWriter writer = new PdfWriter(dest);        //Initialize PDF document        PdfDocument pdf = new PdfDocument(writer);        // Initialize document        Document document = new Document(pdf, PageSize.A4.rotate());        document.setMargins(20, 20, 20, 20);        PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA);        PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);        Table table = new Table(UnitValue.createPercentArray(new float[]{4, 1, 3, 4, 3, 3, 3, 3, 1}))                .useAllAvailableWidth();        BufferedReader br = new BufferedReader(new FileReader(DATA));        String line = br.readLine();        process(table, line, bold, true);        while ((line = br.readLine()) != null) {            process(table, line, font, false);        }        br.close();        document.add(table);        //Close document        document.close();    }    public void process(Table table, String line, PdfFont font, boolean isHeader) {        StringTokenizer tokenizer = new StringTokenizer(line, ";");        while (tokenizer.hasMoreTokens()) {            if (isHeader) {                table.addHeaderCell(new Cell().add(new Paragraph(tokenizer.nextToken()).setFont(font)));            } else {                table.addCell(new Cell().add(new Paragraph(tokenizer.nextToken()).setFont(font)));            }        }    }}
三、简单功能实现

当我们谈论iText文档中的简单内容时,我们总是指写入PDF内容流的PDF语法。PDF定义了一系列运算符,例如我们在iText中为其创建moveTo()方法的m,为其创建lineTo()的l,以及为其创建stroke()的S。通过在PDF中组合这些操作数,或者在iText中组合这些方法,可以绘制路径和形状。

让我们来看一个小例子:

这是PDF语法,说:移动到位置(X = -406 ;Y = 0 ),然后构造一条到位置的路径 ( X = 406 ;Y = 0 );最后描边这条线——在这种情况下,“抚摸”意味着画画。如果我们想用 iText 创建这个 PDF 语法片段,它是这样的:

1、在画布上绘制线条

在画布上绘制线条:

此显示 X 轴和 Y 轴的 PDF 是使用轴示例创建的。让我们逐步检查此示例:

PdfDocument pdf = new PdfDocument(new PdfWriter(dest));PageSize ps = PageSize.A4.rotate();PdfPage page = pdf.addNewPage(ps);PdfCanvas canvas = new PdfCanvas(page);// Draw the axespdf.close();
2、图形状态

当前转换矩阵是页面图形状态的一部分。在图形状态中定义的其他值包括线条宽度、描边颜色(对于线条)、填充颜色(对于形状)等。在另一个教程中,我们将更深入地描述图形状态的每个值。现在,知道默认线宽为 1 个用户单位并且默认描边颜色为黑色就足够了。让我们绘制我们在图 2.1 中看到的那些轴:

//Draw X axiscanvas.moveTo(-(ps.getWidth() / 2 - 15), 0)        .lineTo(ps.getWidth() / 2 - 15, 0)        .stroke();//Draw X axis arrowcanvas.setLineJoinStyle(PdfCanvasConstants.LineJoinStyle.ROUND)        .moveTo(ps.getWidth() / 2 - 25, -10)        .lineTo(ps.getWidth() / 2 - 15, 0)        .lineTo(ps.getWidth() / 2 - 25, 10).stroke()        .setLineJoinStyle(PdfCanvasConstants.LineJoinStyle.MITER);//Draw Y axiscanvas.moveTo(0, -(ps.getHeight() / 2 - 15))        .lineTo(0, ps.getHeight() / 2 - 15)        .stroke();//Draw Y axis arrowcanvas.saveState()        .setLineJoinStyle(PdfCanvasConstants.LineJoinStyle.ROUND)        .moveTo(-10, ps.getHeight() / 2 - 25)        .lineTo(0, ps.getHeight() / 2 - 15)        .lineTo(10, ps.getHeight() / 2 - 25).stroke()        .restoreState();//Draw X seriffor (int i = -((int) ps.getWidth() / 2 - 61);    i < ((int) ps.getWidth() / 2 - 60); i += 40) {    canvas.moveTo(i, 5).lineTo(i, -5);}//Draw Y seriffor (int j = -((int) ps.getHeight() / 2 - 57);    j < ((int) ps.getHeight() / 2 - 56); j += 40) {    canvas.moveTo(5, j).lineTo(-5, j);}canvas.stroke();

大家好,我是Doker品牌的Sinbad,欢迎点赞和评论,您的鼓励是我们持续更新的动力!更多资料请前往Doker 多克

标签: #javaitext #java批量导出pdf