您可能想查看PageCombinationSample.java,根据其 JavaDoc,它几乎可以满足您的需求:
此示例演示如何使用表单 XObjects [PDF:1.6:4.9] 将多个页面组合成单个更大的页面(例如,将两个 A4 模块组合成一个 A3 模块)。
表单 XObject 是一种将多个页面上的内容多次表示为模板的便捷方式。
中心代码:
// 1. Opening the source PDF file...
File sourceFile = new File(filePath);
// 2. Instantiate the target PDF file!
File file = new File();
// 3. Source page combination into target file.
Document document = file.getDocument();
Pages pages = document.getPages();
int pageIndex = -1;
PrimitiveComposer composer = null;
Dimension2D targetPageSize = PageFormat.getSize(SizeEnum.A4);
for(Page sourcePage : sourceFile.getDocument().getPages())
{
pageIndex++;
int pageMod = pageIndex % 2;
if(pageMod == 0)
{
if(composer != null)
{composer.flush();}
// Add a page to the target document!
Page page = new Page(
document,
PageFormat.getSize(SizeEnum.A3, OrientationEnum.Landscape)
); // Instantiates the page inside the document context.
pages.add(page); // Puts the page in the pages collection.
// Create a composer for the target content stream!
composer = new PrimitiveComposer(page);
}
// Add the form to the target page!
composer.showXObject(
sourcePage.toXObject(document), // Converts the source page into a form inside the target document.
new Point2D.Double(targetPageSize.getWidth() * pageMod, 0),
targetPageSize,
XAlignmentEnum.Left,
YAlignmentEnum.Top,
0
);
}
composer.flush();
// 4. Serialize the PDF file!
serialize(file, "Page combination", "combining multiple pages into single bigger ones", "page combination");
// 5. Closing the PDF file...
sourceFile.close();