纯PDFBOX操作pdf(支持中文)

# 话不多说直接看实例

    <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.13</version>
        </dependency>
复制代码
public class Column {

    private String name;
    private float width;

    public Column(String name, float width) {
        this.name = name;
        this.width = width;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getWidth() {
        return width;
    }

    public void setWidth(float width) {
        this.width = width;
    }
}
复制代码
复制代码
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;

import java.util.List;

public class Table {

    // Table attributes
    private float margin;
    private float height;
    private PDRectangle pageSize;
    private boolean isLandscape;
    private float rowHeight;

    // font attributes
    private PDFont textFont;
    private float fontSize;

    // Content attributes
    private Integer numberOfRows;
    private String title;
    private List<Column> columns;
    private String[][] content;
    private float cellMargin;

    public Table() {
    }

    public Integer getNumberOfColumns() {
        return this.getColumns().size();
    }

    public float getWidth() {
        float tableWidth = 0f;
        for (Column column : columns) {
            tableWidth += column.getWidth();
        }
        return tableWidth;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public float getMargin() {
        return margin;
    }

    public void setMargin(float margin) {
        this.margin = margin;
    }

    public PDRectangle getPageSize() {
        return pageSize;
    }

    public void setPageSize(PDRectangle pageSize) {
        this.pageSize = pageSize;
    }

    public PDFont getTextFont() {
        return textFont;
    }

    public void setTextFont(PDFont textFont) {
        this.textFont = textFont;
    }

    public float getFontSize() {
        return fontSize;
    }

    public void setFontSize(float fontSize) {
        this.fontSize = fontSize;
    }

    public String[] getColumnsNamesAsArray() {
        String[] columnNames = new String[getNumberOfColumns()];
        for (int i = 0; i < getNumberOfColumns() - 1; i++) {
            columnNames[i] = columns.get(i).getName();
        }
        return columnNames;
    }

    public List<Column> getColumns() {
        return columns;
    }

    public void setColumns(List<Column> columns) {
        this.columns = columns;
    }

    public Integer getNumberOfRows() {
        return numberOfRows;
    }

    public void setNumberOfRows(Integer numberOfRows) {
        this.numberOfRows = numberOfRows;
    }

    public float getHeight() {
        return height;
    }

    public void setHeight(float height) {
        this.height = height;
    }

    public float getRowHeight() {
        return rowHeight;
    }

    public void setRowHeight(float rowHeight) {
        this.rowHeight = rowHeight;
    }

    public String[][] getContent() {
        return content;
    }

    public void setContent(String[][] content) {
        this.content = content;
    }

    public float getCellMargin() {
        return cellMargin;
    }

    public void setCellMargin(float cellMargin) {
        this.cellMargin = cellMargin;
    }

    public boolean isLandscape() {
        return isLandscape;
    }

    public void setLandscape(boolean isLandscape) {
        this.isLandscape = isLandscape;
    }
}
复制代码
复制代码
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;

import java.util.List;

public class TableBuilder {

    private Table table = new Table();

    public TableBuilder setTitle(String title) {
        table.setTitle(title);
        return this;
    }


    public TableBuilder setHeight(float height) {
        table.setHeight(height);
        return this;
    }

    public TableBuilder setNumberOfRows(Integer numberOfRows) {
        table.setNumberOfRows(numberOfRows);
        return this;
    }

    public TableBuilder setRowHeight(float rowHeight) {
        table.setRowHeight(rowHeight);
        return this;
    }

    public TableBuilder setContent(String[][] content) {
        table.setContent(content);
        return this;
    }

    public TableBuilder setColumns(List<Column> columns) {
        table.setColumns(columns);
        return this;
    }

    public TableBuilder setCellMargin(float cellMargin) {
        table.setCellMargin(cellMargin);
        return this;
    }

    public TableBuilder setMargin(float margin) {
        table.setMargin(margin);
        return this;
    }

    public TableBuilder setPageSize(PDRectangle pageSize) {
        table.setPageSize(pageSize);
        return this;
    }

    public TableBuilder setLandscape(boolean landscape) {
        table.setLandscape(landscape);
        return this;
    }

    public TableBuilder setTextFont(PDFont textFont) {
        table.setTextFont(textFont);
        return this;
    }

    public TableBuilder setFontSize(float fontSize) {
        table.setFontSize(fontSize);
        return this;
    }

    public Table build() {
        return table;
    }
}
复制代码
复制代码
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType0Font;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;


public class PDFTableGenerator {

    // Generates document from Table object
    public void generatePDF(Table table) throws IOException {
        PDDocument doc = null;
        try {
            doc = new PDDocument();
            drawTable(doc, table);
            doc.save("D:\\file\\sample.pdf");
        } finally {
            if (doc != null) {
                doc.close();
            }
        }
    }

    // Configures basic setup for the table and draws it page by page
    public void drawTable(PDDocument doc, Table table) throws IOException {
        // Calculate pagination
        Integer rowsPerPage = new Double(Math.floor(table.getHeight() / table.getRowHeight())).intValue() - 1; // subtract
        Integer numberOfPages = new Double(Math.ceil(table.getNumberOfRows().floatValue() / rowsPerPage)).intValue();

        // Generate each page, get the content and draw it
        for (int pageCount = 0; pageCount < numberOfPages; pageCount++) {
            PDPage page = generatePage(doc, table);
            PDPageContentStream contentStream = generateContentStream(doc, page, table);
            if (pageCount == 0) {
                //写标题
                contentStream.beginText();
                // 文字位置
                contentStream.setFont(PDType0Font.load(doc, new File("C:\\Windows\\Fonts\\simfang.TTF")), 18);
                contentStream.newLineAtOffset(table.getWidth() / 2 + 20, table.getHeight() + table.getMargin() + 40);
                // 插入文本
                contentStream.showText(table.getTitle());
                contentStream.endText();

                //导出时间
                contentStream.beginText();
                contentStream.setFont(PDType0Font.load(doc, new File("C:\\Windows\\Fonts\\simfang.TTF")), 8);
                contentStream.newLineAtOffset(table.getWidth() - 20, table.getHeight() + table.getMargin() + 10);
                // 插入文本
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                contentStream.showText("批单导出日期:"+format.format(new Date()));
                contentStream.endText();

                contentStream.setFont(PDType0Font.load(doc, new File("C:\\Windows\\Fonts\\simfang.TTF")), 10);
                String[][] currentPageContent = getContentForCurrentPage(table, rowsPerPage, pageCount);
                drawCurrentPage(table, currentPageContent, contentStream);
            } else {
                String[][] currentPageContent = getContentForCurrentPage(table, rowsPerPage, pageCount);
                drawCurrentPage(table, currentPageContent, contentStream);
            }
        }
    }

    // Draws current page table grid and border lines and content
    private void drawCurrentPage(Table table, String[][] currentPageContent, PDPageContentStream contentStream)
            throws IOException {
        float tableTopY = table.isLandscape() ? table.getPageSize().getWidth() - table.getMargin() : table.getPageSize().getHeight() - table.getMargin();

        // Draws grid and borders
        drawTableGrid(table, currentPageContent, contentStream, tableTopY);

        // Position cursor to start drawing content
        float nextTextX = table.getMargin() + table.getCellMargin();
        // Calculate center alignment for text in cell considering font height
        float nextTextY = tableTopY - (table.getRowHeight() / 2)
                - ((table.getTextFont().getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * table.getFontSize()) / 4);

        // Write column headers
        writeContentLine(table.getColumnsNamesAsArray(), contentStream, nextTextX, nextTextY, table);
        nextTextY -= table.getRowHeight();
        nextTextX = table.getMargin() + table.getCellMargin();

        // Write content
        for (int i = 0; i < currentPageContent.length; i++) {
            writeContentLine(currentPageContent[i], contentStream, nextTextX, nextTextY, table);
            nextTextY -= table.getRowHeight();
            nextTextX = table.getMargin() + table.getCellMargin();
        }

        contentStream.close();
    }

    // Writes the content for one line
    private void writeContentLine(String[] lineContent, PDPageContentStream contentStream, float nextTextX, float nextTextY,
                                  Table table) throws IOException {
        Integer numberOfColumns = table.getNumberOfColumns();
        for (int i = 0; i < table.getNumberOfColumns(); i++) {
            String text = lineContent[i];
            contentStream.beginText();
            contentStream.moveTextPositionByAmount(nextTextX, nextTextY);
            contentStream.drawString(text != null ? text : "");
            contentStream.endText();
            nextTextX += table.getColumns().get(i).getWidth();
        }
    }

    private void drawTableGrid(Table table, String[][] currentPageContent, PDPageContentStream contentStream, float tableTopY)
            throws IOException {
        // Draw row lines
        float nextY = tableTopY;
        for (int i = 0; i <= currentPageContent.length + 1; i++) {
            contentStream.drawLine(table.getMargin(), nextY, table.getMargin() + table.getWidth(), nextY);
            nextY -= table.getRowHeight();
        }

        // Draw column lines
        final float tableYLength = table.getRowHeight() + (table.getRowHeight() * currentPageContent.length);
        final float tableBottomY = tableTopY - tableYLength;
        float nextX = table.getMargin();
        for (int i = 0; i < table.getNumberOfColumns(); i++) {
            contentStream.drawLine(nextX, tableTopY, nextX, tableBottomY);
            nextX += table.getColumns().get(i).getWidth();
        }
        contentStream.drawLine(nextX, tableTopY, nextX, tableBottomY);
    }

    private String[][] getContentForCurrentPage(Table table, Integer rowsPerPage, int pageCount) {
        int startRange = pageCount * rowsPerPage;
        int endRange = (pageCount * rowsPerPage) + rowsPerPage;
        if (endRange > table.getNumberOfRows()) {
            endRange = table.getNumberOfRows();
        }
        return Arrays.copyOfRange(table.getContent(), startRange, endRange);
    }

    private PDPage generatePage(PDDocument doc, Table table) {
        PDPage page = new PDPage();
        page.setMediaBox(table.getPageSize());
        page.setRotation(table.isLandscape() ? 90 : 0);
        doc.addPage(page);
        return page;
    }

    private PDPageContentStream generateContentStream(PDDocument doc, PDPage page, Table table) throws IOException {
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
        // User transformation matrix to change the reference when drawing.
        // This is necessary for the landscape position to draw correctly
        if (table.isLandscape()) {
            contentStream.concatenate2CTM(0, 1, -1, 0, table.getPageSize().getWidth(), 0);
        }
        contentStream.setFont(PDType0Font.load(doc, new File("C:\\Windows\\Fonts\\simfang.TTF")), 10);
        return contentStream;
    }
}
复制代码
复制代码
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PDFSample {

    // Page configuration
    private static final PDRectangle PAGE_SIZE = PDRectangle.A4;
    private static final float MARGIN = 90;
    private static final boolean IS_LANDSCAPE = true;

    // Font configuration
    private static final PDFont TEXT_FONT = PDType1Font.HELVETICA;
    private static final float FONT_SIZE = 10;

    // Table configuration
    private static final float ROW_HEIGHT = 15;
    private static final float CELL_MARGIN = 2;

    public static void main(String[] args) throws IOException {
        new PDFTableGenerator().generatePDF(createContent());
    }

    private static Table createContent() {
        String title="支付凭证号:"+"00000000000000";
        // Total size of columns must not be greater than table width.
        List<Column> columns = new ArrayList<Column>();
        columns.add(new Column("李四",80));
        columns.add(new Column("LastName", 90));
        columns.add(new Column("Email", 80));
        columns.add(new Column("ZipCode", 83));
        columns.add(new Column("MailOptIn", 80));
        columns.add(new Column("Code", 80));
        columns.add(new Column("Branch", 89));


        String[][] content = {

                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },
                { "张三", "LastName", "fakemail@mock.com", "12345", "yes", "XH4234FSD", "4334" },

    };


        float tableHeight = IS_LANDSCAPE ? PAGE_SIZE.getWidth() - (2 * MARGIN) : PAGE_SIZE.getHeight() - (2 * MARGIN);

        Table table = new TableBuilder()
                .setTitle(title)
            .setCellMargin(CELL_MARGIN)
            .setColumns(columns)
            .setContent(content)
            .setHeight(tableHeight)
            .setNumberOfRows(content.length)
            .setRowHeight(ROW_HEIGHT)
            .setMargin(MARGIN)
            .setPageSize(PAGE_SIZE)
            .setLandscape(IS_LANDSCAPE)
            .setTextFont(TEXT_FONT)
            .setFontSize(FONT_SIZE)
            .build();
        return table;
    }
}
复制代码

本文作者:zydjjcpdszylddpll

本文链接:https://www.cnblogs.com/jyfs/p/15119995.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   zydjjcpdszylddpll  阅读(3379)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起