如何使用Java平铺PDF文档中的页面内容?
注:iText开发环境设置,下载iText7 jar(社区版:http://github.com/itext/itext7/releases/tag/7.0.4 ) ,创建一个工程:java_itext,并将下载的itext7 jar包和slf4j( http://www.slf4j.org/download.html )工具包添加到构建路径中。项目结构如下图所示 -
以下是使用Java平铺PDF文档中的页面内容的程序。
package com.yiibai;
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
public class TilingPDFPages {
public static void main(String args[]) throws Exception {
//Creating a PdfWriter object
String dest = "tilingPdfPages.pdf";
PdfWriter writer = new PdfWriter(dest);
//Creating a PdfReader
String src = "imagsWithPDF.pdf";
PdfReader reader = new PdfReader(src);
//Creating a PdfDocument objects
PdfDocument destpdf = new PdfDocument(writer);
PdfDocument srcPdf = new PdfDocument(reader);
//Opening a page from the existing PDF
PdfPage origPage = srcPdf.getPage(1);
//Getting the page size
Rectangle orig = origPage.getPageSizeWithRotation();
//Getting the size of the page
PdfFormXObject pageCopy = origPage.copyAsFormXObject(destpdf);
//Tile size
Rectangle tileSize = PageSize.A4.rotate();
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
tileSize.getWidth() / orig.getWidth() * 2f,
tileSize.getHeight() / orig.getHeight() * 2f);
//The first tile
PdfPage page = destpdf.addNewPage(PageSize.A4.rotate());
PdfCanvas canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, -orig.getHeight() / 2f);
//The second tile
page = destpdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, -orig.getHeight() / 2f);
//The third tile
page = destpdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, 0);
//The fourth tile
page = destpdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, 0);
destpdf.close();
srcPdf.close();
System.out.println("PDF created successfully..");
}
}
执行上面示例代码,得到以下结果 -
PDF created successfully..
输出文件内容如下所示 -