Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the setMargins method in iText works?

Does the setMargins method in iText work in a conventional manner?

I have tried the following:

System.out.println(f.exists());
Document document = new Document(PageSize.A4,36,36,36,36);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f.getAbsolutePath()+"0.pdf"));
document.open();

//reader
PdfReader reader = new PdfReader(new FileInputStream(f));
PdfContentByte cb = writer.getDirectContent();

for(int i = 1 ; i < reader.getNumberOfPages()+1 ; i++)
{
  System.out.println(f.getName()+" "+i);
  PdfImportedPage page = writer.getImportedPage(reader, i); 
  document.newPage();
  cb.addTemplate(page,0,0);
}


// Add your new data / text here
// for example...
//document.add(new Paragraph("my timestamp")); 
document.close();

However, I get the same output as my input. I'm wondering whether there is a special trick to getting the setMargins method to work normally.

like image 670
jayunit100 Avatar asked Dec 10 '11 00:12

jayunit100


3 Answers

setMargins method works only before:

document.open();
like image 56
Greg Avatar answered Nov 06 '22 18:11

Greg


Margins can be changed after open(), however, the changes only take effect after newPage().

Adding a PdfImportedPage as an "image" honours the margins of the document.

Example:

PdfImportedPage page = writer.getImportedPage(reader, i); 
document.add(Image.getInstance(page));
like image 39
Nazar Annagurban Avatar answered Nov 06 '22 18:11

Nazar Annagurban


You can change left and top margins in the new pdf document by adding offset by calling

cb.addTemplate(page, leftMarginOffset,topMarginOffset);

Positive numbers will reduce margins and negative numbers increase them.

like image 1
user3757654 Avatar answered Nov 06 '22 19:11

user3757654