由于iText许可证的更改,我才刚开始使用OpenPDF。
我要实现的目的是创建一个类似Book的PDF,该文件的初始封面是ToC和章节。
我现在面临的问题是打开文档后setMargins()
方法不起作用。
我确实也读到它是基于iText的分支,所以也许该错误已经存在于 iText ,也许是v4中。
在MWE重现该错误:
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();
}
}
}
这是在Maven中使用OpenPDF的依赖项:
<dependency>
<groupId>com.github.librepdf</groupId>
<artifactId>openpdf</artifactId>
<version>1.3.10</version>
</dependency>