I have a template PDF file that has a a PDF form field embedded in. I am using PdfStamper to fill out these fields. In addition, I would like to be able to change the margins for generated PDF. is there any way I can modify the page margins on the stamped PDF?
Asked
Active
Viewed 5.2k times
21
-
Do you need to keep the **same** existing page size as your PDF template, or is it acceptable to create a new document with a slightly larger/smaller page size? – kuujinbo Feb 19 '12 at 08:49
3 Answers
24
You can do it all in one line.
Document doc = new Document(PageSize.LETTER, 0f, 0f, 0f, 0f );

Baxter
- 5,633
- 24
- 69
- 105
16
Only way I know of is like this.
iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(pageWidth, pageHeight);
Document doc = new Document(rec);
doc.SetMargins(0f, 0f, 0f, 0f);
However, this will limit margins too

Lukas
- 2,885
- 2
- 29
- 31
-
3Thanks so much! That was an annoying problem. Also may want to note that the pageWidth and pageHeight are in pixels. I used 612 x 792 (for 72dpi) to get a regular page size. – James Jan 07 '13 at 22:57
0
setMaring Impelemented as
public override bool SetMargins(float marginLeft, float marginRight, float marginTop, float marginBottom)
{
if ((this.writer != null) && this.writer.IsPaused())
{
return false;
}
this.nextMarginLeft = marginLeft;
this.nextMarginRight = marginRight;
this.nextMarginTop = marginTop;
this.nextMarginBottom = marginBottom;
return true;
}
therefor margin applied for next page. for solve this problem after open pdfDocument call newPage() this solution work for empty pdfDocument .
using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
{
using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f))
{
try
{
//open the stream
pdfDoc.Open();
pdfDoc.setMargin(20f, 20f, 20f, 20f);
pdfDoc.NewPage();
pdfDoc.Close();
}
catch (Exception ex)
{
//handle exception
}
finally
{
}
}
}

user934335
- 47
- 1
-
1Not sure why this answer has been downvoted. It is useful to know that SetMargins will only work from the NEXT page created, but that calling NewPage() on an empty document will not result in an empty page, but will ensure that the margins take effect. – JHW May 03 '22 at 16:31