iText - add content to the bottom of an existing page - java

I want to add a piece of text to every page of a PDF file. This answer in SO works fine. But, the text is added to the top of the page. I would like to add my text to the bottom of each page. How do I do this?
Here is the relevant part of the code.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
document.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
document.add(new Paragraph("My Text here")); //As per the SO answer
}
pageOfCurrentReaderPDF = 0;
}
The code is part of a function which accepts a folder, reads the PDF files in it and merges them into one single file. So, I would like to add the text in the above loop itself, instead of iterating the file once again.

If you want to automatically add content to every page, you need a page event.
This is explained in chapter 5 of my book" iText in Action - Second Edition".
If you don't own a copy of the book, you can consult the examples here.
You can also find solutions by looking for the keyword Header / Footer.
The example you're referring to doesn't look correct at first sight. Sure, you can use "two passes", one to create the content, and another to add headers or footers, but the suggested solution is different from the recommended solution: http://itextpdf.com/examples/iia.php?id=118
You are copying the mistake in your question: why on earth would you import the document you've just created into a new document, thus throwing away all possible interactivity you've added to that document? It just doesn't make sense. It's unbelievable that this answer received that many up-votes. I'm the original developer of iText and I'm not at all happy with that answer!
In your case, there may be no need to create the document in memory first and to add the footer afterwards. Just take a look at http://itextpdf.com/examples/iia.php?id=104
You need to create a PdfPageEvent implementation (for instance using PdfPageEventHelper) and you need to implement the onEndPage() method.
Documented caveats:
Do not use onStartPage() to add content,
Do not add anything to the Document object passed to the page event,
Unless you specified a different page size, the lower-left corner has the coordinate x = 0; y = 0. You need to take that into account when adding the footer. The y-value for the footer is lower than the y-value for the header.
For more info: consult my book.

Have a look at chapter 6 of iText in Action, 2nd edition, especially at subsection 6.4.1: Concatenating and splitting PDF documents.
Listing 6.22, ConcatenateStamp.java, shows you how you should create a PDF from copies of pages (in your case: all pages) of multiple other PDFs; the sample additionally adds a new "Page X of Y" footer; this demonstrates how you can add content at given positions on the pages while merging the source files.

Perhaps this may be of assistance here... I suspect you want to do something like the following:
cb.addTemplate(page, 0, 0);
document.add(new Paragraph("My Text here"));
document.setFooter(new HeaderFooter("Footnote goes here"));
}
pageOfCurrentReaderPDF = 0;

Related

Identifying Hidden Elements in PDF from Chrome Page Breaks

I have a pdf document created by Google Chrome. When parsing the text via PDFBox (Java), I found that there was a hidden block of text straddled between the pages. Although the rendering mode was "FILL", I found that the element was off the page. Problem solved.
Now, I find that another similar element also appears off the page, but the coordinates to not tell this. It is within the visible margin of the second page that it straddles. It has y2 = 31.195312 and max height of 29.894833 (Font size = 36). Calculated y1 is about 1, still on the page.
The text positions obj shows some interesting internal properties, but they are not public vars. All I have is this TextPosition object (https://pdfbox.apache.org/docs/1.8.10/javadocs/org/apache/pdfbox/util/TextPosition.html) and the surrounding context.
I can reproduce the issue, but it requires my particular document. Could be attempted with page-break-inside tests, but I haven't found a simple test for it. I'm looking for some kind of margin, but so far all the boxes from within this.getCurrentPage() show just the plain page height, and no start position. Another possibility is that there is another way of looking for the coordinates than firstTextPos.getY() and firstTextPos.getHeight().
PDF in Mac Preview:
The text is selected between pages and is listed on the second page. In the case where it is listed on the first page, I am able to handle the issue as described above.
TextPosition object private vars:

Add Image in new page to existing PDF file

I am new to itext in java. I have an existing pdf of 2 pages. I need to add 2 new pages to it and then add an image to the 3rd page and then add four small rectangles and some text in the 4th page. On searching I got codes for adding new pages and codes for adding images to the existing pdf separately. Column text was used to add text to a new page, I searched for adding image to column text but I cannot find it. getUnderContent helped me to add image at the bottom of 2nd page. I want the image to be added in 3rd page. And the 4th page gets more complicated. I add the rectangle and text using PdfContentByte. This should be done by creating a new page. Any ideas?
Based on your comments, I assume that you are using PdfStamper and that you're able to add an image to an existing page. This is, for instance, done using getUnderContent() and its addImage() method. Now you need to add an extra page.
In PdfStamper, you can use the insertPage() method to achieve this:
stamper.insertPage(pageNum, rectangle);
In this line pageNum is an int value indication the page number where you want to insert the new page, and rectangle is the size of the page. For instance:
stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSize(1));
Once you have inserted the page, you can get the "over" or "under" content, and add an image to that PdfContentByte using the addImage() method. You might want to replace reader.getPageSize(1) with a Rectangle object that corresponds with the dimensions of the image.

Insert images in different pdf pages

I am trying to set a list of images in a PDF document using iText with Java, i could just insert some of them in the first page but i don't know how to jump to the next pages in order to put the rest of my pictures
for(int i = 0; i < 25; i++) {
Image myImg = Image.getInstance("/home/code/img"+i+".png");
imgPaper.setAbsolutePosition(50, 728-(y*58));
document.add(myImg);
y++;
}
The OP clarified his question in a comment
i have already another pages, i just want how to jump to them 
You seem to be creating a new document using a PdfWriter. That class is designed to create a pdf one page after the other. As soon as you start a new page, all former ones are written to file.
Thus, in this process you cannot jump to arbitrary pages. You have to add all information for a page while it is the current one.
If, after creating a multi page document, you need to manipulate the content of its pages, first close the document (finishing it), read it into a PdfReader, and apply a PdfStamper which allows you to manipulate arbitrary pages of an existing PDF.
Alternatively, especially if your images constitute something like a water mark or header/footer Logos, consider using page events in your pdf creation process with the PdfWriter.
try to add a new line to your document
document.add( Chunk.NEWLINE );
link for info:
How to insert blank lines in PDF?

How to add multiple headers and footers in pdf using itext

In my pdf I need to have more than one header and footer.In header I want title heading on left and some text on the center.
Likewise in footer I need to print my company name on the left side,page number on center and some info regarding the contents in my table on the right side.
I have seen so many posts but I didn't get the correct idea for creating this.Somebody please help me with some example code snippets.Thanks
Headers and footers should be added using 'page events'. If you need some examples, just look for the keyword header / footer on the official web site.
Just create a class that extends PdfPageEventHelper and implement the onEndPage() method. People who read the documentation do not make the common mistake to use the onStartPage() method, but maybe you overlooked this, so I'm adding this as an extra caveat.
Add an instance of your class to the PdfWriter object with the setPageEvent() method.
I don't know if I understand what you mean by "multiple" headers. If you have more than one page event implementation, you can add them all using the setPageEvent() method and they will all be executed. If you want to switch from one page event implementation to another, you need to use setPageEvent(null) first.
Maybe you want the header to be different for different pages, just use a member-variable in your page event implementation and change it along the way. In one of the book examples named MovieHistory2, the text for the header is stored in a String array named header.
The position of the header depends on the page number:
public void onEndPage(PdfWriter writer, Document document) {
Rectangle rect = writer.getBoxSize("art");
switch(writer.getPageNumber() % 2) {
case 0:
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_RIGHT, header[0],
rect.getRight(), rect.getTop(), 0);
break;
case 1:
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_LEFT, header[1],
rect.getLeft(), rect.getTop(), 0);
break;
}
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_CENTER, new Phrase(String.format("page %d", pagenumber)),
(rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
}
For even page numbers, the header is added to the right; for odd page numbers to the left. The footer is centered as you can see.
You also mention a header table. If you want to use a table, please take a look at the MovieCountries1 example.
You say: "I have seen so many posts but I didn't get the correct idea for creating this." You will get the correct idea by reading the documentation, more specifically chapter 5 of the book "iText in Action — Second Edition" from which the code snippets I'm referring to are taken.

How to insert content in the middle of a page in a PDF using IText

I have a requirement to insert Content into the middle of the page in a PDF.
The Content may be a Dynamic Table or an Image.
My Concept was to first split the PDF into 2 parts, then get the new Content that is to be added and append by replacing a place holder field.
the Splitting is called Tiling as per IText and here is an example for the same.
http://itextpdf.com/examples/iia.php?id=116
The Code above has 2 drawbacks:
1. It splits the page into 16 parts. but that is part of the example. Still i cant figure out a way to split the file into 2 parts only.
2. secondly the split page is converted to a complete page thus disturbing its proportions.
The Rearranging code is the another problem.
The remaining Content should be re-ordered in append mode. but till yet i have only found codes to add complete new pages rather than just the content.
I have found a code that appends the PDF content by replacing a placeholder:
float[] fieldPosition= pdfTemplate.getAcroFields().getFieldPositions("tableField");
PdfPTable table = buildTable();
PdfContentByte cb = stamper.getOverContent(1);
table.writeSelectedRows(0, -1, fieldPosition[1],fieldPosition[4],cb);
Please help me to solve this requirement.
PDF is a presentation format, not an edition format. In other words, it is not designed to allow content insertion, with the original content reflowing gracefully. As a consequence, no tool (at least, none that I know of, and surely not iText) will enable you to achieve what you were given as a requirement.
My advice :
refuse the assignment since it's not feasible, or
get your hands on the original document, insert the desired extra content, and then convert to PDF.

Categories