如何使用Apache PDFBox打印页面no?

发布于 2025-02-03 04:53:09 字数 346 浏览 5 评论 0原文

我有一个PDF文件,其中我必须使用Java中的Apache PDFBox库在PDF的每个页面上打印页面。 PDF有一个具有动态内容的表,我不知道我的内容需要多少页来在PDF上打印,因为它包含一个带有动态数据的表。

例如: - 在创建PDF时,文件可能具有4或5页,在这种情况下,我必须在PDF页脚上的每个页面上打印页面。像下面的那样,

假设内容将在

第1页的PDF中的4页上打印在第1页第1页,of 4

第2页第2页,第4页,of 4

第3页,第3页第3页,共4页

第4页第4页,共4页

I have a PDF file where I have to print page no on each page of PDF using the Apache PDFBox library in Java.
And Pdf has a table with dynamic content I don't know how many pages my content will be required to print on PDF because it contains a table with dynamic data.

For e.g:-
While creating the PDF a file may have 4 or 5 pages in that case I have to print page no on each page at the footer of the PDF. like below

Let's assume content will be printed on 4 pages in PDF

On page no 1 Page 1 of 4

On page no 2 Page 2 of 4

On page no 3 Page 3 of 4

On page no 4 Page 4 of 4

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回忆那么伤 2025-02-10 04:53:09
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDMMType1Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.vandeseer.easytable.RepeatedHeaderTableDrawer;
import org.vandeseer.easytable.structure.Row;
import org.vandeseer.easytable.structure.Table;
import org.vandeseer.easytable.structure.cell.TextCell;

import java.awt.*;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicInteger;

//pdf with table and page no
public class SimplePDF {
    public static void main(String[] args) {
        try (PDDocument document = new PDDocument()) {
            final PDPage page = new PDPage(PDRectangle.A4);

            // create table with header and set default settings like each col width, border, font (family, size), padding etc.
            Table.TableBuilder table = Table.builder()
                    .addColumnsOfWidth(150F, 150F, 150F)
                    .borderWidth(1F)
                    .borderColor(Color.lightGray)
                    .padding(8F)
                    .font(PDType1Font.HELVETICA)
                    .fontSize(10)
                    .addRow(
                            // header column names
                            Row.builder()
                                    .font(PDMMType1Font.HELVETICA_BOLD)
                                    .add(TextCell.builder().text("Name").build())
                                    .add(TextCell.builder().text("Age").build())
                                    .add(TextCell.builder().text("Country").build())
                                    .build()
                    );

            //add multiple rows to table
            for (int i = 0; i < 100; i++) {
                table.addRow(
                        Row.builder()
                                .add(TextCell.builder().text("John").build())
                                .add(TextCell.builder().text("20").build())
                                .add(TextCell.builder().text("Any").build())
                                .build()
                );
            }

            //use RepeatedHeaderTableDrawer builder class to repeat header row in all page of pdf
            RepeatedHeaderTableDrawer repeatedHeaderTableDrawer = RepeatedHeaderTableDrawer.builder()
                    .startX(20f)
                    .startY(page.getMediaBox().getUpperRightY())
                    .numberOfRowsToRepeat(1) //specify the no of row wants to repeat on each page of pdf
                    .table(table.build())
                    .build();

            //draw the table on pdf document
            repeatedHeaderTableDrawer.draw(() -> document, () -> new PDPage(PDRectangle.A4), 30);

            //Print the page no on each page of pdf because know we know how many no of pages do this pdf has
            //because it print the table on each page based on the data now we can print the page no on each page of pdf
            //for e.g 'Page 1 of 4'    if we have 4 no of page in pdf then this will be the output on the first page of pdf

            int totalNoOfPages = document.getNumberOfPages();
            AtomicInteger pageCounter = new AtomicInteger(1);

            //iterate each page and print page no on each page at the footer of the pdf
            document.getPages().forEach(pdfPage -> {
                float bottomXAxis = pdfPage.getMediaBox().getLowerLeftX();
                float bottomYAxis = pdfPage.getMediaBox().getLowerLeftY();
                String currentPageNo = MessageFormat.format("Page {0} of {1}", pageCounter.getAndIncrement(), totalNoOfPages);
                try {
                    PDPageContentStream contentStream = new PDPageContentStream(document, pdfPage, PDPageContentStream.AppendMode.APPEND, true);
                    contentStream.beginText();
                    contentStream.setFont(PDMMType1Font.HELVETICA, 10);
                    contentStream.newLineAtOffset(bottomXAxis + 15, bottomYAxis + 5);
                    contentStream.showText(currentPageNo);
                    contentStream.endText();
                    contentStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            //save the pdf file
            document.save("example.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("PDF created");
        }
    }
}

上面的代码将生成一个PDF文件,该文件包含PDF每个页面上的可重复标头行的表和每个页面上的页面。结果对您来说可能略有不同,但对我有用。
2使用库,一个是 apache pdfbox easytable 使用apachepdfbox

依赖性的库来创建表格

<dependency>
   <groupId>org.apache.pdfbox</groupId>
   <artifactId>pdfbox</artifactId>
   <version>2.0.22</version>
</dependency>
<dependency>
   <groupId>com.github.vandeseer</groupId>
   <artifactId>easytable</artifactId>
   <version>0.8.5</version>
</dependency>
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDMMType1Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.vandeseer.easytable.RepeatedHeaderTableDrawer;
import org.vandeseer.easytable.structure.Row;
import org.vandeseer.easytable.structure.Table;
import org.vandeseer.easytable.structure.cell.TextCell;

import java.awt.*;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicInteger;

//pdf with table and page no
public class SimplePDF {
    public static void main(String[] args) {
        try (PDDocument document = new PDDocument()) {
            final PDPage page = new PDPage(PDRectangle.A4);

            // create table with header and set default settings like each col width, border, font (family, size), padding etc.
            Table.TableBuilder table = Table.builder()
                    .addColumnsOfWidth(150F, 150F, 150F)
                    .borderWidth(1F)
                    .borderColor(Color.lightGray)
                    .padding(8F)
                    .font(PDType1Font.HELVETICA)
                    .fontSize(10)
                    .addRow(
                            // header column names
                            Row.builder()
                                    .font(PDMMType1Font.HELVETICA_BOLD)
                                    .add(TextCell.builder().text("Name").build())
                                    .add(TextCell.builder().text("Age").build())
                                    .add(TextCell.builder().text("Country").build())
                                    .build()
                    );

            //add multiple rows to table
            for (int i = 0; i < 100; i++) {
                table.addRow(
                        Row.builder()
                                .add(TextCell.builder().text("John").build())
                                .add(TextCell.builder().text("20").build())
                                .add(TextCell.builder().text("Any").build())
                                .build()
                );
            }

            //use RepeatedHeaderTableDrawer builder class to repeat header row in all page of pdf
            RepeatedHeaderTableDrawer repeatedHeaderTableDrawer = RepeatedHeaderTableDrawer.builder()
                    .startX(20f)
                    .startY(page.getMediaBox().getUpperRightY())
                    .numberOfRowsToRepeat(1) //specify the no of row wants to repeat on each page of pdf
                    .table(table.build())
                    .build();

            //draw the table on pdf document
            repeatedHeaderTableDrawer.draw(() -> document, () -> new PDPage(PDRectangle.A4), 30);

            //Print the page no on each page of pdf because know we know how many no of pages do this pdf has
            //because it print the table on each page based on the data now we can print the page no on each page of pdf
            //for e.g 'Page 1 of 4'    if we have 4 no of page in pdf then this will be the output on the first page of pdf

            int totalNoOfPages = document.getNumberOfPages();
            AtomicInteger pageCounter = new AtomicInteger(1);

            //iterate each page and print page no on each page at the footer of the pdf
            document.getPages().forEach(pdfPage -> {
                float bottomXAxis = pdfPage.getMediaBox().getLowerLeftX();
                float bottomYAxis = pdfPage.getMediaBox().getLowerLeftY();
                String currentPageNo = MessageFormat.format("Page {0} of {1}", pageCounter.getAndIncrement(), totalNoOfPages);
                try {
                    PDPageContentStream contentStream = new PDPageContentStream(document, pdfPage, PDPageContentStream.AppendMode.APPEND, true);
                    contentStream.beginText();
                    contentStream.setFont(PDMMType1Font.HELVETICA, 10);
                    contentStream.newLineAtOffset(bottomXAxis + 15, bottomYAxis + 5);
                    contentStream.showText(currentPageNo);
                    contentStream.endText();
                    contentStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            //save the pdf file
            document.save("example.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("PDF created");
        }
    }
}

The above code will generate a pdf file that contains the table with repeatable header row on each page of pdf and page no on each page. Results might be slightly different for you but it works for me.
2 libraries are used one is Apache PDFBox and EasyTable to create tables using ApachePDFBox

dependency for libraries are:-

<dependency>
   <groupId>org.apache.pdfbox</groupId>
   <artifactId>pdfbox</artifactId>
   <version>2.0.22</version>
</dependency>
<dependency>
   <groupId>com.github.vandeseer</groupId>
   <artifactId>easytable</artifactId>
   <version>0.8.5</version>
</dependency>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文