I am developing an application to generate barcode. I need a number of bar codes to be generated at a time and add to a document of A4 size, using iText Table structure. Also all the barcodes to be positioned in a 13 X 5 matrix style, that fits A4 sheet, and to be printed. But for me, the bar codes are not properly aligned and positioned. Kindly help me.
This is the code:
int barwidthleft=(int) 14.112;
int barwidthtop=(int) 53.28;
int barwidthright=(int) 16.56;
int barwidthbottom=(int) 53.28;
float borderwidth=(float) 0.5;
int vgap=0;
int columns=0;
int i=0,j=0;
Rectangle pageSize = new Rectangle(new Rectangle(PageSize.A4));
Document document = new Document(pageSize);
document.setMargins(barwidthleft, barwidthright, barwidthtop, barwidthbottom);
try
{
PdfWriter writer =PdfWriter.getInstance(document,new FileOutputStream(new File("./barcode.pdf")));
document.open();
int count1=0,count2=0,count3=0,count4=0;
int maxcount=qty;
int itemcount=0,barcount=0;
columns=9;
Barcode128 code128 = new Barcode128();
code128.setGenerateChecksum(true);
String code="";
while(count2<maxcount)
{
PdfPTable table = new PdfPTable(columns); // 1 columns.
table.setWidthPercentage(100);
table.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
table.setTotalWidth(new float[]{ (float)107.28, (float)5.61,(float)107.28, (float)5.61,(float)107.28, (float)5.61,(float)107.28, (float)5.61, (float)107.28});
table.setLockedWidth(true);
for(i=0;i<columns &&count2<maxcount;i=i+2)
{
code=Integer.toString(nextcode);
code128.setCode(code);
code128.setBarHeight(30);
code128.setX(1f);
Image img=code128.createImageWithBarcode(writer.getDirectContent(), null, null);
PdfPCell cell2 = new PdfPCell();
cell2.setFixedHeight((float) 59.04);
cell2.addElement(new Paragraph("Choice ",new Font(Font.FontFamily.COURIER, 6)));
cell2.addElement(new Paragraph("Rs. "+itemlist[itemcount][4]+"/-",new Font(Font.FontFamily.COURIER, 6)));
cell2.addElement(new Paragraph(" ",new Font(Font.FontFamily.COURIER, 2)));
cell2.addElement(img);
cell2.setBorder(PdfPCell.NO_BORDER);
cell2.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(cell2);
if(i!=8)
{
PdfPCell cellblank1 = new PdfPCell();
cellblank1.setBorder(PdfPCell.NO_BORDER);
cellblank1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(cellblank1);
}
count2++;
itemcount++;
System.out.println("Two:"+count2);
nextcode++;
}
if(count2>=maxcount)
{
while(i<columns)
{
PdfPCell finalblank1 = new PdfPCell();
finalblank1.setBorder(PdfPCell.NO_BORDER);
finalblank1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(finalblank1);
PdfPCell finalblank2 = new PdfPCell();
finalblank2.setBorder(PdfPCell.NO_BORDER);
finalblank2.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(finalblank1);
i=i+2;
}
}
document.add(table);
}
document.close();
//print
String[]args={};
PrintPdf.main(args);
}
catch(Exception e)
{
System.out.println(e);
}
Related
The drawing of the table is done correctly but it gets wrong as the data is repeated.
the barcode has to be like this to avoid errors from employees checking wrong codes.
The ideal would be A picture speaks a thousand words.
My function:
Document documentoPDF = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(documentoPDF, new FileOutputStream("c:\\exporta_Celso\\contagem_" + jComboBox1.getSelectedItem().toString() + ".pdf"));
documentoPDF.open();
documentoPDF.setPageSize(PageSize.A4);
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100);
table.setTotalWidth(documentoPDF.getPageSize().getWidth());
for (int i = 0; i < itens.size(); i++) {
System.out.println(((List) itens.get(i)).get(0).toString());
System.out.println(((List) itens.get(i)).get(1).toString());
String item = ((List) itens.get(i)).get(1).toString();
BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
String barCodeBruto = ((List) itens.get(i)).get(0).toString();
String barCode = null;
if (barCodeBruto.length() != 13) {
barCode = ("0000000000000" + barCodeBruto).substring(barCodeBruto.length());
} else {
barCode = barCodeBruto;
}
codeEAN.setCode(barCode);
PdfContentByte cb = writer.getDirectContent();
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);
PdfPCell cellBar = new PdfPCell(imageEAN);
PdfPCell cellDesc = new PdfPCell(new Paragraph(item));
PdfPCell cellQtd = new PdfPCell(new Paragraph("QTD."));
cellBar.setPadding(3);
cellBar.setUseDescender(true);
cellBar.setUseAscender(true);
cellDesc.setPadding(3);
cellDesc.setUseDescender(true);
cellDesc.setUseAscender(true);
cellQtd.setPadding(3);
cellQtd.setUseDescender(true);
cellQtd.setUseAscender(true);
float height = table.calculateHeights();
float width = documentoPDF.getPageSize().getWidth();
if (i % 2 == 0) {
float[] widths = new float[]{145f, width - 36 - 10f, 80f};
table.setWidths(widths);
table.addCell(cellBar);
table.addCell(cellDesc);
table.addCell(cellQtd);
}else{
float[] widths = new float[]{80f, width - 36 - 10f, 145f};
table.setWidths(widths);
table.addCell(cellQtd);
table.addCell(cellDesc);
table.addCell(cellBar);
}
PdfContentByte canvas = writer.getDirectContent();
ColumnText columnText = new ColumnText(canvas);
columnText.setSimpleColumn(36, 756 - height, width - 36, 36);
columnText.addElement(table);
columnText.go();
}
} catch (DocumentException de) {
de.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
documentoPDF.close();
}
I solved it by creating a parent table outside the looping.
PdfPTable tableFinal = new PdfPTable(1);
tableFinal.setWidthPercentage(100);
tableFinal.setTotalWidth(documentoPDF.getPageSize().getWidth());
tableFinal.addCell(table);
PdfContentByte canvas = writer.getDirectContent();
ColumnText columnText = new ColumnText(canvas);
columnText.setSimpleColumn(36, 756 - height, width - 36, 36);
columnText.addElement(tableFinal);
columnText.go();
For particular table layout with particular cell having larger data then it is not getting properly exported to PDF, the data in that particular cell getting cropped.
private static void tableLayout1() {
Document doc = new Document();
try {
PdfWriter.getInstance(doc, new FileOutputStream(
".\\TableLayout_1.pdf"));
doc.open();
// Table
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100f);
table.setSplitLate(false);
//row 1
PdfPCell cell00 = new PdfPCell(new Paragraph("Cell00"));
cell00.setBackgroundColor(new Color(200, 0, 0));
cell00.setRowspan(3);
PdfPCell cell01 = new PdfPCell(new Paragraph("Cell01"));
cell01.setBackgroundColor(new Color(0, 200, 0));
cell01.setColspan(2);
//row 2
PdfPCell cell11 = new PdfPCell(new Paragraph("Cell11"));
cell11.setBackgroundColor(new Color(100, 100, 0));
PdfPCell cell12 = new PdfPCell( getLongCellData() );
cell12.setBackgroundColor(new Color(0, 200, 200));
cell12.setRowspan(2);
//row 3
PdfPCell cell21 = new PdfPCell(new Paragraph("Cell21"));
cell21.setBackgroundColor(new Color(200, 0, 200));
table.addCell(cell00);
table.addCell(cell01);
table.addCell(cell11);
table.addCell(cell12);
table.addCell(cell21);
doc.add(table);
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
}
doc.close();
}
private static Paragraph getLongCellData() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append("Cell12_" + i);
sb.append("\n");
}
return new Paragraph(sb.toString());
}
Here the data from cell12 (which has row span of 2 and has larger data) is getting cropped at the page end and it is not being continued on next page.
Tried dividing this table into two different tables as below, but still the issue is there.
private static void tableLayout2() {
Document doc = new Document();
try {
PdfWriter.getInstance(doc, new FileOutputStream(
".\\TableLayout_2.pdf"));
doc.open();
// Table
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100f);
table.setSplitLate(false);
table.setWidths(new int[]{1, 2});
//Inner table for column 1
PdfPTable column1Table = new PdfPTable(1);
PdfPCell cell00 = new PdfPCell(new Paragraph("Cell00"));
cell00.setBackgroundColor(new Color(200, 0, 0));
//cell00.setRowspan(3);
column1Table.addCell(cell00);
//Inner table for column 2
PdfPTable column2Table = new PdfPTable(2);
PdfPCell cell01 = new PdfPCell(new Paragraph("Cell01"));
cell01.setBackgroundColor(new Color(0, 200, 0));
cell01.setColspan(2);
PdfPCell cell11 = new PdfPCell(new Paragraph("Cell11"));
cell11.setBackgroundColor(new Color(100, 100, 0));
PdfPCell cell12 = new PdfPCell( getLongCellData() );
cell12.setBackgroundColor(new Color(0, 200, 200));
cell12.setRowspan(2);
PdfPCell cell21 = new PdfPCell(new Paragraph("Cell21"));
cell21.setBackgroundColor(new Color(200, 0, 200));
column2Table.addCell(cell01);
column2Table.addCell(cell11);
column2Table.addCell(cell12);
column2Table.addCell(cell21);
table.addCell(column1Table);
table.addCell(column2Table);
doc.add(table);
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
}
doc.close();
}
This issue is partially resolved on iText5, but, due to some issues upgrading library is not quite possible for us, so is there any solution for this ?
With iText5 the data is not getting cropped but cells' heights are not so appropriate. For TableLayout_2_withIText5.pdf cell21 should have rendered on page3 instead of page4. For TableLayout_1_withIText5.pdf cell21 is getting extended in the margin area of Page1.
I am trying to create excel file with image in it, using apache poi. What happening is data which i filled in other cells are not appearing.
ApachePOIImageDemo.java
public class ApachePOIImageDemo {
public static void main(String[] args) {
System.out.println("------------ Start Main()-------------!");
try {
List<Car> carList = new ArrayList<Car>();
Car car1 = new Car("white","GJ01OP1324","/home/vivek/1.jpg","White Maruthi 800");
Car car2 = new Car("Black","GJ01OP1244","/home/vivek/1.jpg","Black Mercedes");
Car car3 = new Car("Red","GJ01OP244","/home/vivek/1.jpg","Red Toyota Innova");
Car car4 = new Car("Blue","MH01OP1224","/home/vivek/1.jpg","Blue Renault Datson");
carList.add(car1);
carList.add(car2);
carList.add(car3);
carList.add(car4);
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("My Sample Excel");
CreationHelper creationHelper = workbook.getCreationHelper();
int index = 0;
for (Car carInstance : carList){
int columnNumber = 0;
Row row = sheet.createRow(index);
Cell cell0 = row.createCell(columnNumber++);
cell0.setCellValue(index);
Cell cell1 = row.createCell(columnNumber++);
cell1.setCellValue(carInstance.getCarColor());
Cell cell2 = row.createCell(columnNumber++);
cell2.setCellValue(carInstance.getCarPlateNumber());
InputStream inputStream = new FileInputStream(carInstance.getCarImage());
byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
inputStream.close();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = creationHelper.createClientAnchor();
anchor.setCol1(3);
anchor.setRow1(index);
anchor.setCol2(4);
anchor.setRow2(index+1);
Picture picture = drawing.createPicture(anchor, pictureIdx);
columnNumber++;
Cell cell4 = row.createCell(columnNumber++);
cell4.setCellValue(carInstance.getDescription());
index++;
}
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("myFile.xlsx");
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("------------ End Main() -------------!");
}
}
My Result :
Click here
I want to set auto height and width of the columns.
My images are of different sizes in practical. So I need to set auto height-width in my file.
Thank you in advance.
You can autosize your column, like this :
sheet.autoSizeColumn(numberOfYourCOlumnWithImage);
I have table with 30 rows and array list full of strings.Table has 2 columns, in first is like company name , in second i need to write Strings from list, each row of that second column should have 10 elements, How do I do that ?
PDF Output should be something like this :
Company name |||| DESTINATION
AirFrance |||| Tokio,London,Istanbul,New Nork,Paris,Vienna,OSLO,Belgrade,Budapest,Amsterdam.
Each company should read 10 destination from list.
It's probably something easy that I just can't see I tried to count list elements and somehow partition it but it didn't work.
By the way i use itextpdf library and i read those data from excel.
Here is code :
public class ReadExcel {
private String inputfile;
private List<Avio> avioni;
public ReadExcel() {
this.avioni = new ArrayList<Avio>();
}
public List<Avio> getAvioni() {
return avioni;
}
public void setAvioni(List<Avio> avioni) {
this.avioni = avioni;
}
public String getInputfile() {
return inputfile;
}
public void setInputfile(String inputfile) {
this.inputfile = inputfile;
}
public void citaj(String naziv) {
Avio a = new Avio();
try {
Workbook w = Workbook.getWorkbook(new File(naziv));
Sheet sheet = w.getSheet(0);
// System.out.println(sheet.getRows());
for (int i = 1; i < sheet.getRows(); i++) {
Avio tmpAvio = new Avio();
tmpAvio.setDrzava(sheet.getCell(0, i).getContents());
System.out.println();
tmpAvio.setNazivKomp(sheet.getCell(1, i).getContents());
tmpAvio.setVlasnik(sheet.getCell(2, i).getContents());
tmpAvio.setBrAviona(Integer.parseInt(sheet.getCell(3, i)
.getContents()));
tmpAvio.setGod(Integer.parseInt(sheet.getCell(4, i)
.getContents()));
tmpAvio.setDatum(sheet.getCell(6,i).getContents());
tmpAvio.setModelAviona(sheet.getCell(7,i).getContents());
tmpAvio.setKapetan(sheet.getCell(8,i).getContents());
tmpAvio.setJMBG(sheet.getCell(9,i).getContents());
tmpAvio.setIskustvo(sheet.getCell(10,i).getContents());
tmpAvio.setBrPutnika(sheet.getCell(11,i).getContents());
tmpAvio.setLet(sheet.getCell(12,i).getContents());
avioni.add(tmpAvio);
}
Sheet sheet1 = w.getSheet(1);
List<String> destinacije = new ArrayList<String>();
for (int i = 0; i < sheet1.getRows(); i++) {
for (int j = 0; j < sheet1.getColumns(); j++) {
destinacije.add(sheet1.getCell(j, i).getContents());
System.out.println(sheet1.getCell(j,i).getContents()+i+","+j);
}
avioni.get(i).setDestinacije(destinacije);
System.out.println(avioni.get(i));
}
}
catch (BiffException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void kreirajPDF(String naziv) {
Document d = new Document();
try {
PdfWriter.getInstance(d, new FileOutputStream(new File(naziv)));
d.open();
File fontFile = new File("swansea.ttf");
BaseFont unicode = BaseFont.createFont(fontFile.getAbsolutePath(),
BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font titleFont = new Font(unicode, 16, Font.BOLD);
titleFont.setColor(BaseColor.WHITE);
Font textFont = new Font(unicode, 11, Font.NORMAL);
Font headerFont = new Font(unicode, 14, Font.BOLD);
Paragraph p1 = new Paragraph("Evropske Avio Kompanije", titleFont);
p1.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
Image img = Image.getInstance("lufthansa2.jpg");
img.setAlignment(Image.MIDDLE |Image.TEXTWRAP);
p1.add(img);
d.add(p1);
//d.add(new Paragraph("DESTINACIJE"));
Paragraph p2 = new Paragraph("Destinacije", titleFont);
p2.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
d.add(p2);
d.add(new Paragraph(" "));
Paragraph p3 = new Paragraph("Piloti", titleFont);
p3.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
d.add(p3);
kreiranjeTabele(d, textFont, headerFont, "Pilot");
d.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void kreiranjeTabele(Document d, Font textFont, Font headerFont,
String smjer) throws DocumentException {
PdfPTable table = new PdfPTable(5);
PdfPCell c1 = new PdfPCell(new Phrase("Drzava", headerFont));
table.addCell(c1);
PdfPCell c2 = new PdfPCell(new Phrase("Kompanija", headerFont));
table.addCell(c2);
PdfPCell c3 = new PdfPCell(new Phrase("Vlasnik", headerFont));
table.addCell(c3);
PdfPCell c4 = new PdfPCell(new Phrase("Broj Aviona", headerFont));
table.addCell(c4);
PdfPCell c5 = new PdfPCell(new Phrase("Godina", headerFont));
table.addCell(c5);
for (Avio s : avioni) {
table.setWidthPercentage(110);
// Paragraph p1 = new Paragraph(s.toString(),
// textFont);Integer.toString(i)
table.addCell(new Phrase(s.getDrzava(), textFont));
table.addCell(new Phrase(s.getNazivKomp(), textFont));
table.addCell(new Phrase(s.getVlasnik(), textFont));
table.addCell(new Phrase(Integer.toString(s.getBrAviona()),
textFont));
table.addCell(new Phrase(Integer.toString(s.getGod()), textFont));
}
PdfPTable table1 = new PdfPTable(5);
PdfPCell c11 = new PdfPCell(new Phrase("Kompanija", headerFont));
table1.addCell(c11);
PdfPCell c22 = new PdfPCell(new Phrase("Avion", headerFont));
table1.addCell(c22);
PdfPCell c33 = new PdfPCell(new Phrase("Datum", headerFont));
table1.addCell(c33);
PdfPCell c44 = new PdfPCell(new Phrase("Destinacija", headerFont));
table1.addCell(c44);
PdfPCell c55 = new PdfPCell(new Phrase("Trajanje leta", headerFont));
table1.addCell(c55);
for (Avio s1 : avioni) {
table1.setWidthPercentage(110);
table1.addCell(new Phrase(s1.getNazivKomp(), textFont));
table1.addCell(new Phrase(s1.getModelAviona(), textFont));
table1.addCell(new Phrase(s1.getDatum(), textFont));
// table1.addCell(new Phrase(s1.getDestinacije(), textFont));
table1.addCell(new Phrase(s1.getLet(), textFont));
}
PdfPTable table2 = new PdfPTable(5);
PdfPCell c111 = new PdfPCell(new Phrase("Pilot", headerFont));
table2.addCell(c111);
PdfPCell c222 = new PdfPCell(new Phrase("Drzava", headerFont));
table2.addCell(c222);
PdfPCell c333 = new PdfPCell(new Phrase("JMBG", headerFont));
table2.addCell(c333);
PdfPCell c444 = new PdfPCell(new Phrase("Iskustvo", headerFont));
table2.addCell(c444);
PdfPCell c555 = new PdfPCell(new Phrase("Avion", headerFont));
table2.addCell(c555);
for (Avio s2 : avioni) {
table2.setWidthPercentage(110);
table2.addCell(new Phrase(s2.getKapetan(), textFont));
table2.addCell(new Phrase(s2.getDrzava(), textFont));
table2.addCell(new Phrase(s2.getJMBG(), textFont));
table2.addCell(new Phrase(s2.getIskustvo(), textFont));
table2.addCell(new Phrase(s2.getModelAviona(), textFont));
}
d.add(table);
d.newPage();
d.add(table1);
d.newPage();
d.add(table2);
}
Hope someone can help. Thanks in advance.
I have an image and some text below the image in an excel sheet. when i am applying autoSizeColumn() to the column where text present the image is also getting streched .
i am also setting the anchortype to 2 but this is not protecting the image to resize.
I am posting some sample code here.
public static void main(String[] args) {
try{
XSSFWorkbook book = new XSSFWorkbook();
XSSFSheet sheet = book.createSheet("Test Sheet");
InputStream is = new FileInputStream("D:\\RPM_Eclipse_Workspaces\\B6.9\\00POI\\Chrysanthemum.jpg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = book.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = new XSSFClientAnchor(0, 0, 1023, 255, 2,2,10,10);
//Image should not get Resized while doing Autosize
anchor.setAnchorType(ClientAnchor.DONT_MOVE_AND_RESIZE);
Picture pict = drawing.createPicture(anchor, pictureIdx);
XSSFRow row = sheet.createRow(12);
for(int i = 2 ; i < 11 ; i++){
XSSFCell cell = row.createCell(i);
cell.setCellValue("oval (although anchor's type is set to MOVE_DONT_RESIZE ). ... But the one way to ");
}
sheet.autoSizeColumn(2);
book.write(new FileOutputStream(new File("D:\\auto.xlsx")));
System.out.println("=== DONE ===");
}catch (Exception e){
}
}
POI uses TwoCellAnchors for adding pictures ... so with a bit of nasty reflections, you can add a Picture with a OneCellAnchor
In the example the drawing.createAnchor(10, 10, 110, 110, 2, 2, 0, 0) is used to position the image 10x10 from the top left corner of the cell(2,2) and scale the picture to 100x100 pixels, i.e. 110-10.
(tested with Libre Office 4.0, Excel Viewer 2010)
import java.io.*;
import java.lang.reflect.*;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;
public class Automation {
public static void main(String[] args) throws Exception {
XSSFWorkbook book = new XSSFWorkbook();
XSSFSheet sheet = book.createSheet("Test Sheet");
InputStream is = new FileInputStream("src/test/resources/smiley.jpg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = book.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(10, 10, 110, 110, 2, 2, 0, 0);
createPicture(anchor, pictureIdx, drawing);
XSSFRow row = sheet.createRow(12);
for (int i = 2; i < 11; i++) {
XSSFCell cell = row.createCell(i);
cell.setCellValue("oval (although anchor's type is set to MOVE_DONT_RESIZE ). ... But the one way to ");
}
sheet.autoSizeColumn(2);
book.write(new FileOutputStream(new File("auto.xlsx")));
}
public static XSSFPicture createPicture(XSSFClientAnchor anchor, int pictureIndex, XSSFDrawing drawing)
throws Exception
{
Method m = XSSFDrawing.class.getDeclaredMethod("addPictureReference", int.class);
m.setAccessible(true);
PackageRelationship rel = (PackageRelationship)m.invoke(drawing, (Integer)pictureIndex);
long shapeId = 1000+drawing.getCTDrawing().sizeOfOneCellAnchorArray();
CTOneCellAnchor ctAnchor = createOneCellAnchor(drawing, anchor);
CTPicture ctShape = ctAnchor.addNewPic();
m = XSSFPicture.class.getDeclaredMethod("prototype");
m.setAccessible(true);
CTPicture ctp = (CTPicture)m.invoke(null);
ctShape.set(ctp);
ctShape.getNvPicPr().getCNvPr().setId(shapeId);
Constructor<XSSFPicture> picCon = XSSFPicture.class
.getDeclaredConstructor(XSSFDrawing.class, CTPicture.class);
picCon.setAccessible(true);
XSSFPicture shape = picCon.newInstance(drawing, ctShape);
Field f = XSSFShape.class.getDeclaredField("anchor");
f.setAccessible(true);
f.set(shape, anchor);
m = XSSFPicture.class.getDeclaredMethod("setPictureReference", PackageRelationship.class);
m.setAccessible(true);
m.invoke(shape, rel);
return shape;
}
public static CTOneCellAnchor createOneCellAnchor(XSSFDrawing drawing, XSSFClientAnchor anchor) {
final int pixel2emu = 12700;
CTOneCellAnchor ctAnchor = drawing.getCTDrawing().addNewOneCellAnchor();
long cx = (anchor.getTo().getRowOff()-anchor.getFrom().getRowOff())*pixel2emu;
long cy = (anchor.getTo().getColOff()-anchor.getFrom().getColOff())*pixel2emu;
CTPositiveSize2D size = CTPositiveSize2D.Factory.newInstance();
size.setCx(cx);
size.setCy(cy);
ctAnchor.setExt(size);
ctAnchor.setFrom(anchor.getFrom());
CTMarker m = ctAnchor.getFrom();
m.setColOff(m.getColOff()*pixel2emu);
m.setRowOff(m.getRowOff()*pixel2emu);
ctAnchor.addNewClientData();
try {
Method mt = XSSFClientAnchor.class.getDeclaredMethod("setFrom", CTMarker.class);
mt.setAccessible(true);
mt.invoke(anchor, ctAnchor.getFrom());
} catch (Exception e) {
throw new RuntimeException("handle me", e);
}
return ctAnchor;
}
}
In picture.resize () method, to calculate the original height of the image, it use the row.getHeight value.
The problem is, the row height value !
Depending on the contents of the cell, the row height is increased automatically, but you cannot obtain the increased height value by row.getHeight() method.
So, you need to set the height of row using row.setHeigth (height) manually.
then you can be obtained for the normal image size and the picture.resize () method will work properly.