The setMargins() command doesn't seem to be working when I want to change the margins for a new page.
The version of OpenPDF that I'm using is the 1.3.10
Here the minimum working example to reproduce the error:
package my.project;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
public class ReportBuilder {
public void addCover(Document document) {
URL coverURL = this.getClass().getResource("/images/report/Cover.png");
this.addCover(document, coverURL);
}
public void addCover(Document document, URL coverURL) {
try {
Image cover = Image.getInstance(coverURL);
cover.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight());
document.add(cover);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try (Document document = new Document(PageSize.A4, 0, 0, 0, 0)) {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Document.pdf"));
document.open();
ReportBuilder reportBuilder = new ReportBuilder();
reportBuilder.addCover(document);
document.setMargins(40, 40, 40, 40);
document.newPage();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++) {
builder.append("Hey there " + i);
}
document.add(new Paragraph(builder.toString()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
and this is the output I'm getting, with the maring not corresponding to the ones that I did set:

Thanks for reporting this. Pull requests welcome!
The setMargins() command doesn't seem to be working when I want to change the margins for a new page.
Isn't this a wrong practice to start with ie. setting margin after document is opened.
I have slightly updated your piece of code with
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("testSetMargin.pdf"));
document.open();
document.setMargins(40, 40, 40, 40);
document.newPage();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++) {
builder.append("Hey there ").append(i);
}
document.add(new Paragraph(builder.toString()));
document.newPage();
builder.setLength(0);
for (int i = 0; i < 100; i++) {
builder.append("Hey there ").append(i);
}
document.add(new Paragraph(builder.toString()));
document.close();
and got the expected response

See, second page has desired margin. I am not sure if this qualifies as a bug.