triForce420
triForce420

Reputation: 729

itextpdf different margin on specific page

Good day everyone!

I have some questions regarding document:

  1. Does itextpdf have the option to have a different margin on a specific page? I have tried to use

document.setMargin

then

document.newPage

but it seems that every page get the same margin.

  1. Is there any way to prevent header and element from overlapping?

Thanks!

EDIT

Here is the method that adds the document content:

    @Override
    void addDocumentContent(Document doc, PdfWriter writer, AbstractDiplomaDataModel diplomaData) throws DiplomaPdfFileProducerException {
        try {
            doc.setMargins(DefaultPdfDocumentSettings.LEFT_MARGIN, DefaultPdfDocumentSettings.RIGHT_MARGIN, 0f, 0f);
            doc.newPage();          
            doc.add(new DiplomaPdfDataGenerator(diplomaData).generateFirstPagePdf());
            doc.setMargins(DefaultPdfDocumentSettings.LEFT_MARGIN, DefaultPdfDocumentSettings.RIGHT_MARGIN, DefaultPdfDocumentSettings.TOP_MARGIN,DefaultPdfDocumentSettings.BOTTOM_MARGIN);
            doc.newPage();          
            doc.add(new DiplomaPdfDataGenerator(diplomaData).generateOtherPagesPdf());
        } catch (Exception e) {
            throw new DiplomaPdfFileProducerException(e.getMessage());
        }
    }

and this is the result:

title page, margin is changed

overlap

Upvotes: 2

Views: 9049

Answers (1)

mkl
mkl

Reputation: 96064

I just tried what you described:

StringBuilder builder = new StringBuilder("test");
for (int i = 0; i < 100; i++)
    builder.append(" test");
String test = builder.toString();

try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "ChangingMargins.pdf")))
{
    Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
    PdfWriter.getInstance(pdfDocument, pdfStream);
    pdfDocument.open();

    for (int m = 0; m < pdfDocument.getPageSize().getWidth() / 2; m += 100)
    {
        pdfDocument.setMargins(m, m, 100, 100);
        pdfDocument.newPage();
        pdfDocument.add(new Paragraph(test));
    }

    pdfDocument.close();
}

(ChangeMargins.java method testChangingMargins)

The result:

Screenshot

Thus, considering your item 1: Yes, iText can have a different margin on a specific page.

The OP wondered in a comment:

how about top and bottom margin? :/

For this I changed the loop above to:

    for (int m = 0; m < pdfDocument.getPageSize().getWidth() / 2 && m < pdfDocument.getPageSize().getHeight() / 2; m += 100)
    {
        pdfDocument.setMargins(m, m, m, m);
        pdfDocument.newPage();
        pdfDocument.add(new Paragraph(test));
    }

And the result:

Screenshot

Thus, different top and bottom margins work, too.


Considering your issue 2 whether there any way to prevent header and element from overlapping: Usually they do not overlap.

Upvotes: 6

Related Questions