I am using itext 5 legacy for the first time and I am new to app development.
I am generating a table that keeps splitting the columns into new rows on a new page and it would repeat the data.
The first Table:
The second table with split columns and repeating data:
Third table:
The fourth table:
The fifth Table:
The table is required to be one long row.
Please help me rectify this,
Here is the code:
private void createPdf() throws FileNotFoundException, DocumentException,IOException {
// getIntent().setType("application/pdf");
Toast.makeText(this,"GENERATING PDF ..."+ directory_path,Toast.LENGTH_LONG).show();
File file = new File(directory_path+filename);
if (!file.exists())
{
file.mkdirs();
}
ProductCondition prodCond = new ProductCondition(true,"GREEN","BFobrourinbiurfufbjfnbbu");
ProductOperations prodOper = new ProductOperations(true,true,true,1000,986,500,"OBNobdfiuvdob");
Product product = new Product("bkbukb","sfdvsf","sdfsdfs","1sfdssV45",prodCond,prodOper);
technicians.addProduct(product);
Document document = new Document(PageSize.A1.rotate());
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(directory_path+filename));
document.open();
PdfPTable table = new PdfPTable(15);
table.setTotalWidth(5000);
table.setWidthPercentage(100);
List<String> listData =new ArrayList<>() ;
listData = GetTechnicianData(technicians);
Image image1 = GetImage();
Image image2 = GetImage();
table.addCell("Bloop");
table.addCell("han Solo");
table.addCell("Hamburger");
table.addCell("NUmber time");
table.addCell("boogaloo");
table.addCell("Boo thang");
table.addCell("Spanish");
table.addCell("Inquisition");
table.addCell("Never ");
table.addCell("Death");
table.addCell("Test ");
// table.addCell("Button");
table.addCell("Lights");
table.addCell("Sunshine");
table.addCell("Comment");
table.addCell("Images");
table.setHeaderRows(3);
table.setFooterRows(1);
table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
PdfPCell cell;
Toast.makeText(this,"ADDING PRELIMINARY DATA",Toast.LENGTH_LONG).show();
for (int c = 0; c < 14; c++) {
cell = new PdfPCell();
cell.setFixedHeight(50);
cell.addElement(new Paragraph(listData.get(c)));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
//cell.setBorder(PdfPCell.NO_BORDER);
table.addCell(cell);
table.setKeepTogether(true);
}
Paragraph p = new Paragraph();
p.add(new Chunk(image1,0,0,true));
p.add(new Chunk(image2,0,0,true));
cell = new PdfPCell();
cell.addElement(p);
//cell.setBorder(PdfPCell.NO_BORDER);
table.addCell(cell);
//document.add(table);
Toast.makeText(this,"ADDING IMAGES...",Toast.LENGTH_LONG).show();
/* cell = new PdfPCell();
Paragraph p = new Paragraph();
p.add(new Chunk(image1,0,0,true));
p.add(new Chunk(image1,0,0,true));
cell.addElement(p);
table.addCell(cell);*/
// document.add(table);
PdfContentByte canvas = writer.getDirectContent();
PdfTemplate tableTemplate = canvas.createTemplate(5000, 2600);
table.writeSelectedRows(0, -1, 0, 800, tableTemplate);
PdfTemplate clip;
for (int j = 0; j <5000; j += 1000) {
table.setKeepTogether(true);
document.newPage();
for (int i = 2600; i > 0; i -= 1300) {
clip = canvas.createTemplate(2000, 1300);
clip.addTemplate(tableTemplate, -j, 1750 - i);
canvas.addTemplate(clip, 50, 312);
table.setKeepTogether(true);
//canvas.addImage(image1);
}
}
// byte [] pdf = Files.readAllBytes(file.toPath());
Uri filepdf = Uri.fromFile(new File(directory_path+filename));
UploadTask uploadTask = storageReference.child(technicians.getEmailAddress()).child("PDFUpdate").putFile(filepdf);
Toast.makeText(this,"PDF Generated Successfully",Toast.LENGTH_LONG).show();
document.close();
/* PackageManager packageManager = context.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
context.startActivity(intent);
} else {
Toast.makeText(context, "Download a PDF Viewer to see the generated PDF", Toast.LENGTH_SHORT).show();
}
*/
}
private void createPdfWrapper() throws FileNotFoundException, DocumentException ,IOException{
int hasWriteStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showMessageOKCancel("You need to allow access to Storage",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(CentralHome.this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
}
});
return;
}
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
return;
}
} else {
createPdf();
}
}
private Image GetImage() throws BadElementException,IOException{
Drawable d = getResources().getDrawable(R.drawable.logo);
BitmapDrawable bitDw = ((BitmapDrawable) d);
Bitmap bmp = bitDw.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
image.scalePercent(10);
return image;
// document.add(image);
}
}
In createPdf you have a loop that adds sections of the template with the whole table to separate pages:
for (int j = 0; j <5000; j += 1000) {
table.setKeepTogether(true);
document.newPage();
for (int i = 2600; i > 0; i -= 1300) {
clip = canvas.createTemplate(2000, 1300);
clip.addTemplate(tableTemplate, -j, 1750 - i);
canvas.addTemplate(clip, 50, 312);
table.setKeepTogether(true);
//canvas.addImage(image1);
}
}
Each section is 2000 units wide (canvas.createTemplate(2000, 1300)) but when advancing to the next section you only go right by 1000 units (j += 1000). Thus, each new section (except the first one) repeats the last three columns (the second half) of the previous section.
You can prevent these repetitions by going right by 2000 units after each section, i.e. by replacing
for (int j = 0; j <5000; j += 1000)
by
for (int j = 0; j <5000; j += 2000)
As an aside, there are numerous other weirdnesses in your code, e.g.
table.setHeaderRows(3);
table.setFooterRows(1);
(here you declare that you have three header rows and one footer row to repeat automatically if the table is added to the Document directly and split over multiple pages; as you don't add the table to the Document but manually to a template, that functionality is not used which is fortunate as you only create enough cells to fill two rows, not even enough for the declared header rows)
and multiple calls of
table.setKeepTogether(true)
after already having rendered the table in
table.writeSelectedRows(0, -1, 0, 800, tableTemplate)
After rendering the table it is too late to set properties controlling the rendering process...
In a comment you said that you only wanted to have a normal 15 column table, not one whose columns are spread across multiple pages. In that case why don't you simply do
Document document = new Document(PageSize.A1.rotate());
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(directory_path+filename));
document.open();
PdfPTable table = new PdfPTable(15);
table.setWidthPercentage(100);
... create cells and add them to the table ...
document.add(table);
document.close();
All the usage of PdfContentByte, PdfTemplate, and writeSelectedRows is completely unnecessary for your use case.
Related
I can set diferent setFixedLeading on specific page.
First i add All paragraphs in list then with help recursive i calculate e height of each paragraph and compare with document height, then i add it to div.
But it dont work.
Maybe there is another way?
public static void main(String[] args) throws FileNotFoundException {
PdfDocument pdf = new PdfDocument(new PdfWriter(DEST));
Document document = new Document(pdf);
pdf.setDefaultPageSize(PageSize.A5);
float bottomMarin = 0;
document.setMargins(0, 25, bottomMarin, 25);
Div div = new Div();
div.setPadding(0);
div.setMargin(0);
maxHeight = document.getPdfDocument().getDefaultPageSize().getHeight()- bottomMarin ;/* (mainPdf_model.getLeftMargin() +mainPdf_model.getRightMargin());*/
String line = "Hello! Welcome to iTextPdf";
List<Paragraph> paragraphs = new ArrayList<>();
for (int i = 0; i < 130; i++) {
Paragraph element = new Paragraph();
element.add(line + " " + i);
element.setMargin(0);
element.setPadding(0);
element.setFixedLeading(100);
paragraphs.add(element);
}
getListParagraphOnPage(paragraphs, document, 1);
Map<Integer, List<Paragraph>> listParagraphOnPage = paragraph;
listParagraphOnPage.forEach((k,v)->{
if(k ==1){
for(Paragraph paragraph : v){
paragraph.setFixedLeading(120);
paragraph.setBackgroundColor(red);
div.add(paragraph);
}
}
if(k ==2){
for(Paragraph paragraph : v){
paragraph.setFixedLeading(150);
paragraph.setBackgroundColor(yellow);
div.add(paragraph);
}
}
if(k ==3){
for(Paragraph paragraph : v){
paragraph.setFixedLeading(30);
paragraph.setBackgroundColor(green);
div.add(paragraph);
}
}
});
Map<Integer, List<Paragraph>> paragraph = new HashMap<>();
document.add(div);
document.close();
}
static Map<Integer,List<Paragraph>> paragraph = new HashMap<>();
//This is a method that is created in the map, in which paragraphs are placed with a certain Leading
public static Map<Integer,List<Paragraph>> getListParagraphOnPage(List<Paragraph> paragraphs, Document document,int page){
float height = 0;
List<Paragraph> ps = new ArrayList<>();
for(Paragraph par: paragraphs){
if(page==1){
par.setFixedLeading(120);
}else if(page==2){
par.setFixedLeading(150);
}else if(page==3){
par.setFixedLeading(30);
}
IRenderer rendererSubTree = par.createRendererSubTree();
LayoutResult result = rendererSubTree.setParent(document.getRenderer()).
layout(new LayoutContext(new LayoutArea(1, new Rectangle(10000, 1000))));
height+=result.getOccupiedArea().getBBox().getHeight();
if(height<maxHeight){
ps.add(par);
}else {
var pageCurrent = page;
paragraph.put(page,ps);
int size = paragraph.get(pageCurrent).size();
page++;
return getListParagraphOnPage(paragraphs.subList(size,paragraphs.size()),document,page);
}
}
return paragraph;
}
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();
I have sucessfully generated the table of contents but how to add respective page numbers. I am using the RtfWriter2 of iText to create documents.
I have tried below code to add table of contents but no luck.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document doc = new Document();
RtfWriter2 writer2 = RtfWriter2.getInstance(doc, baos);
try {
writer2.setAutogenerateTOCEntries(true);
Table headerTable = new Table(3);
headerTable.addCell("Test Cell 1");
headerTable.addCell("Test Cell 2");
headerTable.addCell("Test Cell 3");
HeaderFooter header = new RtfHeaderFooter(headerTable);
RtfHeaderFooterGroup footer = new RtfHeaderFooterGroup();
doc.open();
Paragraph p = new Paragraph();
p.add(new RtfTableOfContents("UPDATE ME!"));
doc.add(p);
p = new Paragraph("", new RtfFont("Staccato222 BT"));
p.add(new Chunk("Hello! "));
p.add(new Chunk("How do you do?"));
doc.add(p);
p.setAlignment(Element.ALIGN_RIGHT);
doc.add(p);
Chunk c = new Chunk("");
c.setNewPage();
doc.add(c);
for (int i = 0; i < 300; i++) {
doc.add(new Paragraph( "Dummy line to get multi-page document. Line " + (i + 1)));
}
} catch (Exception e) {
e.printStackTrace();
}
doc.close();
return baos;
Below is the output I am trying for:
Table of contents
History 1
Intro 2
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);
}
New here so please be kind. I've spent a few hours trawling through posts trying to find an answer but no such luck.
I have an excel file that I import into a JTable and can then edit. Add columns, rows etc.
When I click the button to add a column or row they appear on the JTable as expected. However when I click the save button to save the file it hasn't added the new columns or rows to the Excel file.
I thought my save wasn't working correctly, but if I edit one of the two columns I already have saved in the Excel file the changes are saved to the Excel file so I am confused as to why I can edit the existing data in the file but any new rows or columns are not saved.
My export to excel is:
public void toExcel()
{
try
{
FileInputStream fsIP = new FileInputStream(new File("Recipes.xls"));
HSSFWorkbook fWorkbook = new HSSFWorkbook(fsIP);
HSSFSheet fSheet = fWorkbook.getSheet("RECIPES");
HSSFFont sheetTitleFont = fWorkbook.createFont();
HSSFCellStyle cellStyle = fWorkbook.createCellStyle();
sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
TableColumnModel tcm = tables.getColumnModel();
HSSFRow fRow = fSheet.createRow((short) 0);
for(int j = 0; j < tcm.getColumnCount(); j++)
{
HSSFCell cell = fRow.createCell((int) j);
cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());
}
for (int i = 0, row = 1; i < models.getRowCount(); i++, row++)
{
HSSFRow fRow1 = fSheet.createRow((short) row);
for (int j = 0; j < models.getColumnCount(); j++)
{
HSSFCell cell = fRow1.createCell((int) j);
cell.setCellValue(models.getValueAt(i, j).toString());
cell.setCellStyle(cellStyle);
}
}
FileOutputStream output_file = new FileOutputStream(new File("Recipes.xls"));
BufferedOutputStream bos = new BufferedOutputStream(output_file);
fWorkbook.write(output_file);
fWorkbook.close();
bos.close();
output_file.close();
}
catch(Exception e)
{
}
JOptionPane.showMessageDialog(
null, "Changes Saved",
"Confirmation",
JOptionPane.INFORMATION_MESSAGE);
}
My method for adding a column is as follows:
public void addNewRecipe()
{
models.addColumn(JOptionPane.showInputDialog("Enter A Description for Recipe"));
}
Thanks.
EDIT
Here is code for calling toExcel
saveButton.addActionListener(new ActionListener()
{
#Override public void actionPerformed(ActionEvent arg0)
{
{
models = new DefaultTableModel(datas, headers);
tableWidth = models.getColumnCount() * 150;
tableHeight = models.getRowCount() * 50;
tables.setPreferredSize(new Dimension( tableWidth, tableHeight));
tables.setModel(models);
tables.setRowHeight(50);
toExcel();
}
}
});