pdfbox generate multi page - java

When I generate second page, I get a blank page. I have two functions. One generates a table with text, and another generates a PDF. When end place in first page, I add another page and I want write in new page. When I open generated PDF file, the second page is blank:
//global variables
PDPage nowa=null;
PDPageContentStream contentStream1 = null;
//function to generate table
private void print_sumActionPerformed(java.awt.event.ActionEvent evt){
try {
PDDocument doc = null;
PDPage page = null;
int max_row=55;
int suma=0;
int pozycja=0;
final int starty=760;
final int startx=30;
try{
doc = new PDDocument();
page = new PDPage(PDPage.PAGE_SIZE_A4);
doc.addPage(page);
PDFont font = PDType1Font.HELVETICA;
PDPageContentStream content = new PDPageContentStream(doc, page,true,true);
//some code to generate table
drawTable(page, content, starty, startx, content1,doc);
content.close();
doc.save("path");
doc.close();
Thread.sleep(500);
} catch (Exception e){
System.out.println(e);
}
} catch (IOException ex) {
Logger.getLogger(Okno.class.getName()).log(Level.SEVERE, null, ex);
} catch (PrinterException ex) {
Logger.getLogger(Okno.class.getName()).log(Level.SEVERE, null, ex);
}
}
function to generate table in pdf
private void drawTable(PDPage page, PDPageContentStream contentStream,float y, float margin, String[][] content,PDDocument doc) throws IOException, InterruptedException {
final int rows = content.length;
final int cols = content[0].length;
final float rowHeight = 13f;
final float marginCell=5;
final float startx=30;
final int tableWidth3=200;
final int tableWidth5=250;
boolean new_kol;
if (margin<230){
new_kol=false;
}else {
new_kol=true;
}
float textx;
final float odst=20;
final float starty = y;
float texty=starty-rowHeight+3;
//width table
int tableWidth;
if(cols==5)tableWidth=tableWidth5;
else tableWidth=tableWidth3;
//start print table in pdf
if(!new_kol){
contentStream.drawLine(startx,starty,tableWidth+startx+marginCell,starty);
textx=startx+marginCell;
}else {
contentStream.drawLine(startx+tableWidth5+odst, starty, 2*tableWidth5+(startx)+odst+marginCell,starty);
textx=startx+marginCell+tableWidth+odst;
}
for(int i = 0; i < content.length; i++){
for(int j = 0 ; j < content[i].length; j++){
//linia pionowa
contentStream.drawLine(textx-marginCell,texty-3,textx-marginCell,texty-3+rowHeight);
String text=content[i][j];
if(text.contains("AB")){
contentStream.setFont(PDType1Font.HELVETICA_BOLD,10);
}else contentStream.setFont(PDType1Font.HELVETICA,8);
contentStream.beginText();
contentStream.moveTextPositionByAmount(textx,texty);
contentStream.drawString(text);
contentStream.endText();
switch(j){
case 0: textx+=30;
break;
case 1:
if (cols==5) textx += 120;
else textx+=150;
break;
case 2: textx+=15;
if(cols==3 ) contentStream.drawLine(textx+marginCell,texty-3,textx+marginCell,texty-3+rowHeight);
break;
case 3: textx+=40;
break;
case 4: textx+=40;
contentStream.drawLine(textx+marginCell,texty-3,textx+marginCell,texty-3+rowHeight);
break;
}
}
if(new_kol){
textx=tableWidth+startx+odst+marginCell;
contentStream.drawLine(textx-marginCell,texty-3,textx+tableWidth,texty-3);
}
else {
textx=startx+marginCell;
contentStream.drawLine(textx-marginCell,texty-3,textx+tableWidth,texty-3);
}
if((texty-=rowHeight)<50){
if(!new_kol){
new_kol=true;
contentStream.drawLine(startx,texty+10,startx+tableWidth+marginCell,texty+10);
texty=760-10;
textx=tableWidth+startx+odst+marginCell;
contentStream.drawLine(textx-marginCell,texty+10,textx+tableWidth,texty+10);
}else{
new_kol=false;
contentStream.drawLine(startx+tableWidth5+odst,texty+10,startx+2*tableWidth,texty+10);
texty=760-10;
textx=startx+marginCell;
//here i add new page when end page height
//i get blank page
contentStream.close();
page=null;
contentStream=null;
nowa=new PDPage(PDPage.PAGE_SIZE_A4);
page=null;
page=nowa;
doc.addPage(nowa);
PDFont font = PDType1Font.HELVETICA;
contentStream1 = new PDPageContentStream(doc, nowa,false,true);
contentStream=contentStream1;
contentStream1=null;
contentStream.drawLine(textx,texty+10,textx+tableWidth,texty+10);
}
}
}
}

It could probably be your constructor. I think if you use :
PDPageContentStream content = new PDPageContentStream(doc, page,true,true, false);
it should work as expected. The final parameter corresponds to the resetContext value in the constructor and decides whether the current graphic context should be reset or not (Source) .

Related

PDFBox 2.0.9 - creating TOC with multiple pages

I'm working on PDF Toc. It generates the first page but when I have more elements I did logic to create a new page for TOC. I'm using PDF Box and that PDPageContentStream.
I had to create a function to calculate how many pages I need. Then I'm creating the exact amount of pages in the list and add them to the PDF document before I start PDPageContentStream. That stream is in a loop and it's only generating the first page. Other pages come blank. I don't know what exactly is wrong. Here is the code:
PDDocument pdf = new PDDocument();
int numberOfTocPages = calculateTocPages(50, tocStyle, _height, currentYPosition, leading);
List<PDPage> tocPages = new ArrayList<PDPage>();
for (int i = 0; i < numberOfTocPages; i++) {
PDPage toc = new PDPage(new PDRectangle(_width, _height));
tocPages.add(toc);
}
float numberingXPosition = _width - (contentMarginLeft + contentMarginRight) - 100;
int j = 0;
PDDocument temp = new PDDocument();
for (int i = 0; i < numberOfTocPages; i++) {
PDPage toc = tocPages.get(i);
pdf.addPage(toc);
try {
PDPageContentStream contentStream = new PDPageContentStream(pdf, toc, PDPageContentStream.AppendMode.APPEND, true, false);
contentStream.beginText();
if (i == 0) {
contentStream.setFont(font, fontSize);
contentStream.setNonStrokingColor(tocStyle.getHeaderFontColor());
contentStream.newLineAtOffset(headerMarginLeft, currentYPosition);
contentStream.showText(StylingEnums.TABLE_OF_CONTENTS);
}
fontSize = tocStyle.getContentFontSize();
leading = 1.5f * fontSize;
contentStream.setFont(PDType1Font.HELVETICA, fontSize);
contentStream.setNonStrokingColor(tocStyle.getContentFontColor());
contentStream.newLineAtOffset(contentMarginLeft, -leading);
currentYPosition -= leading;
contentStream.setLeading(leading);
// List<TocContentData> tocItems = _tocData.getTocItems();
while (j < 50) {
if (currentYPosition >= 2 * tocStyle.getContentMarginBottom()) {
// TocContentData item = tocItems.get(i);
contentStream.showText("Item " + j);
contentStream.newLineAtOffset(numberingXPosition, 0);
int pageNumber = j;
contentStream.showText(Integer.toString(pageNumber + 1));
contentStream.newLineAtOffset(-numberingXPosition, 0);
contentStream.newLine();
currentYPosition -= leading;
j++;
} else {
System.out.println("New page!!!");
currentYPosition = initialPosition;
break;
}
}
contentStream.endText();
contentStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream out;
try {
out = new FileOutputStream(fileName + ".pdf");
pdf.save(out);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Page 2 sets the Y offset with this code because currentYPosition is not used when i > 0
contentStream.newLineAtOffset(contentMarginLeft, -leading);
so your first Y offset value is negative.

PDFBOX 2.0+ java flatten annotations freetext created by foxit

I ran into a very tough issue. We have forms that were supposed to be filled out, but some people used annotation freeform text comments in foxit instead of filling the form fields, so the annotations never flatten. When our render software generates the final document annotations are not included.
The solution I tried is to basically go through the document, get the annotation text content and write it to the pdf so it is on the final document then remove the actual annotation, but I run into an issue where I don't know the font the annotation is using, line space, etc so cannot find out how to get it from a pdfbox to recreate exacactly as the annotation looks on the unflattened form.
Basically I want to flatten annotatations that are freeform created in foxit (The typewriter comment feature)
Here is the code. It is working, but again I am struggling with figuring out how to get the annotations to write to my final pdf document. Again flatten on the acroform is not working because these are not acroform fields! The live code filters out anything that is not a freetext type annotation, but below code should show my issue.
public static void main(String [] args)
{
String startDoc = "C:/test2/test.pdf";
String finalFlat = "C:/test2/test_FLAT.pdf";
try {
// for testing
try {
//BasicConfigurator.configure();
File myFile = new File(startDoc);
PDDocument pdDoc = PDDocument.load( myFile );
PDDocumentCatalog pdCatalog = pdDoc.getDocumentCatalog();
PDAcroForm pdAcroForm = pdCatalog.getAcroForm();
// set the NeedApperances flag
pdAcroForm.setNeedAppearances(false);
// correct the missing page link for the annotations
for (PDPage page : pdDoc.getPages()) {
for (PDAnnotation annot : page.getAnnotations()) {
System.out.println(annot.getContents());
System.out.println(annot.isPrinted());
System.out.println(annot.isLocked());
System.out.println(annot.getAppearance().toString());
PDPageContentStream contentStream = new PDPageContentStream(pdDoc, page, PDPageContentStream.AppendMode.APPEND,true,true);
int fontHeight = 14;
contentStream.setFont(PDType1Font.TIMES_ROMAN, fontHeight);
float height = annot.getRectangle().getLowerLeftY();
String s = annot.getContents().replaceAll("\t", " ");
String ss[] = s.split("\\r");
for(String sss : ss)
{
contentStream.beginText();
contentStream.newLineAtOffset(annot.getRectangle().getLowerLeftX(),height );
contentStream.showText(sss);
height = height + fontHeight * 2 ;
contentStream.endText();
}
contentStream.close();
page.getAnnotations().remove(annot);
}
}
pdAcroForm.flatten();
pdDoc.save(finalFlat);
pdDoc.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
System.err.println("Exception: " + e.getLocalizedMessage());
}
}
This was not a fun one. After a million different tests, and I STILL do not understand all the nuances, but this is the version that appeas to flatten all pdf files and annotations if they are visible on PDF. Tested about half a dozen pdf creators and if an annotation is visible on a page this hopefully flattens it. I suspect there is a better way by pulling the matrix and transforming it and what not, but this is the only way I got it to work everywhere.
public static void flattenv3(String startDoc, String endDoc) {
org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.INFO);
String finalFlat = endDoc;
try {
try {
//BasicConfigurator.configure();
File myFile = new File(startDoc);
PDDocument pdDoc = PDDocument.load(myFile);
PDDocumentCatalog pdCatalog = pdDoc.getDocumentCatalog();
PDAcroForm pdAcroForm = pdCatalog.getAcroForm();
if (pdAcroForm != null) {
pdAcroForm.setNeedAppearances(false);
pdAcroForm.flatten();
}
// set the NeedApperances flag
boolean isContentStreamWrapped;
int ii = 0;
for (PDPage page: pdDoc.getPages()) {
PDPageContentStream contentStream;
isContentStreamWrapped = false;
List < PDAnnotation > annotations = new ArrayList < > ();
for (PDAnnotation annotation: page.getAnnotations()) {
if (!annotation.isInvisible() && !annotation.isHidden() && annotation.getNormalAppearanceStream() != null)
{
ii++;
if (ii > 1) {
// contentStream.close();
// continue;
}
if (!isContentStreamWrapped) {
contentStream = new PDPageContentStream(pdDoc, page, AppendMode.APPEND, true, true);
isContentStreamWrapped = true;
} else {
contentStream = new PDPageContentStream(pdDoc, page, AppendMode.APPEND, true);
}
PDAppearanceStream appearanceStream = annotation.getNormalAppearanceStream();
PDFormXObject fieldObject = new PDFormXObject(appearanceStream.getCOSObject());
contentStream.saveGraphicsState();
boolean needsTranslation = resolveNeedsTranslation(appearanceStream);
Matrix transformationMatrix = new Matrix();
boolean transformed = false;
float lowerLeftX = annotation.getNormalAppearanceStream().getBBox().getLowerLeftX();
float lowerLeftY = annotation.getNormalAppearanceStream().getBBox().getLowerLeftY();
PDRectangle bbox = appearanceStream.getBBox();
PDRectangle fieldRect = annotation.getRectangle();
float xScale = fieldRect.getWidth() - bbox.getWidth();
transformed = true;
lowerLeftX = fieldRect.getLowerLeftX();
lowerLeftY = fieldRect.getLowerLeftY();
if (bbox.getLowerLeftX() <= 0 && bbox.getLowerLeftY() < 0 && Math.abs(xScale) < 1) //BASICALLY EQUAL TO 0 WITH ROUNDING
{
lowerLeftY = fieldRect.getLowerLeftY() - bbox.getLowerLeftY();
if (bbox.getLowerLeftX() < 0 && bbox.getLowerLeftY() < 0) //THis is for the o
{
lowerLeftX = lowerLeftX - bbox.getLowerLeftX();
}
} else if (bbox.getLowerLeftX() == 0 && bbox.getLowerLeftY() < 0 && xScale >= 0) {
lowerLeftX = fieldRect.getUpperRightX();
} else if (bbox.getLowerLeftY() <= 0 && xScale >= 0) {
lowerLeftY = fieldRect.getLowerLeftY() - bbox.getLowerLeftY() - xScale;
} else if (bbox.getUpperRightY() <= 0) {
if (annotation.getNormalAppearanceStream().getMatrix().getShearY() < 0) {
lowerLeftY = fieldRect.getUpperRightY();
lowerLeftX = fieldRect.getUpperRightX();
}
} else {
}
transformationMatrix.translate(lowerLeftX,
lowerLeftY);
contentStream.transform(transformationMatrix);
contentStream.drawForm(fieldObject);
contentStream.restoreGraphicsState();
contentStream.close();
}
}
page.setAnnotations(annotations);
}
pdDoc.save(finalFlat);
pdDoc.close();
File file = new File(finalFlat);
// Desktop.getDesktop().browse(file.toURI());
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("Exception: " + e.getLocalizedMessage());
}
}
}

Java how change font in converter pdf - pdfbox

i have a problem. I create application JavaFX management for data base. I decided to convert data from tableview to pdf. For this I used a pdfbox. I can't change font in my converter pdf. How can do it? Because helvetica does not support the UTF-8 (ą, ę, ź ...).
enter code here public enum Orientation{
PORTRAIT, LANDSCAPE
};
public boolean doPrintToPdf(List<List> list, File saveLoc,Orientation orientation) {
try {
if (saveLoc == null) {
return false;
}
if (!saveLoc.getName().endsWith(".pdf")) {
saveLoc = new File(saveLoc.getAbsoluteFile() + ".pdf");
}
//Inicjalizacja dokumentu
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
if (orientation == Orientation.LANDSCAPE) {
page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(), PDRectangle.A4.getWidth()));
} else {
page.setMediaBox(new PDRectangle(PDRectangle.A4.getWidth(), PDRectangle.A4.getHeight()));
}
doc.addPage(page);
float margin = 10;
float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
float yStartNewPage = page.getMediaBox().getHeight() - (2 * margin);
float yStart = yStartNewPage;
float bottomMargin = 0;
BaseTable dataTable = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc, page, true,
true);
DataTable t = new DataTable(dataTable, page);
t.addListToTable(list, DataTable.HASHEADER);
dataTable.draw();
doc.save(saveLoc);
doc.close();
return true;
} catch (IOException e) {
DialogsUtils.errorDialog(e.getMessage());
}
return false;

One Row in One Page: Boxable

This is the code for this issue for you to check if there is any problem in the code.
Now the problem is when I limit the rows to 45 (this number fits in one page) every row will print in one page.
But, If I don't limit the rows and the row size (approximately 100-200), every row goes to new page in the PDF. The PDF page number goes to approximately equal to row numbers.
I have opened this issue in Boxable's git but it's not active so I came for help here.
Following are the files generated in both conditions:
LimitTemp.pdf
noLimitTemp.pdf
public class CSVtoPDF {
private float marginBetweenYElements = 10;
private float titleFontSize = 18;
private float fontSize = 8;
private float headerFontSize = 12;
private float header1FontSize = 14;
private float header2FontSize = 12;
private float headerCellHeight = 19;
private float dataCellHeight = 12;
private PDFont font = PDType1Font.HELVETICA;
private PDFont headerFont = PDType1Font.TIMES_BOLD;
List filteredData = new ArrayList();
ReportSettings rs = new ReportSettings();
String filePath, destPath, header1, header2, filename;
public CSVtoPDF(List data, Audit audit) throws IOException {
this.filteredData = data;
Date liveDate = new Date();
SimpleDateFormat format= new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
liveDate = Calendar.getInstance().getTime();
float headerCellHeight = 18;
PDDocument doc = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
//page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(),
// PDRectangle.A4.getWidth()));
PDPageContentStream cos = new PDPageContentStream(doc, page);
/* Add page to PDDocument */
doc.addPage(page);
System.out.println("Inside Main csvtopdf");
//Draw Header
Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
try {
String[] keys = prefs.keys();
//destPath = prefs.get("destpath", rs.getDestPath());
//filename = prefs.get("file_name", rs.getFileName());
//header1 = prefs.get("header1", rs.getHeader1());
//header2 = prefs.get("header2", rs.getHeader2());
} catch (BackingStoreException ex) {
System.err.println(ex);
}
header1= "Header 1";
header2= "Header 2";
cos.beginText();
cos.moveTextPositionByAmount(220, 810);
cos.setFont(headerFont, header1FontSize);
cos.drawString(header1);
cos.endText();
cos.beginText();
cos.moveTextPositionByAmount(220, 800);
cos.setFont(headerFont, header2FontSize);
cos.drawString(header2);
cos.endText();
cos.beginText();
cos.moveTextPositionByAmount(220, 790);
cos.setFont(headerFont, headerFontSize);
cos.drawString("Report: Filtered Audit Report");
cos.endText();
//cos.beginText();
// cos.moveTo(200, 30);
//cos.setFont(headerFont, headerFontSize);
// cos.drawString(header2);
//cos.endText();
/* Initialize DataTable */
float margin = 20;
float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
float yStartNewPage = page.getMediaBox().getHeight() - (2 * margin);
float yStart = yStartNewPage;
float bottomMargin = -800;
BaseTable table = new BaseTable(yStart, yStartNewPage,
bottomMargin, tableWidth, margin, doc, page, true, true);
Row<PDPage> dataRow = table.createRow(dataCellHeight);
for (int i = 0; i < data.size() - 1; i++) {
System.out.println(data.get(i));
}
drawTableData(table, dataCellHeight, 20, data, 1,doc,page);
table.draw();
File result;
if (Objects.isNull(destPath)) {
cos.close();
result = new File("temp.pdf");
} else {
result = new File(destPath);
}
System.out.println("befor save result");
doc.save(result);
System.out.println("after save result");
}
public void drawTableData(BaseTable table, float dataCellHeight, float
cellWidth, List<Audit> data, int style,PDDocument doc,PDPage page) {
String s;
Cell<PDPage> cell;
// for (int k = 0; k < data.size(); k++) {
System.out.println("inside drawtable for ");
for (int i = 0; i < data.size(); i++) { // add row
System.out.println("inside drawtable for " + i);
Audit atmp = data.get(i);
//if (i==35) {
// doc.addPage(page);
//}
Row<PDPage> sTableRow = table.createRow(dataCellHeight);
for (int j = 0; j <= 2; j++) { //add cell in the rows
if (j == 0) { // normal cells on right
s = atmp.getTimeStamp();
s = s.replaceAll("^\"|\"$", "");
cell = sTableRow.createCell(cellWidth, s, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
setStyle(style, cell);
//k++;
} else if (j == 1) { //big cells on left
s = atmp.getDiscription();
s = s.replaceAll("^\"|\"$", "");
cell = sTableRow.createCell(cellWidth + 50, s, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
setStyle(style, cell);
// k++;
} else if (j == 2) { //top blank cell
//System.out.println("In j null and 0 " + j);
s = atmp.getUserID();
s = s.replaceAll("^\"|\"$", "");
cell = sTableRow.createCell(cellWidth - 10, s, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
//cell.setBottomBorderStyle(null);
setStyle(style, cell);
//k++;
}
}
table.addHeaderRow(sTableRow);
System.out.println(" row added ");
}
//}
}
public void setStyle(int type, Cell cell) {
// type : 0 as header, 1 as table body
if (type == 0) {
cell.setFont(headerFont);
//cell.setHeight(headerCellHeight);
cell.setFontSize(headerFontSize);
cell.setBottomPadding(3);
} else if (type == 1) {
cell.setTopPadding(1);
cell.setFont(font);
cell.setAlign(HorizontalAlignment.LEFT);
//cell.setHeight(dataCellHeight);
cell.setFontSize(fontSize);
cell.setBottomPadding(1);
}
}
I found a silly problem in my code. I am telling this so that someone else must not repeat this.
I treated every row of the data table as header row. So it went to new page.
To be specific. In the function drawTableData I removed table.addHeaderRow(sTableRow)

PDFBox: put two A4 pages on one A3

I have a pdf document with one or more pages A4 paper.
The resulting pdf document should be A3 paper where each page contains two from the first one (odd on the left, even on the right side).
I already got it to render the A4 pages into images and the odd pages are successfully placed on the first parts of a new A3 pages but I cannot get the even pages to be placed.
public class CreateLandscapePDF {
public void renderPDF(File inputFile, String output) {
PDDocument docIn = null;
PDDocument docOut = null;
float width = 0;
float height = 0;
float posX = 0;
float posY = 0;
try {
docIn = PDDocument.load(inputFile);
PDFRenderer pdfRenderer = new PDFRenderer(docIn);
docOut = new PDDocument();
int pageCounter = 0;
for(PDPage pageIn : docIn.getPages()) {
pageIn.setRotation(270);
BufferedImage bufferedImage = pdfRenderer.renderImage(pageCounter);
width = bufferedImage.getHeight();
height = bufferedImage.getWidth();
PDPage pageOut = new PDPage(PDRectangle.A3);
PDImageXObject image = LosslessFactory.createFromImage(docOut, bufferedImage);
PDPageContentStream contentStream = new PDPageContentStream(docOut, pageOut, AppendMode.APPEND, true, true);
if((pageCounter & 1) == 0) {
pageOut.setRotation(90);
docOut.addPage(pageOut);
posX = 0;
posY = 0;
} else {
posX = 0;
posY = width;
}
contentStream.drawImage(image, posX, posY);
contentStream.close();
bufferedImage.flush();
pageCounter++;
}
docOut.save(output + "\\LandscapeTest.pdf");
docOut.close();
docIn.close();
} catch(IOException io) {
io.printStackTrace();
}
}
}
I'm using Apache PDFBox 2.0.2 (pdfbox-app-2.0.2.jar)
Thank you very much for your help and the link to the other question - I think I already read it but wasn't able to use in in my code yet.
But finally the PDFClown made the job, though I think it's not very nice to use PDFBox and PDFClown in the same program.
Anyway here's my working code to combine A4 pages on A3 paper.
public class CombinePages {
public void run(String input, String output) {
try {
Document source = new File(input).getDocument();
Pages sourcePages = source.getPages();
Document target = new File().getDocument();
Page targetPage = null;
int pageCounter = 0;
double moveByX = .0;
for(Page sourcePage : source.getPages()) {
if((pageCounter & 1) == 0) {
//even page gets a blank page
targetPage = new Page(target);
target.setPageSize(PageFormat.getSize(PageFormat.SizeEnum.A3, PageFormat.OrientationEnum.Landscape));
target.getPages().add(targetPage);
moveByX = .0;
} else {
moveByX = .50;
}
//get content from source page
XObject xObject = sourcePages.get(pageCounter).toXObject(target);
PrimitiveComposer composer = new PrimitiveComposer(targetPage);
Dimension2D targetSize = targetPage.getSize();
Dimension2D sourceSize = xObject.getSize();
composer.showXObject(xObject, new Point2D.Double(targetSize.getWidth() * moveByX, targetSize.getHeight() * .0), new Dimension(sourceSize.getWidth(), sourceSize.getHeight()), XAlignmentEnum.Left, YAlignmentEnum.Top, 0);
composer.flush();
pageCounter++;
}
target.getFile().save(output + "\\CombinePages.pdf", SerializationModeEnum.Standard);
source.getFile().close();
} catch (FileNotFoundException fnf) {
log.error(fnf);
} catch (IOException io) {
log.error(io);
}
}
}

Categories