How to create a itext table having cells at user specified positions - itext7

I have a requirement to add images in an iText PDF table, but the position of cells (consisting of images) will depend on indexes (row and column number) given by the user. This table could also have empty cells in between if no index for any image is given.
How to add a cell in itext pdf at random position?
I looked out for this at various forums, not successful. I would really appriciate the help.

There is no API in iText's Table class to add a cell to an arbitrary position. The reasoning behind such a decision lies in iText's Table architecture: if a table has not been constructed yet (i.e. it's unknown whether there will be some cells with a rowpan and/or a colpan greater than 1), it's not feasible for iText to know whether it could place a cell at some custom position.
However, the good news is that all the layout-related code is triggered only after the table is added to the document. So, one can always do the following:
create a table
fill it with some presaved empty Cell objects
alter some Cell object as requested
add the table to the document
In the snippet above I will show, hot to add some diagonal content to the table after the cells have been added to it. The same approach could be followed for images.
int numberOfRows = 3;
int numberOfColumns = 3;
Table table = new Table(numberOfColumns);
List<List<Cell>> cells = new ArrayList<>();
for (int i = 0; i < numberOfRows; i++) {
List<Cell> row = new ArrayList<>();
for (int j = 0; j < numberOfColumns; j++) {
Cell cell = new Cell();
row.add(cell);
table.addCell(cell);
}
cells.add(row);
}
// Add some text diagonally
cells.get(0).get(0).add(new Paragraph("Hello"));
cells.get(1).get(1).add(new Paragraph("diagonal"));
cells.get(2).get(2).add(new Paragraph("world!"));
The resultant PDF looks as follows:

Related

iText7: How to use table.flush() and set a very wide page

I'm using iText7 (7.2.3) to generate PDF documents with wide tables. I need the table to completely appear on the page. These documents also contains tens of thousands of rows so, ideally, I'd like to be able to use a low memory footprint using table.flush() (see https://kb.itextpdf.com/home/it7kb/examples/large-tables).
Here's my actual code that works:
// At this point table contains all the table data
Text Title = new Text("Report Title")
.SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD));
Paragraph p1 = new Paragraph(Title).SetMargin(0);
table.SetBorderCollapse(BorderCollapsePropertyValue.SEPARATE);
table.SetNextRenderer(new CustomBorderTableRenderer(table));
PdfDocument pdfDoc = new(new PdfWriter(Filename));
Document doc = new(pdfDoc);
// calculate maximum width of document based on table width
float necessaryWidth = 523f;
IRenderer tableRenderer = table.CreateRendererSubTree().SetParent(doc.GetRenderer());
LayoutResult tableLayoutResult = tableRenderer.Layout(new LayoutContext(new LayoutArea(0, new Rectangle(necessaryWidth, 1000))));
float tableHeightTotal = tableLayoutResult.GetOccupiedArea().GetBBox().GetHeight();
float tableWidthTotal = tableLayoutResult.GetOccupiedArea().GetBBox().GetWidth();
// regenerate document with updated width
doc = new(pdfDoc, new iText.Kernel.Geom.PageSize(tableWidthTotal, 1024));
doc.Add(p1);
doc.Add(table);
doc.Close();
It's a bit dirty because I first get all the table data (which can take a lot of memory) then check the table width inside the document and regenerate a new page with updated width. Only after that can I insert the table data in the page.
I feel it's kind of the chicken or the egg problem: if I know the page width in advance no problem I can use table.flush() but in order to get the table width I need to fill all the table first.
I think my best bet is to update the page width after all rows are inserted but I could not find a way to do this.
Anyone has a suggestion?

Itext7 - How to create pdf with 2 columns and 4 rows per page with images in java

I have following code to create a single pdf with 2 columns and 4 rows. Every cell contains an image.
int labelCount = x;
int columns = 2;
int labelsPerPage = 8;
int rows = labelCount/columns;
int resto = labelCount%columns;
if(resto>0) rows++;
String dest = "path_to_pdf_file";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
doc.setMargins(0, 0, 0, 0);
Table table = new Table(UnitValue.createPercentArray(columns)).useAllAvailableWidth();
Integer iCount = 0;
for (int i = 1; i <= rows; i++) {
for (int y = 1; y <= columns; y++) {
if(iCount<labelCount) {
String fileName = "name_of_image";
Cell cell = new Cell();
cell.add(new com.itextpdf.layout.element.Image(ImageDataFactory.create("full_path_to_image")).setAutoScale(true));
cell.setBorder(Border.NO_BORDER);
table.addCell(cell);
iCount++;
if(iCount==labelsPerPage-1) {
doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
}
}
}
}
doc.add(table);
doc.close();
If number of labels is bigger than defined limit (8 per page), I want a new page to be created with the following labels.
In my code I used
doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
but it generate (I don't know why) a blank page at the beginning. In the second page there are labels.
Which is the right way to add a new page dynamically and put remaining content into it?
Thanks
Essentially in your code you add AreaBreak to the document before you add the table, that's why the blank page is inserted before the table. iText 7 does not allow you to insert page breaks within tables at this point.
To achieve the desired result you need to flush the existing table to the document before moving on to the next page, and create a new table for the next page. Essentially you will be adding a bunch of tables separated with AreaBreak.
The pseudocode which does not require a lot of modifications to your code could look as follows:
Table table = new Table();
for (...) {
// populate table
if ("it's time to insert a page break") {
doc.add(table);
doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
table = new Table(); // create new table
}
}
doc.add(table);

GetColumn Information and Width on Resize - Slick Grid

Am working on slick grid where am trying to get the column information like id,name and the new width of column after resize.
I wrote an event which will be triggered when user resizes the column.
grid.onColumnsResized.subscribe(function (e, args) {
//To Do
});
grid.getColumns() will help but how do i identify which column user has resized. is there a way I can get the column index of the resized column?
some start up code from here will save lot of my time
Thanks
The onColumnsResized event triggered by SlickGrid doesn't include any references to the columns which changed.
It's important to note that the width of multiple columns may have changed when this event triggers. Examples of this are:
Using the grid option forceFitColumns: true to force the columns to fit in the width of the grid
Resizing a column so small it affects the columns to its left
Two possible options for implementing this are:
Check columns after change
SlickGrid stores the previous column widths in the property named previousWidth on each column. You can compare the prevoiusWidth and width values to determine which columns changed.
grid.onColumnsResized.subscribe(function (e, args) {
//Loop through columns
for(var i = 0, totI = grid.getColumns().length; i < totI; i++){
var column = grid.getColumns()[i];
//Check if column width has changed
if (column.width != column.previousWidth){
//Found a changed column - there may be multiple so all columns must be checked
console.log('Changed column index : ' + i);
console.log(column);
}
}
});
SlickGrid resets the previousWidth values for all columns whenever a column starts being resized.
You can view an example of this approach at http://plnkr.co/edit/W42pBa2ktWKGtqNtQzii?p=preview.
Modifying SlickGrid
If you are hosting SlickGrid and are comfortable maintaining your own version then you could modify it to include column information in the args of the onColumnsResized event.
In slick.grid.js at line 860 amend the code where the event is triggered to include an array containing the indexes of changed columns. You can also include the index of the column which the user resized if this is useful. The below adds properties named changedColumnIndexes and triggeredByColumnIndex which are passed in the args of the triggered event. I've wrapped the changes for this in comments prefixed //MODIFICATION.
.bind("dragend", function (e, dd) {
var newWidth;
//MODIFICATION - Add array to capture changed column indexes and variable to capture
// the index of the column which triggered the change
var changedColumnIndexes = [];
var triggeredByColumnIndex = getColumnIndex($(this).parent()[0].id.replace(uid, ""));
//MODIFICATION END
$(this).parent().removeClass("slick-header-column-active");
for (j = 0; j < columnElements.length; j++) {
c = columns[j];
newWidth = $(columnElements[j]).outerWidth();
//MODIFICATION - Add column index to array if changed
if (c.previousWidth !== newWidth) {
changedColumnIndexes.push(j);
}
//MODIFICATION END
if (c.previousWidth !== newWidth && c.rerenderOnResize) {
invalidateAllRows();
}
}
updateCanvasWidth(true);
render();
//MODIFICATION - Amend trigger for event to include array and triggeredBy column
trigger(self.onColumnsResized, {changedColumnIndexes: changedColumnIndexes, triggeredByColumnIndex: triggeredByColumnIndex});
//MODIFICATION END
});
In your own code subscribe to the onColumnsResized event and pickup the changed column index from the args of the event.
grid.onColumnsResized.subscribe(function(e, args) {
//Triggered by column is passed in args.triggeredByColumnIndex
console.log('Change triggered by column in index : ' + args.triggeredByColumnIndex);
console.log(grid.getColumns()[args.triggeredByColumnIndex]);
//Column array is passed in args.changedColumnIndexes
console.log('Changed columns are...');
console.log(args.changedColumnIndexes);
//Loop through changed columns if necessary
for (var i = 0, totI = args.changedColumnIndexes.length; i < totI; i++){
console.log(grid.getColumns()[args.changedColumnIndexes[i]]);
}
});
You can view an example of this approach at http://plnkr.co/edit/4K6wRtTqSo12SE6WdKFk?p=preview.
Determining column changes by column.width != column.previousWidth wasn't working for me because sometimes the original and new width were different by an insignificant size (e.g. 125.001 and 125).
I used Chris C's logic and made a PR on the 6pac/SlickGrid project. Here's the commit:
https://github.com/6pac/SlickGrid/commit/ba525c8c50baf18d90c7db9eaa3f972b040e0a6e

Find&Replace script in Google Docs SpreadSheets

I have google spreadsheet with direct links to images (jpg and png):
https://docs.google.com/spreadsheet/ccc?key=0AoPGWppcjtzhdDh6MW1QNVJhSHlwVTlfRnRtd0pvNGc&usp=sharing
I want to increase rows heights starting from "2nd row" to 100px and render images there.
It's possible to do via Find&Replace:
Find jpg and Replace to jpg", 1)
Find http://img and Replace to =image("http://img)
Select rows and Scale them
and the same for png image-urls.
Watch this screencast http://www.screenr.com/S0RH
Is it possible to automate it via script? I think - YES! It have to be pretty simple but I googled a lot but haven't found the solution. I can't do it myself as don't know coding. Will anyone help and make this script?
A function to do what you ask is simple, if you have a basic understanding of the language (Javascript), know how to use the development environment, and read the API documentation.
For example, see this script. It's been added to your shared spreadsheet, so you can also view it (and run it) in the script editor there.
/**
* Scan column A, looking for images that have been inserted using
* =image() function. For any row with an image, set the row height
* to 100 pixels.
*/
function resizeImageRows() {
var sheet = SpreadsheetApp.getActiveSheet(); // Get a handle on the sheet
var HEADERS = 1; // Number of header rows at top
var firstRow = HEADERS + 1; // First row with data
var lastRow = sheet.getLastRow(); // Last row with data
var imageRange = sheet.getRange(1, 1, lastRow, 1); // Column A
// Get all formulas from Column A, without Headers
var formulas = imageRange.getFormulas().slice(HEADERS);
// Look for image() formulas, and set the row height.
for (var i = 0; i< formulas.length; i++) {
if (formulas[i][0].indexOf('image') !== -1) {
sheet.setRowHeight(i+firstRow, 100); // Set height to 100 pixels
}
}
}
You can absolutely do this with the find and replace function under the edit menu, just make sure you click "search in formulas" and it will find and replace in the formula.

Google charts column filtering

I am trying to filter a Google line chart columns and using the code shared here in Google Charts-Code for Category Filter
It all works well however I have a number of columns and would like to have the chart start with just one column displayed and allow the user to add in any of the additional columns as needed.
What I've found is that if I play with the initState variable to set it to the one column I want to display initially, it will have that column shown in the selector section but still displays all the columns initially until I select an additional column when it hides the rest and just displays the two I have selected.
So then I tried turning off this part of the code:
// put the columns into this data table (skip column 0)<br>
for (var i = 1; i < data.getNumberOfColumns(); i++) {
columnsTable.addRow([i, data.getColumnLabel(i)]);
initState.selectedValues.push(data.getColumnLabel(i));
}
and replacing it with
columnsTable.addRow([1, data.getColumnLabel(16)]);
initState.selectedValues.push(data.getColumnLabel(16));
which sets the column i'm after (column 16) as the selected column in the selection list but removes the other columns from the list of available columns and still displays all 16 columns.
How can I set this up so it displays the single selected column's data initially yet still gives the ability to pick other columns from the selector?
You want to keep the columnstable.addRow call inside the for loop, as it populates the DataTable used to provide the list of columns. You can set the selectedValue variable as you have it:
// put the columns into this data table (skip column 0)<br>
for (var i = 1; i < data.getNumberOfColumns(); i++) {
columnsTable.addRow([i, data.getColumnLabel(i)]);
}
initState.selectedValues.push(data.getColumnLabel(16));
In order to make the chart draw properly with the initial selection, we need to make a small adjustment to the structure, putting all of the updating code into its own function, and then calling that as necessary:
function setChartView () {
var state = columnFilter.getState();
var row;
var view = {
columns: [0]
};
for (var i = 0; i < state.selectedValues.length; i++) {
row = columnsTable.getFilteredRows([{column: 1, value: state.selectedValues[i]}])[0];
view.columns.push(columnsTable.getValue(row, 0));
}
// sort the indices into their original order
view.columns.sort(function (a, b) {
return (a - b);
});
chart.setView(view);
chart.draw();
}
google.visualization.events.addListener(columnFilter, 'statechange', setChartView);
setChartView();
Here's a working example: http://jsfiddle.net/asgallant/WaUu2/157/.

Resources