📅  最后修改于: 2020-10-16 02:59:38             🧑  作者: Mango
以下Java程序演示了如何使用iText库在PDF页面上进行N-up。它创建一个名为nUppingPDF.pdf的PDF文档,并将其保存在路径C:/ itextExamples /
将此代码保存在名为NUppingPDF.java的文件中。
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 NUppingPDF {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/nUppingPDF.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfReader
String src = "C:/itextExamples/pdfWithImage.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);
Rectangle orig = origPage.getPageSize();
PdfFormXObject pageCopy = origPage.copyAsFormXObject(destpdf);
// N-up page
PageSize nUpPageSize = PageSize.A4.rotate();
PdfPage page = destpdf.addNewPage(nUpPageSize);
PdfCanvas canvas = new PdfCanvas(page);
// Scale page
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
nUpPageSize.getWidth() / orig.getWidth() /
2f, nUpPageSize.getHeight() / orig.getHeight() / 2f);
canvas.concatMatrix(transformationMatrix);
// Add pages to N-up page
canvas.addXObject(pageCopy, 0, orig.getHeight());
canvas.addXObject(pageCopy, orig.getWidth(), orig.getHeight());
canvas.addXObject(pageCopy, 0, 0);
canvas.addXObject(pageCopy, orig.getWidth(), 0);
// closing the documents
destpdf.close();
srcPdf.close();
System.out.println("PDF created successfully..");
}
}
使用以下命令从命令提示符处编译并执行保存的Java文件-
javac NUppingPDF.java
java NUppingPDF
执行后,上述程序将创建一个显示以下消息的PDF文档。
PDF created successfully..
如果验证指定的路径,则可以找到创建的PDF文档,如下所示。