Reputation: 602
I want to know if an existing content of a PDF can be cloned using iText. Basically I have a PDF in the below format:
Without cloning the content
I want to clone the content that is on the left side in the above PDF and want the result as per the below format.
After cloning the content
I am wondering if this is possible using iText PdfStamper class or any other class of iText?
Updating the code with iText7
public void clonePageContent(String dest) throws IOException {
// Initialize PDF Document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfDocument sourcePdf = new PdfDocument(new PdfReader(SRC));
// Original page
PdfPage origPage = sourcePdf.getPage(1);
// Original page size
Rectangle orig = origPage.getPageSize();
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
// N-up page
PageSize nUpPageSize = PageSize.LETTER;
PdfPage page = pdf.addNewPage(nUpPageSize);
page.setRotation(90);
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());
pdf.close();
sourcePdf.close();
}
With the above code, I am not able to produce the output as expected. Can someone throw some light as to what should be tweaked to get the above expected output?
Upvotes: 1
Views: 901
Reputation: 602
After so many days of struggle, the below code helps in achieving the above output that I was expecting. Hope this might be helpful to someone, someday! P.S: I am newbie to iText7.
public void clonePageContent(String dest) throws IOException {
// Initialize PDF Document
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfDocument sourcePdf = new PdfDocument(new PdfReader(SRC));
// Original page
PdfPage origPage = sourcePdf.getPage(1);
// Original page size
Rectangle orig = origPage.getPageSize();
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
//PdfCanvas canvas = new PdfCanvas(pageCopy,sourcePdf);
// N-up page
PageSize nUpPageSize = PageSize.LETTER;
PdfPage page = pdf.addNewPage(nUpPageSize).setRotation(90);
PdfCanvas canvas = new PdfCanvas(page);
// Scale page
AffineTransform transformationMatrix = AffineTransform
.getScaleInstance(
page.getPageSize().getWidth() / orig.getWidth(), page.getPageSize().getHeight() / orig.getHeight()
);
canvas.concatMatrix(transformationMatrix);
System.out.println(page.getPageSize().getWidth());
System.out.println(orig.getWidth());
// Add pages to N-up page
canvas.addXObject(pageCopy, 0, 0);
canvas.addXObject(pageCopy, 0, 350f); //350f
//canvas.addXObject(pageCopy, orig.getRight(), orig.getWidth());
pdf.close();
sourcePdf.close();
}
Upvotes: 2