0

I am trying to add Page numbers to merged PDF files using Itext on top right corner of the pages, but my pdf content size is different, after merging the PDF's while trying to print the page sizes i am getting approximately same sizes(height and width) on each page, but i am not able see page numbers, because of content size difference. please see below code and pdf attachements which am using for merging PDFs and adding page numbers.

public class PageNumber {

    public static void main(String[] args) {
        PageNumber number = new PageNumber();
        try {
            String DOC_ONE_PATH = "C:/Users/Admin/Downloads/codedetailsforartwork/elebill.pdf";
            String DOC_TWO_PATH = "C:/Users/Admin/Downloads/codedetailsforartwork/PP-P0109916.pdf";
            String DOC_THREE_PATH = "C:/Users/Admin/Downloads/codedetailsforartwork/result.pdf";
            String[] files = { DOC_ONE_PATH, DOC_TWO_PATH };
         Document document = new Document();
         PdfCopy copy = new PdfCopy(document, new FileOutputStream(DOC_THREE_PATH));
         document.open();
         PdfReader reader;
         int n;
         for (int i = 0; i < files.length; i++) {
             reader = new PdfReader(files[i]);
             n = reader.getNumberOfPages();
             for (int page = 0; page < n; ) {
                 copy.addPage(copy.getImportedPage(reader, ++page));
             }
             copy.freeReader(reader);
             reader.close();
         }
         // step 5
         document.close();
            number.manipulatePdf(
                    "C:/Users/Admin/Downloads/codedetailsforartwork/result.pdf",
                    "C:/Users/Admin/Downloads/codedetailsforartwork/PP-P0109916_1.pdf");
        } catch (IOException | DocumentException | APIException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void manipulatePdf(String src, String dest)
            throws IOException, DocumentException, APIException {
        PdfReader reader = new PdfReader(src);
        int n = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        PdfContentByte pagecontent;
        for (int i = 0; i < n;) {
            pagecontent = stamper.getOverContent(++i);
            System.out.println(i);
            com.itextpdf.text.Rectangle pageSize = reader.getPageSize(i);
            pageSize.normalize();
            float height = pageSize.getHeight();
            float width = pageSize.getWidth();
            System.out.println(width + " " + height);
            ColumnText.showTextAligned(pagecontent, Element.ALIGN_CENTER,
                    new Phrase(String.format("page %d of %d", i, n)),
                    width - 200, height-85, 0);
        }
        stamper.close();
        reader.close();
    }
}

PDF files Zip

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165

2 Answers2

1

@Bruno's answer explains and/or references answer with explanations for all relevant facts on the issue at hand.

In a nutshell, the two issues of the OP's code are:

  • he uses reader.getPageSize(i); while this indeed returns the page size, PDF viewers do not display the whole page size but merely the crop box on it. Thus, the OP should use reader.getCropBox(i) instead. According to the PDF specification, "the crop box defines the region to which the contents of the page shall be clipped (cropped) when displayed or printed. ... The default value is the page’s media box."
  • he uses pageSize.getWidth() and pageSize.getHeight() to determine the upper right corner but should use pageSize.getRight() and pageSize.getTop() instead. The boxes defining the PDF coordinate system may not have the origin in their lower left corner.
mkl
  • 90,588
  • 15
  • 125
  • 265
  • I upvoted you for this nice concise explanation, but even with this the top right corner doesn't seem to always be in the top right corner... – user1566694 May 03 '17 at 19:40
  • @user1566694 Can you share an example, i.e. your code and the sample PDFs it doesn't work with? – mkl May 03 '17 at 20:09
  • I'm trying to create a margin. Apparently after doing that coordinates lose all meaning... Revisiting the problem of creating a margin.. – user1566694 May 04 '17 at 17:04
  • It was actually your code I was using. This seems to confuse pages as to where the boundaries are: http://stackoverflow.com/questions/21375150/how-to-resize-existing-pdf-page-size – user1566694 May 04 '17 at 17:30
  • @user1566694 I simply cannot reproduce your issue. As requested in a comment to [your recent question](http://stackoverflow.com/q/43791781/1729265): Please share a PDF with which I can reproduce the issue. – mkl May 05 '17 at 06:03
0

I don't understand why you are defining the position of the page number like this:

com.itextpdf.text.Rectangle pageSize = reader.getPageSize(i);
pageSize.normalize();
float height = pageSize.getHeight();
float width = pageSize.getWidth();

where you use

x = width - 200;
y = height - 85;

How does that make sense?

If you have an A4 page in portrait with (0,0) as the coordinate of the lower-left corner, the page number will be added at position x = 395; y = 757. However, (0,0) isn't always the coordinate of the lower-left corner, so the first A4 page with the origin at another position will already put the page number at another position. If the page size is different, the page number will move to other places.

It's as if you're totally unaware of previously answered questions such as How should I interpret the coordinates of a rectangle in PDF? and Where is the Origin (x,y) of a PDF page?

I know, I know, finding these specific answers on StackOverflow is hard, but I've spent many weeks organizing the best iText questions on StackOverflow on the official web site. See for instance: How should I interpret the coordinates of a rectangle in PDF? and Where is the origin (x,y) of a PDF page?

These Q&As are even available in a free ebook! If you take a moment to educate yourself by reading the documentation, you'll find the answer to the question How to position text relative to page? that was already answered on StackOverflow in 2013: How to position text relative to page using iText?

For instance, if you want to position your page number at the bottom and in the middle, you need to define your coordinates like this:

float x = pageSize.getBottom() + 10;
float y = pageSize.getLeft() + pageSize.getWidth() / 2;
ColumnText.showTextAligned(pagecontent, Element.ALIGN_CENTER,
    new Phrase(String.format("page %d of %d", i, n)), x, y, 0);

I hope this answer will inspire you to read the documentation. I've spent weeks of work on organizing that documentation and it's frustrating when I discover that people don't read it.

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • Thanks for your reply Bruno. i already gone through the Q&As PDF but it does not solve my problem. If take a look at attached PDF files second page PDF content is in the middle of the page, when i am trying to get the size of the page am getting total page sizes, using that i am not able to set the page Numbers. please review the attached PDFs once. – ramesh kadudhula Jul 09 '16 at 18:52
  • I need page numbers on top right corner of each page on merged documents – ramesh kadudhula Jul 09 '16 at 19:02
  • If you want them on the top right corner, you need to adapt the code: `x = pageSize.getRight() - 36; y = pageSize.getTop() - 36;` Also change `Element.ALIGN_CENTER` to `Element.RIGHT` and don't whine: just do it right. – Bruno Lowagie Jul 10 '16 at 03:53
  • I tried x=pageSize.getRight() - 36; y=pageSize.getTop()-36 and changed alignment to RIGHT but for first page, page numbers displaying properly but remaining pages its not working as expected. This issue due to data in PDF not showing on total page but when i am trying to get the page size it showing like below:Page Number - 1 Width 612.0 Height 792.0 Page Number - 2 Width 793.701 Height 651.968 Page Number - 3 Width 612.0 Height 792.0 – ramesh kadudhula Jul 10 '16 at 10:07
  • Hi Please find the attached PDF sample file, on page number 1 I am able to get page numbers but on 2 and 3 pages i don't have any page numbers, I am not sure how to add page numbers over their please help me out with this issue. https://drive.google.com/open?id=0Bxuvm1mtsDnHUUhmVzNYUzhXYkk – ramesh kadudhula Jul 11 '16 at 19:51