diff --git a/voila-runtime-displaytag/pom.xml b/voila-runtime-displaytag/pom.xml index 51a5b5f8702e54fefee1ef2e812b7d4e1180cfae..0bd1490fb607ef703c3578197c6c8f09626c5ee7 100644 --- a/voila-runtime-displaytag/pom.xml +++ b/voila-runtime-displaytag/pom.xml @@ -23,16 +23,21 @@ ${project.parent.version} - + + + org.apache.pdfbox + pdfbox + 2.0.31 + org.apache.poi poi diff --git a/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/AbstractPdfExporter.java b/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/AbstractPdfExporter.java index de9d98bdf932c6a9daeae414c219fd90ff9f8bef..d80b8039147b05ceffa3045020263890ba637f72 100644 --- a/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/AbstractPdfExporter.java +++ b/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/AbstractPdfExporter.java @@ -1,14 +1,13 @@ package it.mice.voila.runtime.displaytag.pdfexporter; -import it.mice.voila.runtime.displaytag.basedec.ValueDecorator; -import it.mice.voila.runtime.displaytag.exporter.AbstractTotalExporter; - -import java.awt.Color; +import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; +import java.util.List; import java.util.Map; +import java.util.ArrayList; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; @@ -16,6 +15,12 @@ import javax.servlet.jsp.PageContext; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.PDPageContentStream; +import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode; +import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.displaytag.Messages; import org.displaytag.decorator.ColumnDecorator; import org.displaytag.decorator.TotalTableDecorator; @@ -29,24 +34,8 @@ import org.displaytag.model.HeaderCell; import org.displaytag.model.Row; import org.displaytag.model.RowIterator; import org.displaytag.model.TableModel; -import org.displaytag.util.TagConstants; - -import com.itextpdf.text.BadElementException; -import com.itextpdf.text.BaseColor; -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Element; -import com.itextpdf.text.Font; -import com.itextpdf.text.FontFactory; -import com.itextpdf.text.PageSize; -import com.itextpdf.text.Paragraph; -import com.itextpdf.text.Phrase; -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.ColumnText; -import com.itextpdf.text.pdf.PdfContentByte; -import com.itextpdf.text.pdf.PdfPCell; -import com.itextpdf.text.pdf.PdfPTable; -import com.itextpdf.text.pdf.PdfWriter; + +import it.mice.voila.runtime.displaytag.exporter.AbstractTotalExporter; /** * Created by IntelliJ IDEA. @@ -89,16 +78,14 @@ public abstract class AbstractPdfExporter extends AbstractTotalExporter { */ protected boolean decorated; - /** - * This is the table, added as an Element to the PDF document. It contains all the data, needed to represent the - * visible table into the PDF - */ - protected PdfPTable tablePDF; + protected PDDocument document; + + protected PDPageContentStream contentStream; /** * The default font used in the document. */ - protected Font smallFont; + protected PDType1Font smallFont = PDType1Font.HELVETICA; /** * @see org.displaytag.export.ExportView#setParameters(org.displaytag.model.TableModel, boolean, boolean, boolean) @@ -116,15 +103,15 @@ public abstract class AbstractPdfExporter extends AbstractTotalExporter { * * @throws BadElementException for errors during table initialization */ - protected void initTable() throws BadElementException { - tablePDF = new PdfPTable(this.model.getNumberOfColumns()); - - tablePDF.setWidthPercentage(100); - tablePDF.setHeaderRows(1); - - smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL, new BaseColor(0, 0, 0)); - - super.init(this.model); + protected void initDocument(OutputStream out) throws Exception { + PDRectangle landscapeA4 = new PDRectangle(PDRectangle.A4.getHeight(), PDRectangle.A4.getWidth()); + + document = new PDDocument(); + PDPage page = new PDPage(landscapeA4); + document.addPage(page); + contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true); + contentStream.setFont(smallFont, 7); + super.init(model); } /** @@ -135,49 +122,27 @@ public abstract class AbstractPdfExporter extends AbstractTotalExporter { return "application/pdf"; //$NON-NLS-1$ } - /** - * The overall PDF table generator. - * - * @throws javax.servlet.jsp.JspException for errors during value retrieving from the table model - * @throws DecoratorException - * @throws ObjectLookupException - * @throws BadElementException IText exception - */ - protected void generatePDFTable(Document document) throws JspException, DocumentException, ObjectLookupException, DecoratorException { - if (this.header) { - generateHeaders(); - } - generateRows(document); - } /** * @throws PdfGenerationException * @see org.displaytag.export.BinaryExportView#doExport(java.io.OutputStream) */ public void doExport(OutputStream out) throws PdfGenerationException { - try { - // Initialize the table with the appropriate number of columns - initTable(); - - // Initialize the Document and register it with PdfWriter listener and the OutputStream - Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40); - PdfWriter.getInstance(document, out); - - document.addCreationDate(); - - PdfWriter writer = PdfWriter.getInstance(document, out); - document.open(); + try { + initDocument(out); - prepareHeaderFooter(writer, document); - prepareDocumentTitle(document); + prepareDocumentTitle(); + prepareHeaderFooter(); - // Fill the virtual PDF table with the necessary data - generatePDFTable(document); - document.add(this.tablePDF); - document.close(); + if (header) { + generateHeaders(); + } + generateRows(); - } - catch (Exception e) { + contentStream.close(); + document.save(out); + document.close(); + } catch (Exception e) { throw new PdfGenerationException(e); } } @@ -188,22 +153,20 @@ public abstract class AbstractPdfExporter extends AbstractTotalExporter { * @throws BadElementException IText exception */ @SuppressWarnings("unchecked") - protected void generateHeaders() throws BadElementException { + protected void generateHeaders() throws IOException { Iterator iterator = this.model.getHeaderCellList().iterator(); - + float yPosition = 520; + float xPosition = 50; + float cellWidth = (PDRectangle.A4.getHeight() - 100) / model.getNumberOfColumns(); // Dynamic cell width + float cellHeight = 10; // Height of each cell while (iterator.hasNext()) { HeaderCell headerCell = iterator.next(); - String columnHeader = headerCell.getTitle(); - if (columnHeader == null) { columnHeader = StringUtils.capitalize(headerCell.getBeanPropertyName()); } - - PdfPCell hdrCell = getCell(columnHeader); - hdrCell.setGrayFill(0.9f); - hdrCell.setHorizontalAlignment(Element.ALIGN_CENTER); - tablePDF.addCell(hdrCell); + addCell(columnHeader, xPosition, yPosition, cellWidth, cellHeight, true); + xPosition += cellWidth; } } @@ -215,89 +178,98 @@ public abstract class AbstractPdfExporter extends AbstractTotalExporter { * @throws ObjectLookupException * @throws BadElementException errors while generating content */ - protected void generateRows(Document document) throws JspException, DocumentException, ObjectLookupException, DecoratorException { + protected void generateRows() throws IOException, JspException, ObjectLookupException, DecoratorException { int rowNum = 0; - // get the correct iterator (full or partial list according to the exportFull field) + float yPosition = 510; + float xPosition; + float cellWidth = (PDRectangle.A4.getHeight() - 100) / model.getNumberOfColumns(); // Dynamic cell width + float cellHeight = 0; + float margin = 50; + float footerHeight = 30; + float usablePageHeight = yPosition - margin - footerHeight; RowIterator rowIterator = this.model.getRowIterator(this.exportFull); - // iterator on rows + int maxRowsPerPage = PDFTABLE_FRAGMENT_SIZE; while (rowIterator.hasNext()) { - if (rowNum % PDFTABLE_FRAGMENT_SIZE == PDFTABLE_FRAGMENT_SIZE - 1) { - document.add(tablePDF); - tablePDF.deleteBodyRows(); - tablePDF.setSkipFirstHeader(true); + if (rowNum % maxRowsPerPage == maxRowsPerPage - 1) { + contentStream.close(); + PDRectangle landscapeA4 = new PDRectangle(PDRectangle.A4.getHeight(), PDRectangle.A4.getWidth()); + PDPage page = new PDPage(landscapeA4); + document.addPage(page); + contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true); + contentStream.setFont(smallFont, 7); + yPosition = 540; } Row row = rowIterator.next(); - - super.startRow(row.getObject()); - - // iterator on columns + xPosition = 50; ColumnIterator columnIterator = row.getColumnIterator(this.model.getHeaderCellList()); - + cellHeight = calculateRowHeight(row, cellWidth); + maxRowsPerPage = (int) Math.floor(usablePageHeight / cellHeight); while (columnIterator.hasNext()) { Column column = columnIterator.nextColumn(); - // Get the value to be displayed for the column Object value = column.getValue(this.decorated); - - processPdfCell(column.getHeader(), value, false); +// cellHeight = calculateCellHeight(value.toString(), cellWidth); + addCell(value.toString(), xPosition, yPosition, cellWidth, cellHeight, false); + xPosition += cellWidth; } + yPosition -= cellHeight; rowNum++; } - generateTotals(); } + + private float calculateRowHeight(Row row, float cellWidth) throws IOException, ObjectLookupException, DecoratorException { + float maxHeight = 0; + ColumnIterator columnIterator = row.getColumnIterator(this.model.getHeaderCellList()); + while (columnIterator.hasNext()) { + Column column = columnIterator.nextColumn(); + Object value = column.getValue(this.decorated); + float cellHeight = calculateCellHeight(value.toString(), cellWidth); + if (cellHeight > maxHeight) { + maxHeight = cellHeight; + } + } + return maxHeight; + } + + private float calculateCellHeight(String text, float cellWidth) throws IOException { + contentStream.setFont(smallFont, 7); + String sanitizedText = sanitizeText(text); + float textWidth = smallFont.getStringWidth(sanitizedText) / 1000 * 7; // Convert font size to PDF points + int lines = (int) Math.ceil(textWidth / cellWidth); + return lines * 10 + 4; // 10 points per line + 4 points padding + } - private void generateTotals() throws BadElementException { - if (model.getTableDecorator() != null && model.getTableDecorator() instanceof TotalTableDecorator) { + private void generateTotals() throws IOException { + if (model.getTableDecorator() != null && model.getTableDecorator() instanceof TotalTableDecorator) { Iterator iterator = this.model.getHeaderCellList().iterator(); Map totals = super.getTotalRow(); + float yPosition = 540; // Adjust as necessary + float xPosition = 50; + float cellWidth = 100; // Width of each cell + float cellHeight = 20; // Height of each cell while (iterator.hasNext()) { HeaderCell headerCell = iterator.next(); Object value = totals.get(headerCell.getBeanPropertyName()); ColumnDecorator decorator = headerCell.getColumnDecorator(); if (decorator != null) { - try { - value = decorator.decorate(value); - } catch (DecoratorException e) { - log.warn(e.getMessage(), e); - } + try { + value = decorator.decorate(value); + } catch (DecoratorException e) { + log.warn(e.getMessage(), e); + } } - processPdfCell(headerCell, value, true); + addCell(value == null ? "" : value.toString(), xPosition, yPosition, cellWidth, cellHeight, true); + yPosition -= cellWidth; } } - } - - private void processPdfCell(HeaderCell hc, Object value, boolean isTotal) - throws BadElementException { - PdfPCell cell = getCell(value == null ? "" : value.toString()); - - if (isTotal) { - if (value == null || value == "") { - cell.setBorder(Rectangle.NO_BORDER); - } else { - cell.setBackgroundColor(BaseColor.LIGHT_GRAY); - } - } - Object al = hc.getHtmlAttributes().get(TagConstants.ATTRIBUTE_ALIGN); - if (al == null) { - Object dec = hc.getColumnDecorator(); - if (dec instanceof ValueDecorator) { - al = "right"; - } - } - if (al != null) { - String align = (String)al; - if (align.equalsIgnoreCase("left")) { - cell.setHorizontalAlignment(Element.ALIGN_LEFT); - } else if(align.equalsIgnoreCase("right")) { - cell.setHorizontalAlignment(Element.ALIGN_RIGHT); - } else if(align.equalsIgnoreCase("center")) { - cell.setHorizontalAlignment(Element.ALIGN_CENTER); - } - } - tablePDF.addCell(cell); - } - + } + + private String sanitizeText(String text) { + // Rimuove i caratteri di controllo dal testo + return text.replaceAll("\\p{Cntrl}", ""); + } + /** * Returns a formatted cell for the given value. * @@ -305,27 +277,108 @@ public abstract class AbstractPdfExporter extends AbstractTotalExporter { * @return Cell * @throws BadElementException errors while generating content */ - protected PdfPCell getCell(String value) throws BadElementException { - PdfPCell cell = new PdfPCell(new Phrase(StringUtils.trimToEmpty(value), smallFont)); - cell.setVerticalAlignment(Element.ALIGN_TOP); - cell.setLeading(8, 0); - return cell; +// private void addCell(String value, float x, float y, boolean isHeader) throws IOException { +// value = sanitizeText(value); +// contentStream.beginText(); +// contentStream.newLineAtOffset(x, y); +// contentStream.setFont(smallFont, 7); +// contentStream.showText(StringUtils.trimToEmpty(value)); +// contentStream.endText(); +// +// if (isHeader) { +// contentStream.setNonStrokingColor(200); // Light gray +// contentStream.addRect(x, y - 5, 50, 10); // Cell dimensions +// contentStream.fill(); +// contentStream.setNonStrokingColor(0); // Reset to black +// } +// +// // Manual vertical alignment +// float leading = 8; +// contentStream.setLeading(leading); +// } + protected void addCell(String value, float x, float y, float width, float height, boolean isHeader) throws IOException { + value = sanitizeText(value); + + contentStream.setNonStrokingColor(isHeader ? 200 : 255); // Light gray for headers + contentStream.addRect(x, y - height, width, height); + contentStream.fill(); + contentStream.setNonStrokingColor(0); // Reset to black + contentStream.setLineWidth(0.5f); + contentStream.addRect(x, y - height, width, height); + contentStream.stroke(); + + if (isHeader) { + float titleWidth = smallFont.getStringWidth(value) / 1000 * 7; + float textX = x + (width - titleWidth) / 2; // Center horizontally + float textY = y - (height) / 2 - 3; // Center vertically + contentStream.beginText(); + contentStream.newLineAtOffset(textX, textY); + contentStream.setFont(smallFont, 7); + contentStream.showText(value); + contentStream.endText(); + } else { + + float textY = y - 10; // Start text just below the top border of the cell + float textX = x + 2; // Start text with some padding from the left border of the cell + float availableWidth = width - 4; // Subtract padding from both sides + + String[] lines = splitTextIntoLines(value, availableWidth); + + for (String line : lines) { +// if (textY - 10 < y - height) { +// // If text goes beyond cell height, truncate remaining text +// break; +// } + contentStream.beginText(); + contentStream.newLineAtOffset(textX, textY); + contentStream.setFont(smallFont, 7); + contentStream.showText(line); + contentStream.endText(); + textY -= 10; // Move to next line + } + } + } + + private String[] splitTextIntoLines(String text, float maxWidth) throws IOException { + List lines = new ArrayList<>(); + StringBuilder currentLine = new StringBuilder(); + String[] words = text.split(" "); + + for (String word : words) { + if (smallFont.getStringWidth(currentLine + " " + word) / 1000 * 7 > maxWidth) { + lines.add(currentLine.toString()); + currentLine = new StringBuilder(word); + } else { + if (currentLine.length() > 0) { + currentLine.append(" "); + } + currentLine.append(word); + } + } + + if (currentLine.length() > 0) { + lines.add(currentLine.toString()); + } + + return lines.toArray(new String[0]); } - protected void prepareDocumentTitle(Document document) throws DocumentException { - Paragraph title = new Paragraph("Customize this document title by overriding prepareDocumentTitle method!"); - title.setAlignment(Element.ALIGN_CENTER); - document.add(title); - document.add(new Phrase("")); + protected void prepareDocumentTitle() throws IOException { + contentStream.beginText(); + contentStream.newLineAtOffset(document.getPage(0).getMediaBox().getWidth() / 2, 800); // Centered on the page + contentStream.setFont(smallFont, 12); + contentStream.showText("Customize this document title by overriding prepareDocumentTitle method!"); + contentStream.endText(); } - protected void prepareHeaderFooter(PdfWriter writer, Document document) { + protected void prepareHeaderFooter() throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); String footerText = sdf.format(new Date()) + " pagina: "; - PdfContentByte cb = writer.getDirectContent(); - Phrase footer = new Phrase(footerText, smallFont); - ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, - (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 10, 0); + contentStream.beginText(); + contentStream.newLineAtOffset(300, 30); // Bottom of the page + contentStream.setFont(smallFont, 7); + contentStream.showText(footerText); + contentStream.endText(); } /** diff --git a/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/AbstractPdfExporterOld.java b/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/AbstractPdfExporterOld.java new file mode 100644 index 0000000000000000000000000000000000000000..10a889b86ea6dc8eb8b3efbf63363c88c237b98c --- /dev/null +++ b/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/AbstractPdfExporterOld.java @@ -0,0 +1,374 @@ +//package it.mice.voila.runtime.displaytag.pdfexporter; +// +//import it.mice.voila.runtime.displaytag.basedec.ValueDecorator; +//import it.mice.voila.runtime.displaytag.exporter.AbstractTotalExporter; +// +//import java.awt.Color; +//import java.io.OutputStream; +//import java.text.SimpleDateFormat; +//import java.util.Date; +//import java.util.Iterator; +//import java.util.Map; +// +//import javax.servlet.jsp.JspException; +//import javax.servlet.jsp.PageContext; +// +//import org.apache.commons.lang.StringUtils; +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +//import org.displaytag.Messages; +//import org.displaytag.decorator.ColumnDecorator; +//import org.displaytag.decorator.TotalTableDecorator; +//import org.displaytag.exception.BaseNestableJspTagException; +//import org.displaytag.exception.DecoratorException; +//import org.displaytag.exception.ObjectLookupException; +//import org.displaytag.exception.SeverityEnum; +//import org.displaytag.model.Column; +//import org.displaytag.model.ColumnIterator; +//import org.displaytag.model.HeaderCell; +//import org.displaytag.model.Row; +//import org.displaytag.model.RowIterator; +//import org.displaytag.model.TableModel; +//import org.displaytag.util.TagConstants; +// +//import com.itextpdf.text.BadElementException; +//import com.itextpdf.text.BaseColor; +//import com.itextpdf.text.Document; +//import com.itextpdf.text.DocumentException; +//import com.itextpdf.text.Element; +//import com.itextpdf.text.Font; +//import com.itextpdf.text.FontFactory; +//import com.itextpdf.text.PageSize; +//import com.itextpdf.text.Paragraph; +//import com.itextpdf.text.Phrase; +//import com.itextpdf.text.Rectangle; +//import com.itextpdf.text.pdf.ColumnText; +//import com.itextpdf.text.pdf.PdfContentByte; +//import com.itextpdf.text.pdf.PdfPCell; +//import com.itextpdf.text.pdf.PdfPTable; +//import com.itextpdf.text.pdf.PdfWriter; +// +///** +// * Created by IntelliJ IDEA. +// * User: zzy9v4 +// * Date: May 23, 2006 +// * Time: 11:50:45 AM +// * To change this template use File | Settings | File Templates. +// */ +//public abstract class AbstractPdfExporterOld extends AbstractTotalExporter { +// /** +// * Logger. +// */ +// private static Log log = LogFactory.getLog(AbstractPdfExporter.class); +// +// private PageContext pageContext; +// +// /** +// * PDF table fragment size for fragmentation of large tables. +// * for more detail see http://itextdocs.lowagie.com/tutorial/objects/tables/pdfptable/ +// */ +// protected static final int PDFTABLE_FRAGMENT_SIZE = 20; +// +// /** +// * TableModel to render. +// */ +// protected TableModel model; +// +// /** +// * export full list? +// */ +// protected boolean exportFull; +// +// /** +// * include header in export? +// */ +// protected boolean header; +// +// /** +// * decorate export? +// */ +// protected boolean decorated; +// +// /** +// * This is the table, added as an Element to the PDF document. It contains all the data, needed to represent the +// * visible table into the PDF +// */ +// protected PdfPTable tablePDF; +// +// /** +// * The default font used in the document. +// */ +// protected Font smallFont; +// +// /** +// * @see org.displaytag.export.ExportView#setParameters(org.displaytag.model.TableModel, boolean, boolean, boolean) +// */ +// public void setParameters(TableModel tableModel, boolean exportFullList, boolean includeHeader, +// boolean decorateValues) { +// this.model = tableModel; +// this.exportFull = exportFullList; +// this.header = includeHeader; +// this.decorated = decorateValues; +// } +// +// /** +// * Initialize the main info holder table. +// * +// * @throws BadElementException for errors during table initialization +// */ +// protected void initTable() throws BadElementException { +// tablePDF = new PdfPTable(this.model.getNumberOfColumns()); +// +// tablePDF.setWidthPercentage(100); +// tablePDF.setHeaderRows(1); +// +// smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL, new BaseColor(0, 0, 0)); +// +// super.init(this.model); +// } +// +// /** +// * @return "application/pdf" +// * @see org.displaytag.export.BaseExportView#getMimeType() +// */ +// public String getMimeType() { +// return "application/pdf"; //$NON-NLS-1$ +// } +// +// /** +// * The overall PDF table generator. +// * +// * @throws javax.servlet.jsp.JspException for errors during value retrieving from the table model +// * @throws DecoratorException +// * @throws ObjectLookupException +// * @throws BadElementException IText exception +// */ +// protected void generatePDFTable(Document document) throws JspException, DocumentException, ObjectLookupException, DecoratorException { +// if (this.header) { +// generateHeaders(); +// } +// generateRows(document); +// } +// +// /** +// * @throws PdfGenerationException +// * @see org.displaytag.export.BinaryExportView#doExport(java.io.OutputStream) +// */ +// public void doExport(OutputStream out) throws PdfGenerationException { +// try { +// // Initialize the table with the appropriate number of columns +// initTable(); +// +// // Initialize the Document and register it with PdfWriter listener and the OutputStream +// Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40); +// PdfWriter.getInstance(document, out); +// +// document.addCreationDate(); +// +// PdfWriter writer = PdfWriter.getInstance(document, out); +// document.open(); +// +// prepareHeaderFooter(writer, document); +// prepareDocumentTitle(document); +// +// // Fill the virtual PDF table with the necessary data +// generatePDFTable(document); +// document.add(this.tablePDF); +// document.close(); +// +// } +// catch (Exception e) { +// throw new PdfGenerationException(e); +// } +// } +// +// /** +// * Generates the header cells, which persist on every page of the PDF document. +// * +// * @throws BadElementException IText exception +// */ +// @SuppressWarnings("unchecked") +// protected void generateHeaders() throws BadElementException { +// Iterator iterator = this.model.getHeaderCellList().iterator(); +// +// while (iterator.hasNext()) { +// HeaderCell headerCell = iterator.next(); +// +// String columnHeader = headerCell.getTitle(); +// +// if (columnHeader == null) { +// columnHeader = StringUtils.capitalize(headerCell.getBeanPropertyName()); +// } +// +// PdfPCell hdrCell = getCell(columnHeader); +// hdrCell.setGrayFill(0.9f); +// hdrCell.setHorizontalAlignment(Element.ALIGN_CENTER); +// tablePDF.addCell(hdrCell); +// } +// } +// +// /** +// * Generates all the row cells. +// * +// * @throws javax.servlet.jsp.JspException for errors during value retrieving from the table model +// * @throws DecoratorException +// * @throws ObjectLookupException +// * @throws BadElementException errors while generating content +// */ +// protected void generateRows(Document document) throws JspException, DocumentException, ObjectLookupException, DecoratorException { +// int rowNum = 0; +// // get the correct iterator (full or partial list according to the exportFull field) +// RowIterator rowIterator = this.model.getRowIterator(this.exportFull); +// // iterator on rows +// while (rowIterator.hasNext()) { +// if (rowNum % PDFTABLE_FRAGMENT_SIZE == PDFTABLE_FRAGMENT_SIZE - 1) { +// document.add(tablePDF); +// tablePDF.deleteBodyRows(); +// tablePDF.setSkipFirstHeader(true); +// } +// Row row = rowIterator.next(); +// +// super.startRow(row.getObject()); +// +// // iterator on columns +// ColumnIterator columnIterator = row.getColumnIterator(this.model.getHeaderCellList()); +// +// while (columnIterator.hasNext()) { +// Column column = columnIterator.nextColumn(); +// // Get the value to be displayed for the column +// Object value = column.getValue(this.decorated); +// +// processPdfCell(column.getHeader(), value, false); +// } +// rowNum++; +// } +// +// generateTotals(); +// } +// +// private void generateTotals() throws BadElementException { +// if (model.getTableDecorator() != null && model.getTableDecorator() instanceof TotalTableDecorator) { +// Iterator iterator = this.model.getHeaderCellList().iterator(); +// Map totals = super.getTotalRow(); +// +// while (iterator.hasNext()) { +// HeaderCell headerCell = iterator.next(); +// Object value = totals.get(headerCell.getBeanPropertyName()); +// ColumnDecorator decorator = headerCell.getColumnDecorator(); +// if (decorator != null) { +// try { +// value = decorator.decorate(value); +// } catch (DecoratorException e) { +// log.warn(e.getMessage(), e); +// } +// } +// processPdfCell(headerCell, value, true); +// } +// } +// } +// +// private void processPdfCell(HeaderCell hc, Object value, boolean isTotal) +// throws BadElementException { +// PdfPCell cell = getCell(value == null ? "" : value.toString()); +// +// if (isTotal) { +// if (value == null || value == "") { +// cell.setBorder(Rectangle.NO_BORDER); +// } else { +// cell.setBackgroundColor(BaseColor.LIGHT_GRAY); +// } +// } +// Object al = hc.getHtmlAttributes().get(TagConstants.ATTRIBUTE_ALIGN); +// if (al == null) { +// Object dec = hc.getColumnDecorator(); +// if (dec instanceof ValueDecorator) { +// al = "right"; +// } +// } +// if (al != null) { +// String align = (String)al; +// if (align.equalsIgnoreCase("left")) { +// cell.setHorizontalAlignment(Element.ALIGN_LEFT); +// } else if(align.equalsIgnoreCase("right")) { +// cell.setHorizontalAlignment(Element.ALIGN_RIGHT); +// } else if(align.equalsIgnoreCase("center")) { +// cell.setHorizontalAlignment(Element.ALIGN_CENTER); +// } +// } +// tablePDF.addCell(cell); +// } +// +// /** +// * Returns a formatted cell for the given value. +// * +// * @param value cell value +// * @return Cell +// * @throws BadElementException errors while generating content +// */ +// protected PdfPCell getCell(String value) throws BadElementException { +// PdfPCell cell = new PdfPCell(new Phrase(StringUtils.trimToEmpty(value), smallFont)); +// cell.setVerticalAlignment(Element.ALIGN_TOP); +// cell.setLeading(8, 0); +// return cell; +// } +// +// protected void prepareDocumentTitle(Document document) throws DocumentException { +// Paragraph title = new Paragraph("Customize this document title by overriding prepareDocumentTitle method!"); +// title.setAlignment(Element.ALIGN_CENTER); +// document.add(title); +// document.add(new Phrase("")); +// } +// +// protected void prepareHeaderFooter(PdfWriter writer, Document document) { +// SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); +// String footerText = sdf.format(new Date()) + " pagina: "; +// PdfContentByte cb = writer.getDirectContent(); +// Phrase footer = new Phrase(footerText, smallFont); +// ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, +// (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 10, 0); +// } +// +// /** +// * Wraps IText-generated exceptions. +// * +// * @author Fabrizio Giustina +// * @version $Revision: 1.1 $ ($Author: zzy9v4 $) +// */ +// static class PdfGenerationException extends BaseNestableJspTagException { +// +// /** +// * D1597A17A6. +// */ +// private static final long serialVersionUID = 899149338534L; +// +// /** +// * Instantiate a new PdfGenerationException with a fixed message and the given cause. +// * +// * @param cause Previous exception +// */ +// public PdfGenerationException(Throwable cause) { +// super(AbstractPdfExporter.class, Messages.getString("PdfView.errorexporting"), cause); //$NON-NLS-1$ +// } +// +// /** +// * @see org.displaytag.exception.BaseNestableJspTagException#getSeverity() +// */ +// public SeverityEnum getSeverity() { +// return SeverityEnum.ERROR; +// } +// } +// +// /** +// * Allow to register the PageContext instance useful to access all view context parameters such +// * as: request parameter, request/session attributes, etc... +// * +// * @param pageContext +// */ +// public void setPageContext(PageContext pageContext) { +// this.pageContext = pageContext; +// } +// +// public PageContext getPageContext() { +// return pageContext; +// } +//} \ No newline at end of file diff --git a/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/BasicPdfExporter.java b/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/BasicPdfExporter.java index e188706ab00ee621a596c36e8204adcef812d129..f5a05a9a561c5bd783e1de86ebeee0813d3e1166 100644 --- a/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/BasicPdfExporter.java +++ b/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/BasicPdfExporter.java @@ -2,22 +2,28 @@ package it.mice.voila.runtime.displaytag.pdfexporter; import it.mice.voila.runtime.displaytag.DisplayTagUtils; -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Element; -import com.itextpdf.text.Paragraph; -import com.itextpdf.text.Phrase; +import java.io.IOException; + +import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.pdmodel.font.PDType1Font; public class BasicPdfExporter extends AbstractPdfExporter { - protected void prepareDocumentTitle(Document document) throws DocumentException { - String title = DisplayTagUtils.getDocumentTitle(model); - if (title != null) { - Paragraph p = new Paragraph(title); - p.setSpacingAfter((float)5); - p.setAlignment(Element.ALIGN_CENTER); - document.add(p); - document.add(new Phrase("")); - } - } + protected void prepareDocumentTitle() throws IOException { + String title = DisplayTagUtils.getDocumentTitle(model); + if (title != null) { + PDRectangle pageSize = new PDRectangle(PDRectangle.A4.getHeight(), PDRectangle.A4.getWidth()); + float pageWidth = pageSize.getWidth(); + float titleFontSize = 12; + float titleWidth = PDType1Font.HELVETICA_BOLD.getStringWidth(title) / 1000 * titleFontSize; + float x = (pageWidth - titleWidth) / 2; + float y = 540; // Adjust y position as needed + contentStream.beginText(); + contentStream.newLineAtOffset(x, y); // Centered on the page + contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); + contentStream.showText(title); + contentStream.endText(); +// contentStream.moveTextPositionByAmount(0, -20); // Spacing after title + } + } } diff --git a/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/BasicPdfExporterOld.java b/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/BasicPdfExporterOld.java new file mode 100644 index 0000000000000000000000000000000000000000..e55bf635f5683047ce376c1c0994fd7deac93b5f --- /dev/null +++ b/voila-runtime-displaytag/src/main/java/it/mice/voila/runtime/displaytag/pdfexporter/BasicPdfExporterOld.java @@ -0,0 +1,23 @@ +//package it.mice.voila.runtime.displaytag.pdfexporter; +// +//import it.mice.voila.runtime.displaytag.DisplayTagUtils; +// +//import com.itextpdf.text.Document; +//import com.itextpdf.text.DocumentException; +//import com.itextpdf.text.Element; +//import com.itextpdf.text.Paragraph; +//import com.itextpdf.text.Phrase; +// +//public class BasicPdfExporterOld extends AbstractPdfExporter { +// +// protected void prepareDocumentTitle(Document document) throws DocumentException { +// String title = DisplayTagUtils.getDocumentTitle(model); +// if (title != null) { +// Paragraph p = new Paragraph(title); +// p.setSpacingAfter((float)5); +// p.setAlignment(Element.ALIGN_CENTER); +// document.add(p); +// document.add(new Phrase("")); +// } +// } +//}