iTextSharp 在开头插入一个页面
iTextSharp insert a page at the beginning
使用 iTextSharp,当 PdfWriter 已经写入页面时,如何在页面的开头插入新页面?假设索引页应该是文档的第一页,但是在编写整个文档之前您不会知道它的内容。具体来说,每个section/chapter写在哪一页
您在创建文档时无法返回到第一页,但有多种方法可以解决您的问题。
如果您不希望有很多页面,您可以考虑在 iText in Action - Second Edition, more specifically in the MovieHistory1.java 示例的第 5 章中解释的解决方案。
在这个例子中,我们在关闭文档之前重新排序页面:
// step 1
Document document = new Document();
// step 2
PdfWriter writer
= PdfWriter.getInstance(document, new FileOutputStream(RESULT));
// IMPORTANT: set linear page mode!
writer.setLinearPageMode();
// step 3
document.open();
// step 4
// Add all your content
// Create a new order for the pages
int total = writer.reorderPages(null);
// change the order
int[] order = new int[total];
for (int i = 0; i < total; i++) {
order[i] = i + toc;
if (order[i] > total)
order[i] -= total;
}
// apply the new order
writer.reorderPages(order);
// step 5
document.close();
为什么我只推荐页数有限的文档使用此功能?为了使这个功能起作用,我们需要创建一个线性页面树:
writer.setLinearPageMode();
线性页面树并不是真正的树(它是一棵没有任何分支的树)并且在 PDF 中不是最优的。
最好重新排序页面。 The Best iText Questions on Whosebug(免费电子书)中捆绑的两个问题对此进行了解释。
问题是:
- Create Index File(TOC) for merged pdf using itext library in java
- PDF Page re-ordering using itext
我知道在 SO 上有冗余信息并不理想,但这是您需要的代码:
PdfReader reader = new PdfReader(baos.toByteArray());
int n = reader.getNumberOfPages();
reader.selectPages(String.format("%d, 1-%d", n, n-1));
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(filename));
stamper.close();
使用 iTextSharp,当 PdfWriter 已经写入页面时,如何在页面的开头插入新页面?假设索引页应该是文档的第一页,但是在编写整个文档之前您不会知道它的内容。具体来说,每个section/chapter写在哪一页
您在创建文档时无法返回到第一页,但有多种方法可以解决您的问题。
如果您不希望有很多页面,您可以考虑在 iText in Action - Second Edition, more specifically in the MovieHistory1.java 示例的第 5 章中解释的解决方案。
在这个例子中,我们在关闭文档之前重新排序页面:
// step 1
Document document = new Document();
// step 2
PdfWriter writer
= PdfWriter.getInstance(document, new FileOutputStream(RESULT));
// IMPORTANT: set linear page mode!
writer.setLinearPageMode();
// step 3
document.open();
// step 4
// Add all your content
// Create a new order for the pages
int total = writer.reorderPages(null);
// change the order
int[] order = new int[total];
for (int i = 0; i < total; i++) {
order[i] = i + toc;
if (order[i] > total)
order[i] -= total;
}
// apply the new order
writer.reorderPages(order);
// step 5
document.close();
为什么我只推荐页数有限的文档使用此功能?为了使这个功能起作用,我们需要创建一个线性页面树:
writer.setLinearPageMode();
线性页面树并不是真正的树(它是一棵没有任何分支的树)并且在 PDF 中不是最优的。
最好重新排序页面。 The Best iText Questions on Whosebug(免费电子书)中捆绑的两个问题对此进行了解释。
问题是:
- Create Index File(TOC) for merged pdf using itext library in java
- PDF Page re-ordering using itext
我知道在 SO 上有冗余信息并不理想,但这是您需要的代码:
PdfReader reader = new PdfReader(baos.toByteArray());
int n = reader.getNumberOfPages();
reader.selectPages(String.format("%d, 1-%d", n, n-1));
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(filename));
stamper.close();