Need to shift the table to right in apache poi word - apache-poi
I have created the table in apache POI, need to create another similar table but shifted right:
But I want to create similar another table to the right but at bottom.
Do we have a setting in XWPFTable to set the alignment for the table to shift right or Do i need to re-build the entire table again
Code snippet
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.math.BigInteger;
public class WordBuilder {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The table:");
createNonGroupedSubTacTable(document);
CTSectPr sectPr = document.getDocument().getBody().getSectPr();
if (sectPr == null) sectPr = document.getDocument().getBody().addNewSectPr();
CTPageSz pageSz = sectPr.addNewPgSz();
pageSz.setOrient(STPageOrientation.PORTRAIT);
pageSz.setW(BigInteger.valueOf(11900)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
pageSz.setH(BigInteger.valueOf(16840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"
FileOutputStream out = new FileOutputStream("example_docx");
document.write(out);
out.close();
}
private static void createNonGroupedSubTacTable(XWPFDocument document) {
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
XWPFTable table = document.createTable(10, 8);
setTableAlign(table);
int defaultColWidth = 1 * 1600 * 5 / 8; // 8 columns fits to 8 inches
int[] colunmWidths = new int[]{
defaultColWidth * 3 / 4, defaultColWidth * 8 / 4, defaultColWidth * 2 / 4, defaultColWidth * 3 / 4,
defaultColWidth * 3 / 4, defaultColWidth * 2 / 4, defaultColWidth * 8 / 4, defaultColWidth * 3 / 4
};
table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[0]));
setColumnWidth(table, 0, 0, colunmWidths[0]);
//other columns
for (int col = 1; col < colunmWidths.length; col++) {
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[col]));
setColumnWidth(table, 0, col, colunmWidths[col]);
}
//set cell borders
for (int col = 0; col < 3; col++) {
setCellBorders(table.getRow(0).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.THICK, STBorder.NIL, STBorder.NIL});
}
setCellBorders(table.getRow(0).getCell(3), new STBorder.Enum[]{STBorder.NIL, STBorder.THICK, STBorder.THICK, STBorder.NIL});
setCellBorders(table.getRow(0).getCell(4), new STBorder.Enum[]{STBorder.THICK, STBorder.THICK, STBorder.NIL, STBorder.NIL});
for (int col = 5; col < 8; col++) {
setCellBorders(table.getRow(0).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.THICK, STBorder.NIL, STBorder.NIL});
}
for (int col = 0; col < 3; col++) {
setCellBorders(table.getRow(1).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK});
}
setCellBorders(table.getRow(1).getCell(3), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.THICK, STBorder.THICK});
setCellBorders(table.getRow(1).getCell(4), new STBorder.Enum[]{STBorder.THICK, STBorder.NIL, STBorder.NIL, STBorder.THICK});
for (int col = 5; col < 8; col++) {
setCellBorders(table.getRow(1).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK});
}
table.getRow(0).setHeight(28 * 20); // 28pt row height
table.getRow(0).getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT);
XWPFTableCell cell = table.getRow(0).getCell(7);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("Species:");
cell = table.getRow(0).getCell(6);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("Greater silver smelt");
cell = table.getRow(0).getCell(3);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(9);
run.setText("Zone:");
cell = table.getRow(0).getCell(1);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(9);
run.setText("Union and international waters of 1 and 2 (2)");
table.getRow(1).setHeight(28 * 20); // 28pt row height
table.getRow(1).getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT);
cell = table.getRow(1).getCell(6);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
paragraph.setAlignment(ParagraphAlignment.RIGHT);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.addBreak();
run = paragraph.createRun();
run.setText("Argentinia silos");
cell = table.getRow(1).getCell(1);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.addTab();
run = paragraph.createRun();
run.addTab();
run = paragraph.createRun();
run.addBreak();
run = paragraph.createRun();
run.setText("(ARU/1/2)");
for (int row = 2; row < 6; row++) {
for (int col = 5; col < 8; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
setCellBorders(table.getRow(row).getCell(5), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
setCellBorders(table.getRow(row).getCell(6), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
for (int col = 0; col < 5; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
XWPFTableCell cell1 = table.getRow(row).getCell(7);
paragraph = (cell1.getParagraphs().size() > 0) ? cell1.getParagraphs().get(0) : cell1.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(10);
run.setText("Belgium");
cell = table.getRow(row).getCell(6);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
paragraph.setAlignment(ParagraphAlignment.RIGHT);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("6 ");
run = paragraph.createRun();
run.setText("(2)");
run.setSubscript(VerticalAlign.SUPERSCRIPT); // superscript (2)
}
mergeCellHorizontally(table, 2, 0, 3);
cell = table.getRow(2).getCell(0);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(9);
run.setText("Analytical TAC");
mergeCellHorizontally(table, 3, 0, 3);
cell = table.getRow(3).getCell(0);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(9);
run.setText("Article 3 of Regulation (EC) No 847/96 shall not apply");
mergeCellHorizontally(table, 4, 0, 3);
cell = table.getRow(4).getCell(0);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(10);
run.setText("Article 4 of Regulation (EC) No 847/96 shall not apply.");
for (int col = 0; col < 8; col++) {
setCellBorders(table.getRow(6).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
for (int row = 7; row < 8; row++) {
for (int col = 5; col < 8; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
setCellBorders(table.getRow(row).getCell(3), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
setCellBorders(table.getRow(row).getCell(4), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
for (int col = 0; col < 3; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
XWPFTableCell cell1 = table.getRow(row).getCell(7);
paragraph = (cell1.getParagraphs().size() > 0) ? cell1.getParagraphs().get(0) : cell1.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("TAC");
cell = table.getRow(row).getCell(6);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
paragraph.setAlignment(ParagraphAlignment.RIGHT);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run = paragraph.createRun();
run.setText("10");
run = paragraph.createRun();
run.setText("(2)");
run.setSubscript(VerticalAlign.SUPERSCRIPT); // superscript (2)
}
for (int row = 8; row < 10; row++) {
if (row == 9) {
for (int col = 0; col < 3; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK});
}
setCellBorders(table.getRow(row).getCell(5), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK});
setCellBorders(table.getRow(row).getCell(3), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK});
for (int col = 4; col < 8; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK});
}
} else {
for (int col = 0; col < 3; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
setCellBorders(table.getRow(row).getCell(5), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
setCellBorders(table.getRow(row).getCell(3), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
for (int col = 4; col < 8; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
}
XWPFTableCell cell1 = table.getRow(row).getCell(7);
paragraph = (cell1.getParagraphs().size() > 0) ? cell1.getParagraphs().get(0) : cell1.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("1");
mergeCellHorizontally(table, row, 0, 5);
cell = table.getRow(row).getCell(0);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run = paragraph.createRun();
run.setFontSize(9);
run.setText("Up to 2 % of the quota may consist of by-catches of whiting and mackerel (OT1/*2A3A4). " +
"By-catches of whiting and mackerel counted against the quota pursuant to this provision and by-catches of species counted " +
"against the quota pursuant to Article 15(8) of Regulation (EU) No 1380/2013 shall, together, not exceed 9% of the quota.");
}
}
private static void setColumnWidth(XWPFTable table, int row, int col, int width) {
CTTblWidth tblWidth = CTTblWidth.Factory.newInstance();
tblWidth.setW(BigInteger.valueOf(width));
tblWidth.setType(STTblWidth.DXA);
CTTcPr tcPr = table.getRow(row).getCell(col).getCTTc().getTcPr();
if (tcPr != null) {
tcPr.setTcW(tblWidth);
} else {
tcPr = CTTcPr.Factory.newInstance();
tcPr.setTcW(tblWidth);
table.getRow(row).getCell(col).getCTTc().setTcPr(tcPr);
}
}
private static void setCellBorders(XWPFTableCell cell, STBorder.Enum[] borderTypesLTRB) {
CTTcBorders borders = CTTcBorders.Factory.newInstance();
borders.addNewLeft().setVal(borderTypesLTRB[0]);
borders.addNewTop().setVal(borderTypesLTRB[1]);
borders.addNewRight().setVal(borderTypesLTRB[2]);
borders.addNewBottom().setVal(borderTypesLTRB[3]);
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr != null) {
tcPr.setTcBorders(borders);
} else {
tcPr = CTTcPr.Factory.newInstance();
tcPr.setTcBorders(borders);
cell.getCTTc().setTcPr(tcPr);
}
}
private static void mergeCellHorizontally(XWPFTable table, int row, int fromCol, int toCol) {
XWPFTableCell cell = table.getRow(row).getCell(fromCol);
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr();
if (tcPr.isSetGridSpan()) {
tcPr.getGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1));
} else {
tcPr.addNewGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1));
}
for (int colIndex = toCol; colIndex > fromCol; colIndex--) {
table.getRow(row).getCtRow().removeTc(colIndex);
table.getRow(row).removeCell(colIndex);
}
}
private static void setTableAlign(XWPFTable table) {
CTTbl cttblp = table.getCTTbl();
CTTblPr cttblpr;
cttblpr = (cttblp.getTblPr() == null ? cttblp.addNewTblPr() : cttblp.getTblPr());
cttblpr.addNewBidiVisual().setVal(STOnOff.ON);
CTJc ctjc = (cttblpr.isSetJc() ? cttblpr.getJc() : cttblpr.addNewJc());
ctjc.setVal(STJc.LEFT);
}
}
You can indent the table using the low level org.openxmlformats.schemas.wordprocessingml.x2006.main.* classes.
XWPFTable table = document.createTable(3,3);
// set indentation of the table
CTTblWidth tableIndentation = table.getCTTbl().getTblPr().addNewTblInd();
tableIndentation.setW(BigInteger.valueOf(720)); //720 TWentieths of an Inch Point (Twips) = 720/20 = 36 pt = 36/72 = 0.5"
tableIndentation.setType(STTblWidth.DXA);
But there also is XWPFTable.setTableAlignment. Using that you can align the whole table.
XWPFTable table = document.createTable(3,3);
table.setTableAlignment(TableRowAlign.RIGHT); //table right aligned
For apache poi versions prior 4.1.1 the following low level approach can be used to right align the table:
XWPFTable table = document.createTable(3,3);
table.getCTTbl().getTblPr().addNewJc().setVal(STJc.RIGHT); //table right aligned
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import java.math.BigInteger;
public class CreateWordTableIndent {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The table indented:");
XWPFTable table = document.createTable(3,3);
// set indentation of the table
CTTblWidth tableIndentation = table.getCTTbl().getTblPr().addNewTblInd();
tableIndentation.setW(BigInteger.valueOf(720)); //720 TWentieths of an Inch Point (Twips) = 720/20 = 36 pt = 36/72 = 0.5"
tableIndentation.setType(STTblWidth.DXA);
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
table.getRow(row).getCell(col).setText("row " + row + ", col " + col);
}
}
//create CTTblGrid for this table with widths of the 3 columns.
//necessary for Libreoffice/Openoffice to accept the column widths.
//first column
table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(1440+1440/8));
//other columns
for (int col = 1; col < 3; col++) {
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(1440+1440/8));
}
paragraph = document.createParagraph();
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("The table right aligned:");
table = document.createTable(3,3);
table.setTableAlignment(TableRowAlign.RIGHT); //table right aligned
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
table.getRow(row).getCell(col).setText("row " + row + ", col " + col);
}
}
//create CTTblGrid for this table with widths of the 3 columns.
//necessary for Libreoffice/Openoffice to accept the column widths.
//first column
table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(1440+1440/8));
//other columns
for (int col = 1; col < 3; col++) {
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(1440+1440/8));
}
paragraph = document.createParagraph();
FileOutputStream out = new FileOutputStream("CreateWordTableIndent.docx");
document.write(out);
out.close();
document.close();
}
}
Result:
This answer is about your problems with your provided complete example:
First: Aligning by using bidirectional text settings so table is displayed in a right to left direction is not to recommend. This only should be used for langauges which really needs bidirectional text, hebrew or arabic for example. So your table aligning rather should be like:
private static void setTableAlign(XWPFTable table, STJc.Enum align) {
CTTbl cttblp = table.getCTTbl();
CTTblPr cttblpr = (cttblp.getTblPr() == null ? cttblp.addNewTblPr() : cttblp.getTblPr());
CTJc ctjc = (cttblpr.isSetJc() ? cttblpr.getJc() : cttblpr.addNewJc());
ctjc.setVal(align);
}
Second: When cells were merged, then the column width for the new merged cell should be set. Else Word will possibly use kinds of unwanted automatism to determine column widths. So for example:
...
mergeCellHorizontally(table, 2, 4, 7);
setColumnWidth(table, 2, 4, colunmWidths[4]+colunmWidths[5]+colunmWidths[6]+colunmWidths[7]);
...
and
...
mergeCellHorizontally(table, row, 1, 7);
setColumnWidth(table, row, 1, colunmWidths[1]+colunmWidths[2]+colunmWidths[3]+colunmWidths[4]+colunmWidths[5]+colunmWidths[6]+colunmWidths[7]);
...
Complete example for creating a right aligned table as of your provided screen shots:
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.io.FileOutputStream;
import java.math.BigInteger;
public class WordBuilder {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The table:");
createNonGroupedSubTacTable(document);
CTSectPr sectPr = document.getDocument().getBody().getSectPr();
if (sectPr == null) sectPr = document.getDocument().getBody().addNewSectPr();
CTPageSz pageSz = sectPr.addNewPgSz();
pageSz.setOrient(STPageOrientation.PORTRAIT);
pageSz.setW(BigInteger.valueOf(11900)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
pageSz.setH(BigInteger.valueOf(16840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"
FileOutputStream out = new FileOutputStream("example.docx");
document.write(out);
out.close();
document.close();
}
private static void createNonGroupedSubTacTable(XWPFDocument document) {
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
XWPFTable table = document.createTable(10, 8);
setTableAlign(table, STJc.RIGHT);
int defaultColWidth = 1 * 1600 * 5 / 8; // 8 columns fits to 8 inches
int[] colunmWidths = new int[]{
defaultColWidth * 3 / 4, defaultColWidth * 2 / 4, defaultColWidth * 8 / 4, defaultColWidth * 3 / 4,
defaultColWidth * 3 / 4, defaultColWidth * 2 / 4, defaultColWidth * 8 / 4, defaultColWidth * 3 / 4
};
table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[0]));
setColumnWidth(table, 0, 0, colunmWidths[0]);
//other columns
for (int col = 1; col < colunmWidths.length; col++) {
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[col]));
setColumnWidth(table, 0, col, colunmWidths[col]);
}
//set cell borders
for (int col = 0; col < 3; col++) {
setCellBorders(table.getRow(0).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.THICK, STBorder.NIL, STBorder.NIL});
}
setCellBorders(table.getRow(0).getCell(3), new STBorder.Enum[]{STBorder.NIL, STBorder.THICK, STBorder.THICK, STBorder.NIL});
setCellBorders(table.getRow(0).getCell(4), new STBorder.Enum[]{STBorder.THICK, STBorder.THICK, STBorder.NIL, STBorder.NIL});
for (int col = 5; col < 8; col++) {
setCellBorders(table.getRow(0).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.THICK, STBorder.NIL, STBorder.NIL});
}
for (int col = 0; col < 3; col++) {
setCellBorders(table.getRow(1).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK});
}
setCellBorders(table.getRow(1).getCell(3), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.THICK, STBorder.THICK});
setCellBorders(table.getRow(1).getCell(4), new STBorder.Enum[]{STBorder.THICK, STBorder.NIL, STBorder.NIL, STBorder.THICK});
for (int col = 5; col < 8; col++) {
setCellBorders(table.getRow(1).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK});
}
table.getRow(0).setHeight(28 * 20); // 28pt row height
table.getRow(0).getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT);
XWPFTableCell cell = table.getRow(0).getCell(0);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("Species:");
cell = table.getRow(0).getCell(2);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("Greater silver smelt");
cell = table.getRow(0).getCell(4);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(9);
run.setText("Zone:");
cell = table.getRow(0).getCell(6);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(9);
run.setText("Union and international waters of 1 and 2 (2)");
table.getRow(1).setHeight(28 * 20); // 28pt row height
table.getRow(1).getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT);
cell = table.getRow(1).getCell(2);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
paragraph.setAlignment(ParagraphAlignment.RIGHT);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.addBreak();
run = paragraph.createRun();
run.setText("Argentinia silos");
cell = table.getRow(1).getCell(6);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.addTab();
run = paragraph.createRun();
run.addTab();
run = paragraph.createRun();
run.addBreak();
run = paragraph.createRun();
run.setText("(ARU/1/2)");
for (int row = 2; row < 6; row++) {
for (int col = 5; col < 8; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
setCellBorders(table.getRow(row).getCell(5), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
setCellBorders(table.getRow(row).getCell(6), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
for (int col = 0; col < 5; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
XWPFTableCell cell1 = table.getRow(row).getCell(0);
paragraph = (cell1.getParagraphs().size() > 0) ? cell1.getParagraphs().get(0) : cell1.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(10);
run.setText("Belgium");
cell = table.getRow(row).getCell(3);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
//paragraph.setAlignment(ParagraphAlignment.RIGHT);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("6 ");
run = paragraph.createRun();
run.setText("(2)");
run.setSubscript(VerticalAlign.SUPERSCRIPT); // superscript (2)
}
mergeCellHorizontally(table, 2, 4, 7);
setColumnWidth(table, 2, 4, colunmWidths[4]+colunmWidths[5]+colunmWidths[6]+colunmWidths[7]);
cell = table.getRow(2).getCell(4);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(9);
run.setText("Analytical TAC");
mergeCellHorizontally(table, 3, 4, 7);
setColumnWidth(table, 3, 4, colunmWidths[4]+colunmWidths[5]+colunmWidths[6]+colunmWidths[7]);
cell = table.getRow(3).getCell(4);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(9);
run.setText("Article 3 of Regulation (EC) No 847/96 shall not apply");
mergeCellHorizontally(table, 4, 4, 7);
setColumnWidth(table, 4, 4, colunmWidths[4]+colunmWidths[5]+colunmWidths[6]+colunmWidths[7]);
cell = table.getRow(4).getCell(4);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontSize(9);
run.setText("Article 4 of Regulation (EC) No 847/96 shall not apply.");
for (int col = 0; col < 8; col++) {
setCellBorders(table.getRow(6).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
for (int row = 7; row < 8; row++) {
for (int col = 0; col < 8; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
XWPFTableCell cell1 = table.getRow(row).getCell(0);
paragraph = (cell1.getParagraphs().size() > 0) ? cell1.getParagraphs().get(0) : cell1.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("TAC");
cell = table.getRow(row).getCell(3);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
//paragraph.setAlignment(ParagraphAlignment.RIGHT);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run = paragraph.createRun();
run.setText("10");
run = paragraph.createRun();
run.setText("(2)");
run.setSubscript(VerticalAlign.SUPERSCRIPT); // superscript (2)
}
for (int row = 8; row < 10; row++) {
if (row == 9) {
for (int col = 0; col < 8; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK});
}
} else {
for (int col = 0; col < 8; col++) {
setCellBorders(table.getRow(row).getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
}
XWPFTableCell cell1 = table.getRow(row).getCell(0);
paragraph = (cell1.getParagraphs().size() > 0) ? cell1.getParagraphs().get(0) : cell1.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText("1");
mergeCellHorizontally(table, row, 1, 7);
setColumnWidth(table, row, 1, colunmWidths[1]+colunmWidths[2]+colunmWidths[3]+colunmWidths[4]+colunmWidths[5]+colunmWidths[6]+colunmWidths[7]);
cell = table.getRow(row).getCell(1);
paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run = paragraph.createRun();
run.setFontSize(9);
run.setText("Up to 2 % of the quota may consist of by-catches of whiting and mackerel (OT1/*2A3A4). " +
"By-catches of whiting and mackerel counted against the quota pursuant to this provision and by-catches of species counted " +
"against the quota pursuant to Article 15(8) of Regulation (EU) No 1380/2013 shall, together, not exceed 9% of the quota.");
}
}
private static void setColumnWidth(XWPFTable table, int row, int col, int width) {
CTTblWidth tblWidth = CTTblWidth.Factory.newInstance();
tblWidth.setW(BigInteger.valueOf(width));
tblWidth.setType(STTblWidth.DXA);
CTTcPr tcPr = table.getRow(row).getCell(col).getCTTc().getTcPr();
if (tcPr != null) {
tcPr.setTcW(tblWidth);
} else {
tcPr = CTTcPr.Factory.newInstance();
tcPr.setTcW(tblWidth);
table.getRow(row).getCell(col).getCTTc().setTcPr(tcPr);
}
}
private static void setCellBorders(XWPFTableCell cell, STBorder.Enum[] borderTypesLTRB) {
CTTcBorders borders = CTTcBorders.Factory.newInstance();
borders.addNewLeft().setVal(borderTypesLTRB[0]);
borders.addNewTop().setVal(borderTypesLTRB[1]);
borders.addNewRight().setVal(borderTypesLTRB[2]);
borders.addNewBottom().setVal(borderTypesLTRB[3]);
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr != null) {
tcPr.setTcBorders(borders);
} else {
tcPr = CTTcPr.Factory.newInstance();
tcPr.setTcBorders(borders);
cell.getCTTc().setTcPr(tcPr);
}
}
private static void mergeCellHorizontally(XWPFTable table, int row, int fromCol, int toCol) {
XWPFTableCell cell = table.getRow(row).getCell(fromCol);
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr();
if (tcPr.isSetGridSpan()) {
tcPr.getGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1));
} else {
tcPr.addNewGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1));
}
for (int colIndex = toCol; colIndex > fromCol; colIndex--) {
table.getRow(row).getCtRow().removeTc(colIndex);
table.getRow(row).removeCell(colIndex);
}
}
private static void setTableAlign(XWPFTable table, STJc.Enum align) {
CTTbl cttblp = table.getCTTbl();
CTTblPr cttblpr = (cttblp.getTblPr() == null ? cttblp.addNewTblPr() : cttblp.getTblPr());
CTJc ctjc = (cttblpr.isSetJc() ? cttblpr.getJc() : cttblpr.addNewJc());
ctjc.setVal(align);
}
}
Related
handling a view frustum when not facing the object
i have made a view frustum from scratch in javascript. i have been having trouble with objects that the camera is place within and also facing away from. an example of the problem is below ive been stuck on this for months with little help, chatgpt recommended that i switch to a right handed corodinate system, so i did, but it didnt seem to fix the problem. my proccess for putting pixels on the screen is described below step 1 = cross product with camera matrix step 2 = cross product with projection matrix step 3 = divide co-ordinates by their own w co-ord (normalize w to 1) step 3.5 = im currently skipping culling. culling would go here, but since my object is made of multiple vertices i cant cull a vertex just because its offscreen as it forms part of a whole object, and that would deform the rest of the object step 4 = cross product with projection to screen matrix below shows how the co-ordinates of 1 vertex changes with each step co-ordinates of vertex before projection [5.00,9.00,10.00,1.00] good projection (tile is good) step 1 = [5, 9, -4.799999999999979, 10] step 2 = [-8.660254038143698, 15.588457268658656, 15.353535353535376, 4.799999999999979] step 3 = [-1.8042195912799448, 3.2475952643039006, 3.198653198653217, 1] step 4 = [-120.63293869199174, 637.1392896455851, 3.198653198653217, 1] pixels = -120.63293869199174,637.1392896455851 ############################# bad projection from within the object (tile is deformed) step 1 = [5, 9, 0.6000000000000014, 10] step 2 = [-8.660254038143698, 15.588457268658656, 20.808080808080813, -0.6000000000000014] step 3 = [14.433756730239462, -25.980762114431034, -34.68013468013461, 1] step 4 = [2315.0635095359194, -3747.114317164655, -34.68013468013461, 1] pixels = 2315.0635095359194,-3747.114317164655 ############################### bad projection from behind (tile appears on the ceiling, when A it should be on the floor and B it shouldn't be visible) step 1 = [5, 9, 16.800000000000004, 10] step 2 = [-8.660254038143698, 15.588457268658656, 37.17171717171718, -16.800000000000004] step 3 = [0.5154913117942677, -0.9278843612296817, -2.2126022126022122, 1] step 4 = [227.32369676914016, 10.817345815547753, -2.2126022126022122, 1] pixels = 227.32369676914016, 10.817345815547753 does anyone know which step could be wrong or need changing in situation 2 and 3? and why? below is a minimal (i know its 500 lines... but its about as minimal as i can get it) just open it in a browser and use wasd to control it. <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.3.3/math.js"></script> <script async src="https://unpkg.com/es-module-shims#1.3.6/dist/es-module-shims.js"></script> </head> <body> <div id="canvas div" style = "position: relative; left: 0px; float:left; top: 0px;" > <h1> first person below </h1> <canvas id="mi_canvas" width="300" height="300" style="border-style: solid;"></canvas> <br> <h1> radar below </h1> <canvas id="radar_canvas" width="300" height="300" style="border-style: solid;"></canvas> </div> <div id="big info div" style = "position: relative; left: 310px; float:left; float:top; top: 0px; width:400px;" > <div id = "info_1111"> </div><br> </div> <script> var floor_y_pos = 9 canvas = document.getElementById("mi_canvas"); ctx = canvas.getContext("2d"); radar = document.getElementById("radar_canvas"); radar_ctx = radar.getContext("2d"); render_distance = 1000; fov = math.pi / 2 class Projection{ constructor(){ var NEAR = player.near_plane var FAR = player.far_plane var RIGHT = Math.tan(player.h_fov/2) var LEFT = - RIGHT var TOP = Math.tan(player.v_fov /2) var BOTTOM = -TOP var m00 = 2*NEAR / (RIGHT - LEFT) var m02 = (RIGHT + LEFT)/(RIGHT - LEFT) var m11 = 2*NEAR / (TOP - BOTTOM) var m12 = (TOP + BOTTOM) /(TOP - BOTTOM) var m22 = (FAR * NEAR) / (FAR - NEAR) var m23 = -2 * NEAR * FAR / (FAR-NEAR) this.projection_matrix = [ [-m00,0,m02,0], [0,m11,0,0], [m02,m12,-m22,-1], [0,0,m23,0] ] var HW=player.H_WIDTH var HH = player.H_HEIGHT this.to_screen_matrix = [ [HW,0,0,0], [0,HH,0,0], [0,0,1,0], [HW,HH,0,1] ] } } function multiply(a, b) { var aNumRows = a.length, aNumCols = a[0].length, bNumRows = b.length, bNumCols = b[0].length, m = new Array(aNumRows); // initialize array of rows for (var r = 0; r < aNumRows; ++r) { m[r] = new Array(bNumCols); // initialize the current row for (var c = 0; c < bNumCols; ++c) { m[r][c] = 0; // initialize the current cell for (var i = 0; i < aNumCols; ++i) { m[r][c] += a[r][i] * b[i][c]; } } } return m; } function mi_position_matrix_multiplier(A, B) { var new_matrix = [] for (var new_num_ind = 0; new_num_ind < A.length; ++new_num_ind) { this_num = 0; for (var a_ind = 0; a_ind < A.length; ++a_ind) { this_num += (A[a_ind] * B[a_ind][new_num_ind]) } // console.log("just added this num to my new matrix = "+this_num.toString()) new_matrix.push(this_num) } return new_matrix; } function pythagoras(thing1, thing2) { dist = (((thing1[0]-thing2[0])**2)+((thing1[1]-thing2[1])**2))**0.5 return dist } class vertex{ constructor(x, y,z , id){ this.id = id this.position = [x,y,z,1] this.min_dist = 1.5 // minimum possible distance between player and object } is_this_object_behind_player(){ var arrow_length = 0.0001; var pointing_position = [player.position[0]+(player.forward[0]*arrow_length) , player.position[2]-(player.forward[2]*arrow_length)] var dist1 = pythagoras([this.position[0],this.position[2]], pointing_position) var dist2 = pythagoras([this.position[0],this.position[2]], [player.position[0],player.position[2]]) if (dist1 < dist2){ return true;} else if (dist1 > dist2){ return false;} else{console.log(" else ");} } screen_projection(){ var position = mi_position_matrix_multiplier(this.position , player.camera_matrix()) console.log(position+" = position , which is a cross product of this.position"+this.position+" & "+ player.camera_matrix()+ " = player.camera_matrix()") update_matrix_info_debug("camera_matrix",player.camera_matrix()) update_matrix_info_debug("position", position) position = mi_position_matrix_multiplier(position , projection.projection_matrix) // does this just convert the position to cameras reference frame. console.log(position+" = position , which is a cross product of position"+position+" & "+ projection.projection_matrix+ " = projection.projection_matrix") update_matrix_info_debug("projection_matrix",projection.projection_matrix) update_matrix_info_debug("position after being multiplied by proj matrix", position) // if so then i image to screen matrix is insufficient for (let i = 0; i < position.length; i++) { position[i] = position[i]/position[3] } console.log(position+" = position after being normaslized") for (let i = 0; i < position.length; i++) { if (i != 9787781){ console.log(i+" =-= "+position[i]) if (this.is_this_object_behind_player()){for (let ii = 0; ii < position.length; ii++) {position[ii] = -999999999;} console.log("culling1")} if (position[i] > 2){for (let ii = 0; ii < position.length; ii++) {position[ii] = -9999;} console.log("culling2")} if (position[i] < -2){for (let ii = 0; ii < position.length; ii++) {position[ii] = -9999;} console.log("culling3")} } } // also all examples say set position = 0 if culling console.log(position+" = position after being culled") position = mi_position_matrix_multiplier(position , projection.to_screen_matrix) console.log(position+" = position after being multiplied by "+projection.to_screen_matrix+ " = projection.to_screen_matrix") update_matrix_info_debug("projection.to_screen_matrix",projection.to_screen_matrix) update_matrix_info_debug("position after being multiplied by projection.to_screen_matrix", position) ctx.beginPath(); var scale_multiplier = (render_distance / pythagoras([this.position[0],this.position[2]] , [player.position[0],player.position[2]]))*1.5 var arrow_size = 0.02 * scale_multiplier; ctx.moveTo(position[0]-arrow_size ,position[1]+arrow_size); ctx.lineTo(position[0]+arrow_size ,position[1]-arrow_size); ctx.moveTo(position[0]+arrow_size ,position[1]+arrow_size); ctx.lineTo(position[0]-arrow_size, position[1]-arrow_size); ctx.stroke(); } return_screen_projection(dont_cull = false){ var position = mi_position_matrix_multiplier(this.position , player.camera_matrix()) position = mi_position_matrix_multiplier(position , projection.projection_matrix) // does this just convert the position to cameras reference frame. for (let i = 0; i < position.length; i++) { position[i] = position[i]/position[3] } position = mi_position_matrix_multiplier(position , projection.to_screen_matrix) return [position[0],position[1]] } } class player{ constructor(){ this.position =[0,0,0,1.0] this.forward = [0,0,1,1] this.up = [0,1,0,1] this.right =[1,0,0,1] this.h_fov = 3.1415926535/3 this.v_fov = this.h_fov * (canvas.height / canvas.width) this.near_plane = 1 this.far_plane = 100 this.moving_speed = 0.2 this.rotation_speed = 0.1 this.H_WIDTH = canvas.width/2 this.H_HEIGHT = canvas.height/2 this.anglePitch = 0 this.angleYaw = 0 } set_camera_angle(){ var rotate = multiply(rotate_x(this.anglePitch) , rotate_y(this.angleYaw)) this.forward = [0, 0, 1, 1] this.up = [0, 1, 0, 1] this.right = [1, 0, 0, 1] this.forward = mi_position_matrix_multiplier(this.forward , rotate) this.right = mi_position_matrix_multiplier(this.right , rotate) this.up = mi_position_matrix_multiplier(this.up , rotate) } camera_yaw(angle){ this.angleYaw += angle} translate_matrix(self){ var x = this.position[0]; var y = this.position[1]; var z = this.position[2]; var w = this.position[3]; return [ [1,0,0,0], [0,1,0,1], [0,0,1,0], [-x,-y,z, 1] ]} rotate_matrix(){ var rx = this.right[0] var ry = this.right[1] var rz = this.right[2] var w = this.right[3] var fx = this.forward[0] var fy = this.forward[1] var fz = this.forward[2] var w = this.forward[3] var ux = this.up[0] var uy = this.up[1] var uz = this.up[2] var w = this.up[3] return [ [rx,ux,fx,0], [ry,uy,fy,0], [rz,uz,fz,0], [0,0,0,1] ] } camera_matrix(){ return multiply(this.translate_matrix(), this.rotate_matrix()); } check_min_distance_isnt_overcome_by_this_move(dx, dy){ var can_move = true; console.log(" zzzzzzzzzzzzz ") for (let i = 0; i < objects.length; i++) { var dist=Math.abs(pythagoras([objects[i].position[0], objects[i].position[2]] , [this.position[0], this.position[2]])) var dist2=Math.abs(pythagoras([objects[i].position[0], objects[i].position[2]] , [this.position[0]+dx, this.position[2]+dy])) console.log(dist +" ########################### " +dist2) if ((dist2 < objects[i].min_dist)&(dist > dist2)) {can_move = false; console.log(objects[i].min_dist +" yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")} else{console.log(objects[i].min_dist+" can move this is bloody min dist xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx "+dist2);} } return can_move; } move(event) { var key_code = parseInt(event.keyCode) if (key_code == 37 || key_code == 39 || key_code == 83 || key_code == 87 || key_code == 119|| key_code == 115) { var dx = Math.cos(this.angleYaw)*this.moving_speed var dy = Math.sin(this.angleYaw)*this.moving_speed console.log("that were moving = dx , dy = "+dx.toString()+" , "+dy.toString()) if ( key_code == 37 || key_code == 87 || key_code == 119) { if (this.check_min_distance_isnt_overcome_by_this_move(dx, -dy)){ this.position[0] += -dy this.position[2] += dx } } if (key_code == 39 || key_code == 83 || key_code == 115) { for (let i = 0; i < this.position.length; i++) { if (this.check_min_distance_isnt_overcome_by_this_move(dx, dy)){ this.position[0] += dy this.position[2] += -dx } } } } else { if ( key_code == 38 || key_code == 65 || key_code == 97) { this.camera_yaw(-this.rotation_speed) } if (key_code == 40 || key_code == 68 || key_code == 100) { this.camera_yaw(this.rotation_speed) } this.set_camera_angle() } } } function translate(pos){ tx,ty,tz=pos return np.array([ [1,0,0,0], [0,1,0,0], [0,0,1,0], [tx,ty,tz,1] ])} function rotate_x(angle){ return [ [1,0,0,0], [0,Math.cos(angle),Math.sin(angle),0], [0,-Math.sin(angle),Math.cos(angle),0], [0,0,0,1] ] } function rotate_y(a){ return [ [math.cos(a),0, -math.sin(a),0], [0,1,0,0], [math.sin(a), 0 , math.cos(a),0], [0,0,0,1] ] } function update_radar(){ var arrow_length = 4; var object_size = 6.5; radar_ctx.beginPath(); var mid_screen = [radar.width/2,radar.height/2]; pointing_position = [mid_screen[0]+(player.forward[0]*arrow_length) , mid_screen[1]-(player.forward[2]*arrow_length)] radar_ctx.moveTo(mid_screen[0], mid_screen[1]); // start of player pos on radar radar_ctx.lineTo(pointing_position[0], pointing_position[1]); radar_ctx.lineTo(pointing_position[0]-2, pointing_position[1]-2); radar_ctx.lineTo(pointing_position[0]+2, pointing_position[1]+2); radar_ctx.lineTo(pointing_position[0]-2, pointing_position[1]+2); radar_ctx.moveTo(mid_screen[0], mid_screen[1]); for (let i = 0; i < objects.length; i++) { var dx = (player.position[0]-objects[i].position[0]) var dz = player.position[2]+objects[i].position[2] var x = (dx*2) + mid_screen[0] var z = (dz*2) + mid_screen[1] x = x +(object_size/2) z = z +(object_size/2) radar_ctx.moveTo(x-object_size,z-object_size); radar_ctx.lineTo(x+object_size,z+object_size); radar_ctx.moveTo(x+object_size,z-object_size); radar_ctx.lineTo(x-object_size,z+object_size); } radar_ctx.stroke(); } function update_matrix_info_debug(matrix_name, matrix){ if (matrix[0].length > 1) { for (let x = 1; x < matrix.length+1; x++) { for (let y = 1; y < matrix.length+1; y++) { // console.log(matrix_name.toString()+"_"+x.toString()+y.toString()); document.getElementById(matrix_name.toString()+"_"+x.toString()+y.toString()).innerHTML = matrix[x-1][y-1] } } } else { for (let x = 1; x < matrix.length+1; x++) {document.getElementById(matrix_name.toString()+"_"+"1"+x.toString()).innerHTML = matrix[x-1]} } } class box{ constructor(x,z,size){ var low_y = 0.5 var high_y = low_y - size this.position = [x+(size/2),0,z+(size/2)] this.vertices = [new vertex(x,low_y,z,0),new vertex(x+size,low_y,z,1),new vertex(x,low_y,z+size,2),new vertex(x+size,low_y,z+size,3), new vertex(x,high_y,z,4),new vertex(x+size,high_y,z,5),new vertex(x,high_y,z+size,6),new vertex(x+size,high_y,z+size,7) ] this.faces=[ [0,1,3,2,0], [0,1,5,4,0] , [1,3,7,5,1] , [4,5,7,6,4] , [2,6,7,3,2] , [0,4,6,2,0]] // this.faces=[ [0,4,6,2,0]] } draw_all_vertices(){ for (let i = 0; i < this.vertices.length; i++) { this.vertices[i].screen_projection() } } draw_all_faces(){ var each_point = [] for (let i = 0; i < this.vertices.length; i++) { each_point.push(this.vertices[i].return_screen_projection()) } var skip_drawing = if_most_of_these_numbers_are_off_screen(each_point) if (skip_drawing){console.log(" skipp drawing any faces init ");return;} ctx.fillStyle = '#f00'; var moved_to_first_yet = false for (let face = 0; face < this.faces.length; face++) { ctx.beginPath(); console.log("%%%%%%%%%%%%%%%%%%%%%%%%%"); console.log(this.faces); console.log(this.faces[face]); for (let vertex = 0; vertex < this.faces[face].length; vertex++) { console.log(vertex+" vertex bef dddddddddddddddddddddddddddddd") var vertex2 = this.faces[face][vertex] console.log(vertex2+" vertex aft ddddddddd ") if (moved_to_first_yet == false) { moved_to_first_yet = true ctx.moveTo( each_point[this.vertices[vertex2].id][0],each_point[this.vertices[vertex2].id][1]); } else{ctx.lineTo( each_point[this.vertices[vertex2].id][0],each_point[this.vertices[vertex2].id][1]);} } ctx.closePath(); ctx.fill(); } } } class two_d_surdace { constructor(verex1,verex2,verex3,verex4 , colour){ this.vertices = [verex1,verex2,verex3,verex4] this.colour = colour } draw_all_faces(){ var each_point = [] for (let i = 0; i < this.vertices.length; i++) { each_point.push(this.vertices[i].return_screen_projection(true)) } ctx.fillStyle = this.colour; var moved_to_first_yet = false for (let vertex = 0; vertex < this.vertices.length; vertex++) { console.log(each_point[vertex][0]+" , "+each_point[vertex][1]+ " actual x y points on screen for this vertex of corner of floor ") if (moved_to_first_yet == false) { moved_to_first_yet = true ctx.moveTo( each_point[vertex][0],each_point[vertex][1]); } else{ctx.lineTo( each_point[vertex][0],each_point[vertex][1]);} } ctx.closePath(); ctx.fill(); } } function if_off_screen(x, y) { if (x> canvas.width || x < 0){console.log(x +" x = off screen "); return true;} if (y > canvas.height || y < 0){console.log(y +" y = off screen "); return true;} console.log(x +" , "+y + " =x,y = not off screen "); return false; } function if_most_of_these_numbers_are_off_screen(numbers){ var threshold = 1; //Math.floor(numbers.length*0.49) var counter = 0 console.log(numbers + " xxxx numbers as they come in ") for (let i = 0; i < numbers.length; i++) { if (if_off_screen(numbers[i][0], numbers[i][1])){console.log(numbers[i]+" , "+numbers[i+1]+ " = numbers[i] are off screen"); counter +=1} else{console.log(numbers[i]+" , "+numbers[i+1]+ " = numbers[i] not off screen")} } console.log("quuin quoirs of raptor"); if (counter >= threshold){console.log(threshold+" < " + counter);return true} console.log(threshold+" > " + counter); return false; } player = new player(); projection = new Projection() objects = [] // floor = new two_d_surdace(new vertex(50,floor_y_pos,50) , new vertex(-50,floor_y_pos,50) , new vertex(-50,floor_y_pos,-50) , new vertex(50,floor_y_pos,-50) , '#F90' ) update_radar() $(document).on("keypress", function (event) { player.move(event) ctx.beginPath(); radar_ctx.beginPath(); radar_ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height); for (let i = 0; i < objects.length; i++) { objects[i].draw_all_faces() objects[i].draw_all_vertices() } floor.draw_all_faces() update_radar() }); </script> </body>
Need to reduce the spaces between 2 cells in apache poi word
I am trying to build a table. I need the space between 2 rows to be reduced but I am not able to achieve the result using row.setheight(). Below is the code : import eu.europa.ec.fisheries.quotaprepservice.constants.StrConstants; import eu.europa.ec.fisheries.quotaprepservice.report.bean.Annexe1ATacBeanQuotaItem; import eu.europa.ec.fisheries.quotaprepservice.report.bean.TacBean; import org.apache.logging.log4j.util.Strings; import org.apache.poi.xwpf.usermodel.*; import org.apache.xmlbeans.impl.xb.xmlschema.SpaceAttribute; import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.List; import static eu.europa.ec.fisheries.quotaprepservice.constants.StrConstants.*; public class WordBuilder1 { public static void main(String[] args) throws Exception { XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText("The table:"); XWPFTable table = document.createTable(4, 8); prepareQuotaList(table); CTSectPr sectPr = document.getDocument().getBody().getSectPr(); if (sectPr == null) sectPr = document.getDocument().getBody().addNewSectPr(); CTPageSz pageSz = sectPr.addNewPgSz(); pageSz.setOrient(STPageOrientation.PORTRAIT); pageSz.setW(BigInteger.valueOf(11900)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5" pageSz.setH(BigInteger.valueOf(16840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11" FileOutputStream out = new FileOutputStream("C:\\Users\\mishrne\\example.docx"); document.write(out); out.close(); } private static void prepareQuotaList(XWPFTable table) { int count = 0; for (int row = 0; row < 4; row++) { XWPFTableRow tableRow = table.getRow(row); tableRow.setHeight((short) 0); for (int col = 0; col < 3; col++) { setCellBorders(tableRow.getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL}); } setCellBorders(tableRow.getCell(3), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL}); setCellBorders(tableRow.getCell(4), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL}); for (int col = 5; col < 8; col++) { setCellBorders(tableRow.getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL}); } if (count == 2) { createCell(tableRow.getCell(0), TAC, ParagraphAlignment.LEFT, 9); createCell(tableRow.getCell(2), "80", "(2)", ParagraphAlignment.RIGHT); } else { createCell(tableRow.getCell(0), "Belgium", ParagraphAlignment.LEFT, 9); mergeCellHorizontally(table, row, 2, 3); createCell(tableRow.getCell(2), "80", "(2)", ParagraphAlignment.RIGHT); } count++; } } private static void createCell(XWPFTableCell cell, String text, ParagraphAlignment paragraphAlignment, int fontSize) { XWPFParagraph paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph(); paragraph.setIndentationLeft(5 * 20); // 10pt left indentation paragraph.setAlignment(paragraphAlignment); paragraph.setWordWrapped(true); XWPFRun run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun(); run.setText(text); run.setFontFamily(TIMES_NEW_ROMAN); run.setFontSize(fontSize); cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); } private static void createCell(XWPFTableCell cell, String text, String superscriptText, ParagraphAlignment left) { XWPFRun run; XWPFParagraph paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph(); paragraph.setIndentationLeft(5 * 20); // 10pt left indentation paragraph.setAlignment(ParagraphAlignment.LEFT); paragraph.setSpacingBefore(0); paragraph.setSpacingBeforeLines(0); run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun(); run.setFontFamily(TIMES_NEW_ROMAN); cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); run.setFontSize(9); run.setText(text); run = paragraph.createRun(); run.setText(StrConstants.BLANK_SPACE + StrConstants.BLANK_SPACE + StrConstants.BLANK_SPACE + superscriptText); run.setFontSize(9); run.setFontFamily(TIMES_NEW_ROMAN); run.setSubscript(VerticalAlign.SUPERSCRIPT); // superscript (2) } private static void mergeCellHorizontally(XWPFTable table, int row, int fromCol, int toCol) { XWPFTableCell cell = table.getRow(row).getCell(fromCol); CTTcPr tcPr = cell.getCTTc().getTcPr(); if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr(); if (tcPr.isSetGridSpan()) { tcPr.getGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1)); } else { tcPr.addNewGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1)); } for (int colIndex = toCol; colIndex > fromCol; colIndex--) { table.getRow(row).getCtRow().removeTc(colIndex); table.getRow(row).removeCell(colIndex); } } private static void setCellBorders(XWPFTableCell cell, STBorder.Enum[] borderTypesLTRB) { CTTcBorders borders = CTTcBorders.Factory.newInstance(); borders.addNewLeft().setVal(borderTypesLTRB[0]); borders.addNewTop().setVal(borderTypesLTRB[1]); borders.addNewRight().setVal(borderTypesLTRB[2]); borders.addNewBottom().setVal(borderTypesLTRB[3]); CTTcPr tcPr = cell.getCTTc().getTcPr(); if (tcPr != null) { tcPr.setTcBorders(borders); } else { tcPr = CTTcPr.Factory.newInstance(); tcPr.setTcBorders(borders); cell.getCTTc().setTcPr(tcPr); } } }
To set table row height in XWPFTable table the height rule also must be set additional to the height itself. For example: table.getRow(0).setHeight(12*20); // row height in twentieth pt table.getRow(0).getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT); // height rule exact There are following height rules possible: AT_LEAST: At least the given height. Higher if needed but not lesser. AUTO: The default. Default height of one default paragraph height inclusive spacing before and after. As high as needed dependent on content. EXACT: Exact the given height. Content possibly gets cut of. Note, a 0 value for XWPFTableRow.setHeight will not be accepted in combination with EXACT height rule. This falls back to default AUTO height then. According to your code sample: ... private static void prepareQuotaList(XWPFTable table) { int count = 0; for (int row = 0; row < 4; row++) { XWPFTableRow tableRow = table.getRow(row); tableRow.setHeight(12*20); // row height = 12 pt tableRow.getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT); // height rule exact for (int col = 0; col < 3; col++) { setCellBorders(tableRow.getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL}); } ... } ... As said above there are only the three height rules possible. So if the goal is having table rows as high as their content but not more ore less, then height rule AUTO must be used. Then the paragraph's height determines the row height. Note a XWPFParagraph might have set spacing before, between and after the text rows. So you might have to set: ... paragraph.setSpacingAfter(0); paragraph.setSpacingBetween(1); // don't set this 0 paragraph.setSpacingBefore(0); ... This must be set for each table cell which contains paragraphs already. So if needed for the whole table, then: XWPFTable table = document.createTable(4, 8); for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph p : cell.getParagraphs()) { p.setSpacingAfter(0); p.setSpacingBetween(1); // don't set this 0 p.setSpacingBefore(0); } } }
Create a table in powerpoint with Apache poi
I'm using Java v8 and "org.apache.poi" and "poi-ooxml" (both are version 3.9). I'm trying to create a powerpoint with a slide on it which contains a table. I can get the powerpoint file to create ok but the slide is empty but for a small black box in the top right corner. I'm guessing I'm missing something small but can't see what it is. I've tried some examples from the web and they look to be the same as what I'm seeing. This is what I see in the Powerpoint slide: My code is as below: XMLSlideShow powerpoint = new XMLSlideShow(); XSLFSlide slide = powerpoint.createSlide(); XSLFTable table = slide.createTable(); table.setAnchor(new Rectangle(50, 50, 800, 800)); int numColumns = 3; int numRows = 5; XSLFTableRow headerRow = table.addRow(); headerRow.setHeight(50); // header for (int i = 0; i < numColumns; i++) { XSLFTableCell th = headerRow.addCell(); XSLFTextParagraph p = th.addNewTextParagraph(); p.setTextAlign(TextAlign.CENTER); XSLFTextRun r = p.addNewTextRun(); r.setText("Header " + (i + 1)); r.setFontSize(20); r.setFontColor(Color.white); th.setFillColor(new Color(79, 129, 189)); table.setColumnWidth(i, 150); } // rows for (int rownum = 0; rownum < numRows; rownum++) { XSLFTableRow tr = table.addRow(); tr.setHeight(50); // header for (int i = 0; i < numColumns; i++) { XSLFTableCell cell = tr.addCell(); XSLFTextParagraph p = cell.addNewTextParagraph(); XSLFTextRun r = p.addNewTextRun(); r.setText("Cell " + (i + 1)); if (rownum % 2 == 0) { cell.setFillColor(new Color(208, 216, 232)); } else { cell.setFillColor(new Color(233, 247, 244)); } } } try { try (FileOutputStream out = new FileOutputStream("c:\\myFile.pptx")) { try { powerpoint.write(out); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } Any thoughts/guidance would be really appreciated. Thanks Ro
Handle Null Value In Gridview During Exporting To Excel
I am working with a C# Windows application. Trying to export data from gridview to Excel , but when the gridview column is empty I do get error message. How to handle that? Please help This is my code // Store Header from Gridview to Excel for (int i = 1; i < dgvresult.Columns.Count + 1; i++) { Excel.Cells[1, i] = dgvresult.Columns[i - 1].HeaderText; } // Loop rows and columns of Gridview to store to Excel for (int i = 0; i < dgvresult.Rows.Count; i++) { for (int j = 0; j < dgvresult.Columns.Count; j++) { Excel.Cells[i + 2, j + 1] = dgvresult.Rows[i].Cells[j].Value.ToString(); // Here when the value in Gridview is empty error how to handle this } } Excel.ActiveWorkbook.SaveCopyAs("D:\\Asserts.xls"); Excel.ActiveWorkbook.Saved = true; Excel.Quit(); MessageBox.Show("Excel file created,you can find the file D:\\Asserts.xls"); Excel.Visible = true;
Found solution do a checking by code below private void btnexport_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Excel.ApplicationClass Excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); Excel.Application.Workbooks.Add(Type.Missing); Excel.Columns.ColumnWidth = 14; // Store Header from Gridview to Excel for (int i = 1; i < dgvresult.Columns.Count + 1; i++) { Excel.Cells[1, i] = dgvresult.Columns[i - 1].HeaderText; } // Loop rows and columns of Gridview to store to Excel for (int i = 0; i < dgvresult.Rows.Count; i++) { for (int j = 0; j < dgvresult.Columns.Count; j++) { if (dgvresult.Rows[i].Cells[j].Value == null) { dgvresult.Rows[i].Cells[j].Value = "NA"; // Where the gridview is empty do a checking and Insert NA } Excel.Cells[i + 2, j + 1] = dgvresult.Rows[i].Cells[j].Value.ToString(); } } Excel.ActiveWorkbook.SaveCopyAs("D:\\Asserts.xls"); Excel.ActiveWorkbook.Saved = true; Excel.Quit(); MessageBox.Show("Excel file created,you can find the file D:\\Asserts.xls"); Excel.Visible = true; }
not able to insert image on cell of table when converting griddata to PDF file using iTextsharp in Ext.net
I am using iTextSharp to export Griddata to PDF. I am not able to insert .jpg image to a cell of a table. I want to export griddata(billdata) to PDF I can insert text on a cell but not able to insert image. My code is as below protected void ToPDF(object sender, EventArgs e) { System.IO.MemoryStream PDFData = new System.IO.MemoryStream(); iTextSharp.text.Document newDocument = new iTextSharp.text.Document(PageSize.A4.Rotate(), 10, 10, 10, 10); iTextSharp.text.pdf.PdfWriter newPdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(newDocument, PDFData); DataSet newDataSet = null; string json = GridData.Value.ToString(); if (json != "[]") { StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null); XmlNode xml = eSubmit.Xml; if (xml != null) { XmlTextReader xtr = new XmlTextReader(xml.OuterXml, XmlNodeType.Element, null); newDataSet = new DataSet(); newDataSet.ReadXml(xtr); int totalColumns = newDataSet.Tables[0].Columns.Count; iTextSharp.text.pdf.PdfPTable newPdfTable = new iTextSharp.text.pdf.PdfPTable(totalColumns - 3+1); newPdfTable.DefaultCell.Padding = 1; newPdfTable.WidthPercentage = 80; newPdfTable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT; newPdfTable.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; newPdfTable.HeaderRows = 1; newPdfTable.DefaultCell.BorderColor = new iTextSharp.text.BaseColor(255, 255, 255); newPdfTable.DefaultCell.BackgroundColor = new iTextSharp.text.BaseColor(255, 255, 255); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance("D:\\company_logo.jpg"); image.Alignment = iTextSharp.text.Image.ALIGN_LEFT; iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image); cell.Rowspan = 5; cell.HorizontalAlignment = 0; //cell.Border = 1; newPdfTable.AddCell(cell); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Your company name", FontFactory.GetFont("Times New Roman", 18, Font.BOLD, new iTextSharp.text.BaseColor(80, 80, 80)))); cell.Colspan = 6; cell.HorizontalAlignment = 0; //cell.Border = 1; newPdfTable.AddCell(cell); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(Environment.NewLine)); cell.Colspan = 6; cell.HorizontalAlignment = 0; //cell.Border = 1; newPdfTable.AddCell(cell); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Street Address", FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80)))); cell.Colspan = 6; cell.HorizontalAlignment = 0; //cell.Border =1; newPdfTable.AddCell(cell); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("City, Pincode", FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80)))); cell.Colspan = 5; cell.HorizontalAlignment = 0; //cell.Border = 1; newPdfTable.AddCell(cell); string dt=Convert.ToString( Convert.ToDateTime(dtBill.Text).ToShortDateString()); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Date : " + dt, FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80)))); //cell.Colspan = 2; cell.HorizontalAlignment = 0; //cell.Border = 1; newPdfTable.AddCell(cell); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Phone no., Website, etc.", FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80)))); cell.Colspan = 5; cell.HorizontalAlignment = 0; //cell.Border =1; newPdfTable.AddCell(cell); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Bill no : " + cmbBill.Text, FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80)))); //cell.Colspan = 2; cell.HorizontalAlignment = 0; //cell.Border =1; newPdfTable.AddCell(cell); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(Environment.NewLine)); cell.Colspan = 7; cell.HorizontalAlignment = 0; //cell.Border = 1; newPdfTable.AddCell(cell); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(Environment.NewLine)); cell.Colspan = 7; cell.HorizontalAlignment = 0; //cell.Border = 1; newPdfTable.AddCell(cell); cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(Environment.NewLine)); cell.Colspan = 7; cell.HorizontalAlignment = 0; //cell.Border = 1; newPdfTable.AddCell(cell); for (int i = 0; i <= totalColumns-1 ; i++) { if ((i != 0) & (i != 1) & (i != 2)) { cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(newDataSet.Tables[0].Columns[i].ColumnName, FontFactory.GetFont("Tahoma", 12, Font.BOLD, new iTextSharp.text.BaseColor(80, 80, 80)))); cell.BorderColor = new iTextSharp.text.BaseColor(80, 80, 80); cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.LightGray); cell.VerticalAlignment =iTextSharp.text.Element.ALIGN_MIDDLE; if (i == 5) { cell.Colspan = 2; cell.HorizontalAlignment = 1; } else { cell.HorizontalAlignment = 1; } newPdfTable.AddCell(cell); } } int j = 0; foreach (DataRow record in newDataSet.Tables[0].Rows) { for (int i = 0; i <= totalColumns - 1; i++) { if ((i != 0) & (i != 1) & (i != 2)) { if (i == 3) { if(record[i].ToString()=="true") cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Yes", FontFactory.GetFont("Tahoma", 10, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80)))); else cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("No", FontFactory.GetFont("Tahoma", 10, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80)))); } else { cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(record[i].ToString(), FontFactory.GetFont("Tahoma", 10, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80)))); } if ((j % 2) == 0) { //cell.BorderColor = new iTextSharp.text.BaseColor(System.Drawing.Color); } else { cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.WhiteSmoke); } cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; if (i == 3) cell.Border = iTextSharp.text.pdf.PdfPCell.NO_BORDER; else cell.Border = iTextSharp.text.pdf.PdfPCell.LEFT_BORDER; if (i == 5) { cell.Colspan = 2; cell.HorizontalAlignment = 0; } else { if ((i == 6) | (i == 7) | (i == 8)) { cell.HorizontalAlignment = 2; } else { cell.HorizontalAlignment = 0; } } newPdfTable.AddCell(cell); } } j++; } newDocument.Open(); newDocument.Add(new Phrase(Environment.NewLine)); newDocument.Add(new Phrase(Environment.NewLine)); newDocument.Add(newPdfTable); //newDocument.Add(new Phrase(" Total " + txtTotalQty.Text + " " + txtTotalAmount.Text, FontFactory.GetFont("Trebuchet MS", 14, Font.BOLD, new iTextSharp.text.BaseColor(21, 66, 157)))); newDocument.Add(new Phrase(Environment.NewLine)); //newDocument.Add(new Phrase("Printed On: " + DateTime.Now.ToString(), FontFactory.GetFont("Tahoma", 9, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80)))); newDocument.Close(); Response.ContentType = "application/pdf"; Response.Cache.SetCacheability(System.Web.HttpCacheability.Public); Response.AppendHeader("Content-Type", "application/pdf"); Response.AppendHeader("Content-Disposition", "attachment; filename=" + this.ID + ".pdf"); Response.OutputStream.Write(PDFData.GetBuffer(), 0, PDFData.GetBuffer().Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); } } }
Just replace newPdfTable.HeaderRows = 1; to newPdfTable.HeaderRows = 0; and one more thing iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image); and one more parameter as true iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image,true);