iText7: How to add text to the bottom of last page? - java

I am new to iText7, and I want to add a text after the content in the last page. I basically got a pdf file and create a new one, copying the pages from the first into the last. After, I get the last page and tried to append some text:
PdfPage lastPage = pdfOut.getLastPage();
PdfCanvas canvas = new PdfCanvas(lastPage.newContentStreamAfter(), lastPage.getResources(), pdfOut);
Paragraph paragraph = new Paragraph().add(new Text("Este documento foi assinado Hoje"));
Canvas c = new Canvas(canvas, pdfOut, rect);
c.add(paragraph);
c.close();
The text is not being appended after the content, sometimes appears in the first line of the last page or even it is not shown. Some ideas?
Thanks

What's definition of rect in the code? Despite this uncertainty below snippet should work
final Rectangle canvasSize = document.getPageEffectiveArea(new PageSize(lastPage.getPageSize()));
Canvas c = new Canvas(canvas, pdfOut, canvasSize);
Paragraph paragraph = new Paragraph()
.add(new Text("Este documento foi assinado Hoje"))
.setHeight(canvasSize.getHeight())
.setVerticalAlignment(VerticalAlignment.BOTTOM);

Related

Set position and rotation of text in pdf with itextpdf

I was trying to find out how to set the text position and rotation in a pdf with the "itextpdf" dependency. My current code looks like that:
//Create the pdf document
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
PdfContentByte pdfCB = new PdfContentByte(writer);
//Create the font which will be used
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
//Open the document
document.open();
//Get the image which was previously created (Not important for this)
Image iTextImage = Image.getInstance(pdfCB, image, 1);
//Set the position of the image (How do I do that with the text?)
iTextImage.setAbsolutePosition(0, 0);
//Create a text chunk which I want to set the position of and rotate
Chunk chunk = new Chunk("Hello World!", font);
//Add both the image and text to the pdf and save it
document.add(iTextImage);
document.add(chunk);
document.close();
//Notify the user that it was a success
System.out.println("Image added successfully and PDF file created!");
Now I was wondering how to set the position and rotation of the text. I want to create PDF's for a project which will later be printed. Now I don't want to add like a hundred whitespace's each time there is a blank spot in the page like the table of contents and then a footer at the bottom. I don't want to write the table of contents and then do \n 20 times to reach the bottom, so I can add my footer text, like page number, author, project ID, date, company logo, etc.
So how do I best position the text here? Also, I would like to rotate it, since some of the text has to be turned by 90 degrees for stuff like labels for tables and so on.
Any help would be appreciated, thank you.
PS: I already tried to set the absolute position, which just makes the text disappear.

Moving text on a page with iText7 retaining font, color, style, ... but changing size of the text

I want to move text with iText7. I have a source bounding box, that can be somewhere on the page and I have a target bounding box, that has a fixed position (incl. width and height). I'll stay on the same page. The source and target boxes can overlap. The source bounding box can also be larger than the target box. In this case I have to reduce the font size. The text should retain font, color and so on.
There is a cut and paste example on the iText website . But in the result pdf file you can select the text at the new and old position (tried it only with a normal pdf reader). I don't want the text to be selectable at the old position.
I thought, that maybe I could select the text and just place it at the new position and remove it from the old position. For the latter i would need pdfSweep, but this is ok. Adding the text at the new position should be no problem. Even if the text has different fonts, sizes and so on. There are plenty of examples on the iText website. The only way I know to select the text is like shown in this example. This gives me only the text. But to place it at the target position with the same font, color and so on, I need all those informations, too.
I know, that pdf is not meant for editing. This is often mention in answers on StackOverflow.
Is there a way to do this with iText7?
There is no high level API in iText allowing you to move page content, in particular not all content from some rectangle. One reason may be that in general this is no mere moving. PDFs often contain structures influencing larger areas, and such structures would not simply have to be moved but instead copied, and each copy restricted to its area.
It is indeed possible, though, to combine the cut and paste example the OP found with the pdfSweep module already considered by the OP to a solution which prevents the text from being selectable at the old position, e.g. like this:
public void moveCleanSection(PdfReader pdfReader, String targetFile, int page, Rectangle from, Rectangle to) throws IOException
{
LicenseKey.loadLicenseFile("itextkey-multiple-products.xml");
ByteArrayOutputStream interimMain = new ByteArrayOutputStream();
ByteArrayOutputStream interimPage = new ByteArrayOutputStream();
ByteArrayOutputStream interimSection = new ByteArrayOutputStream();
try ( PdfDocument pdfMainDocument = new PdfDocument(pdfReader);
PdfDocument pdfPageDocument = new PdfDocument(new PdfWriter(interimPage)) )
{
pdfMainDocument.setCloseReader(false);
pdfMainDocument.copyPagesTo(page, page, pdfPageDocument);
}
try ( PdfDocument pdfMainDocument = new PdfDocument(pdfReader, new PdfWriter(interimMain));
PdfDocument pdfSectionDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(interimPage.toByteArray())),
new PdfWriter(interimSection)) )
{
List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
cleanUpLocations.add(new PdfCleanUpLocation(page, from, null));
cleanUpLocations.add(new PdfCleanUpLocation(page, to, null));
PdfCleanUpTool cleaner = new PdfCleanUpTool(pdfMainDocument, cleanUpLocations);
cleaner.cleanUp();
cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
Rectangle mediaBox = pdfSectionDocument.getPage(1).getMediaBox();
if (from.getTop() < mediaBox.getTop())
cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(mediaBox.getLeft(), from.getTop(), mediaBox.getWidth(), mediaBox.getTop() - from.getTop()), null));
if (from.getBottom() > mediaBox.getBottom())
cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(mediaBox.getLeft(), mediaBox.getBottom(), mediaBox.getWidth(), from.getBottom() - mediaBox.getBottom()), null));
if (from.getLeft() > mediaBox.getLeft())
cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(mediaBox.getLeft(), mediaBox.getBottom(), from.getLeft() - mediaBox.getLeft(), mediaBox.getHeight()), null));
if (from.getRight() < mediaBox.getRight())
cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(from.getRight(), mediaBox.getBottom(), mediaBox.getRight() - from.getRight(), mediaBox.getHeight()), null));
cleaner = new PdfCleanUpTool(pdfSectionDocument, cleanUpLocations);
cleaner.cleanUp();
}
try ( PdfDocument pdfSectionDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(interimSection.toByteArray())));
PdfDocument pdfMainDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(interimMain.toByteArray())), new PdfWriter(targetFile)) )
{
float scale = Math.min(to.getHeight() / from.getHeight(), to.getWidth() / from.getWidth());
pdfSectionDocument.getPage(1).setMediaBox(from);
PdfFormXObject pageXObject = pdfSectionDocument.getFirstPage().copyAsFormXObject(pdfMainDocument);
PdfPage pdfPage = pdfMainDocument.getPage(page);
PdfCanvas pdfCanvas = new PdfCanvas(pdfPage);
pdfCanvas.addXObject(pageXObject, scale, 0, 0, scale, (to.getLeft() - from.getLeft() * scale), (to.getBottom() - from.getBottom() * scale));
}
}
(From MoveSectionCleanly.java)
Beware: Due to the nature of pdfSweep, text being on the border of the source area is removed both from the source and the copy of it.

How to prevent first chapter on page two when table in header of pdf generated with iText?

When having a PdfPTable in the header of the document, the first Chapter added gets added too page two, leaving the first page blank. If having just text in the header all works fine (see the out commented line in code sample). Am I doing something wrong or are there a workaround for this problem? I'm using iText-2.1.7.
So to be clear: The code below generates a pdf with one empty page as the first page and if going with the out commented row instead there is no empty page first.
Another thing is that if having a table in the header the generated header gets no height making the text of the document placed over the header table. That one I can work around. But it could perhaps give some help in understanding what's happening...
Document vDocument = new Document();
PdfWriter.getInstance(vDocument, new FileOutputStream("C:/Test.pdf"));
PdfPTable vTable = new PdfPTable(1);
vTable.addCell(new PdfPCell (new Phrase("Header text")));
Phrase vPhr = new Phrase();
vPhr.add(vTable);
HeaderFooter vHeaderFooter = new HeaderFooter(vPhr, false);
// HeaderFooter vHeaderFooter = new HeaderFooter(new Phrase("Header text"), false);
vDocument.setHeader(vHeaderFooter);
vDocument.open();
vDocument.add(new Chapter("New Chapter", 0));
for (int i=0; i<1000; i++) {
vDocument.add(new Paragraph(" TEXT " + i));
}
vDocument.close();

Adding more text to a cell in table in itext

I am trying to add some text with a bar code in a table cell using itext as per the following code but it does not show in the pdf file. i tried adding chunks and paragraph. Any help on this would be appreciated.
Barcode128 barcode = new Barcode128();
//barcode.setCodeType(Barcode.EAN8);
barcode.setCode(code);
PdfPCell cell = new PdfPCell(barcode.createImageWithBarcode(writer.getDirectContent(), BaseColor.BLACK, BaseColor.GRAY), true);
Paragraph paragraph = new Paragraph("Hello World");
cell.addElement(paragraph);
cell.setPadding(10);
You are probably confused by text vs. composite mode.
When using the PdfPCell(Image) constructor, you create a cell in text mode. Any subsequent call to addElement(Element) will then switch the cell to composite mode, removing all content previously entered in the constructor.
You'll have to change your code that way:
PdfPCell cell = new PdfPCell();
Barcode128 barcode = new Barcode128();
barcode.setCode(code);
Image barcodeImage = barcode.createImageWithBarcode(writer.getDirectContent(), BaseColor.BLACK, BaseColor.GRAY);
cell.addElement(barcodeImage);
Paragraph paragraph = new Paragraph("Hello World");
cell.addElement(paragraph);

Add anchor to pdf using itext java

I am trying to add anchor(named destinations) to pdf using itext java api. But it's not working.When I click the text , nothing happens.This is what I am doing .
Anchor anchor =
new Anchor("Jump down to next paragraph");
anchor.setReference("#linkTarget");
Paragraph paragraph = new Paragraph();
paragraph.add(anchor);
document.add(paragraph);
Anchor anchorTarget =
new Anchor("This is the target of the link above");
anchor.setName("linkTarget");
Paragraph targetParagraph = new Paragraph();
targetParagraph.setSpacingBefore(50);
targetParagraph.add(anchorTarget);
document.add(targetParagraph);
What am I doing wrong?. Any help
It worked for me. setLocalGoto() and setLocalDestination() will do the magic.
Chunk chunk = new Chunk("Contact information");
chunk.setLocalGoto("contact");
document.add(new Paragraph(chunk));
document.newPage();
chunk chunk1 = new Chunk("Contact information");
chunk1.setLocalDestination("contact");
Chapter chapter = new Chapter(new Paragraph(chunk1),1);
chapter.setNumberDepth(0);
document.add(chapter);
You are not passing anchorTarget in setName(), that's why it's not leading you towards #linktarget
Anchor anchorTarget = new Anchor("This is the target of the link above");
anchorTarget.setName("linkTarget");
Paragraph anchorTargetLinkParagraph = new Paragraph();
anchorTargetLinkParagraph.setAlignment(Element.ALIGN_CENTER);
anchorTargetLinkParagraph.add(anchorTarget);
document.add(anchorTargetLinkParagraph);

Categories