使用iText平铺,并添加边距 [英] Tiling with iText, and adding margins
问题描述
我正在关注Tiling Hero示例( http://itextpdf.com/examples/iia .php?id = 116 )但我希望能够为每个页面添加页边距。
Im following the Tiling Hero example (http://itextpdf.com/examples/iia.php?id=116) but I'd like to be able to add margins to each page.
推荐答案
请查看 TileClipped 示例。它基于 TilingHero 示例,但它有一个转折点:
Please take a look at the TileClipped example. It is based on the TilingHero example, but it has a twist:
public void manipulatePdf(String src, String dest)
throws IOException, DocumentException {
float margin = 30;
// Creating a reader
PdfReader reader = new PdfReader(src);
Rectangle rect = reader.getPageSizeWithRotation(1);
Rectangle pagesize = new Rectangle(rect.getWidth() + margin * 2, rect.getHeight() + margin * 2);
// step 1
Document document = new Document(pagesize);
// step 2
PdfWriter writer
= PdfWriter.getInstance(document, new FileOutputStream(dest));
// step 3
document.open();
// step 4
PdfContentByte content = writer.getDirectContent();
PdfImportedPage page = writer.getImportedPage(reader, 1);
// adding the same page 16 times with a different offset
float x, y;
for (int i = 0; i < 16; i++) {
x = -rect.getWidth() * (i % 4) + margin;
y = rect.getHeight() * (i / 4 - 3) + margin;
content.rectangle(margin, margin, rect.getWidth(), rect.getHeight());
content.clip();
content.newPath();
content.addTemplate(page, 4, 0, 0, 4, x, y);
document.newPage();
}
// step 4
document.close();
reader.close();
}
您是否看到我们如何区分 rect
和 pagesize
?我们将 rect
定义为原始页面的大小,我们将 pagesize
定义为稍大的大小(取决于 margin
的值。
Do you see how we make a distinction between rect
and pagesize
? We define rect
as the size of the original pages and we define pagesize
as a size that is slightly bigger (depending on the value of margin
).
我们在定义偏移时使用rect x
和 y
,但我们添加 margin
来稍微改变该偏移量。我们更改了偏移量,因为我们剪切了 pagesize
。通过定义剪切路径来完成剪辑:
We use rect when we define the offset x
and y
, but we add margin
to slightly change that offset. We change the offset because we clip the pagesize
. Clipping is done by defining a clipping path:
content.rectangle(margin, margin, rect.getWidth(), rect.getHeight());
content.clip();
content.newPath();
这三行之后添加的所有内容都将被我们在 rectangle()
方法。如果您还想添加其他内容,可能需要添加额外的 saveState()
/ restoreState()
方法如果需要在剪切路径之外添加内容。
Everything added after these three lines will be clipped by the rectangle we define in the rectangle()
method. You may want to add extra saveState()
/restoreState()
methods if you also want to add other content, especially if that content needs to be added outside the clipping path.
这篇关于使用iText平铺,并添加边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!