OpenPDF
OpenPDF copied to clipboard
RuntimeException when I put an Anchor in the footer
Describe the bug Document.close throws this exception when I put an anchor in the footer:
Exception in thread "main" java.lang.RuntimeException: Not all annotations could be added to the document (the document doesn't have enough pages).
at com.lowagie.text.pdf.PdfDocument.close(PdfDocument.java:874)
at com.lowagie.text.Document.close(Document.java:497)
at openpdf.FooterTest.main(FooterTest.java:42)
To Reproduce Here is a simple test case which causes the exception:
package openpdf;
import com.lowagie.text.Anchor;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class FooterTest {
public static void main(String[] args)
throws Exception {
Document document = new Document(PageSize.LETTER, 50, 50, 50, 50);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Tmp\\footerTest.pdf"));
Font footerFont = FontFactory.getFont(FontFactory.HELVETICA,9);
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
Paragraph paragraph = new Paragraph();
Anchor anchor = new Anchor("http://www.google.com",footerFont);
anchor.setReference("http://www.google.com");
paragraph.add(anchor);
PdfPCell cell = new PdfPCell(paragraph);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Right footer",footerFont));
table.addCell(cell);
Paragraph footerParagraph = new Paragraph();
footerParagraph.add(table);
HeaderFooter footer = new HeaderFooter(footerParagraph, false);
document.setFooter(footer);
document.open();
document.add(new Paragraph("Test"));
document.close();
writer.close();
}
}
Expected behavior
The document should not throw an exception. Because of the exception, my pdf file is empty.
I can catch and silently ignore the exception as a workaround, but this is still a bug.
System (please complete the following information):
- OS: Windows 11 Home
- Used Font: Helvetica
This is simple been caused by the code
if (annotationsImp.hasUnusedAnnotations()) {
throw new RuntimeException(MessageLocalization.getComposedMessage(
"not.all.annotations.could.be.added.to.the.document.the.document.doesn.t.have.enough.pages"));
}
in PdfDocument.close(). If I comment out this code, the document is generated "correctly", and the Anchor is also displayed in the Footer.
This is actually still the code of the first commit.
Any ideas, how this could be fixed?
Pull requests are welcome.