2014-01-16 3 views
0

Как я могу форматировать данные, экспортированные в PDF/RTF, с помощью тега?Как форматировать данные, экспортированные в pdf/rtf, с помощью displaytag?

Моего displaytag.properties

export.types=csv excel xml pdf rtf 
export.excel=true 
export.csv=true 
export.xml=true 
export.pdf=true 
export.rtf=true 
export.rtf.class=org.displaytag.export.DefaultRtfExportView 
export.pdf.class=org.displaytag.export.DefaultPdfExportView 

я использовал заголовок и нижний колонтитул в теге отображения.

Для отображения цвета в разных строках я настроил один html-декоратор. Этот декоратор расширяет TableDecorator, и HTML-просмотр работает так, как я ожидал.

Как этот html, как я могу создать один декоратор для PDF?

Для этого класса, который я хочу расширить, и какие методы мне нужно написать?

Я просто хочу, чтобы дать некоторый цвет на строк на основе данных в конкретной строке ..

ли кто-нибудь есть какие-нибудь идеи?

ответ

0

Лучше написать декоратор и добавить его в

<display:setProperty name="decorator.media.pdf" value="org.displaytag.sample.decorators.ItextTotalWrapper"/

Но вы можете иметь свой собственный класс экспортера.

Например, Создание пакета decorators и создать класс myPdfExportView.java в этом пакете и копировать вставить ниже код в нем.

package decorators; 

import java.awt.Color; 
import com.lowagie.text.Font; 
import com.lowagie.text.Rectangle; 

import java.io.OutputStream; 
import java.util.Iterator; 

import javax.servlet.jsp.JspException; 

import org.apache.commons.lang.ObjectUtils; 
import org.displaytag.Messages; 
import org.displaytag.exception.BaseNestableJspTagException; 
import org.displaytag.exception.SeverityEnum; 
import org.displaytag.export.BinaryExportView; 


import com.lowagie.text.Cell; 
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.apache.commons.lang.StringUtils; 

import com.lowagie.text.BadElementException; 
import com.lowagie.text.Chunk; 
import com.lowagie.text.Document; 

import com.lowagie.text.Element; 
import com.lowagie.text.FontFactory; 
import com.lowagie.text.HeaderFooter; 
import com.lowagie.text.PageSize; 
import com.lowagie.text.Phrase; 
import com.lowagie.text.Table; 


import com.lowagie.text.pdf.PdfWriter; 



public class myPdfExportView implements BinaryExportView 
{ 
private TableModel model; 
private boolean exportFull; 
private boolean header; 
private boolean decorated; 
private Table tablePDF; 
private Font smallFont; 
private Font headerFont; 
public void setParameters(TableModel tableModel, boolean exportFullList, boolean includeHeader, 
    boolean decorateValues) 
{ 
    this.model = tableModel; 
    this.exportFull = true; 
    this.header = includeHeader; 
    this.decorated = decorateValues; 
} 


protected void initTable() throws BadElementException 
{ 
    tablePDF = new Table(this.model.getNumberOfColumns()); 
    //tablePDF.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); 
    tablePDF.setCellsFitPage(true); 
    tablePDF.setWidth(100); 

    tablePDF.setPadding(2); 
    tablePDF.setSpacing(0); 

    smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL, new Color(0,0,0)); 
    headerFont = FontFactory.getFont(FontFactory.HELVETICA, 14, Font.BOLD, new Color(192, 20, 25)); 
} 


public String getMimeType() 
{ 
    return "application/pdf"; //$NON-NLS-1$ 
} 


protected void generatePDFTable() throws JspException, BadElementException 
{ 
    if (this.header) 
    { 
     generateHeaders(); 
    } 
    tablePDF.endHeaders(); 
    generateRows(); 
} 

public void doExport(OutputStream out) throws JspException 
{ 
    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); 
     document.addCreationDate(); 

     HeaderFooter header = new HeaderFooter(new Phrase(this.model.getCaption(), headerFont), false); 
     header.setBorder(Rectangle.NO_BORDER);    
     header.setAlignment(Element.ALIGN_CENTER); 

     HeaderFooter footer = new HeaderFooter(new Phrase("Page No - " + document.getPageNumber() , smallFont), true); 
     footer.setBorder(Rectangle.NO_BORDER); 
     footer.setAlignment(Element.ALIGN_CENTER); 
     //footer.setBackgroundColor(new Color(206, 204, 207)); 


     PdfWriter.getInstance(document, out); 

     // Fill the virtual PDF table with the necessary data 
     generatePDFTable(); 
     document.setHeader(header); 
     document.setFooter(footer); 
     document.open(); 
     document.add(this.tablePDF); 

     document.close(); 

    } 
    catch (Exception e) 
    { 
     throw new PdfGenerationException(e); 
    } 
} 


protected void generateHeaders() throws BadElementException 
{ 
    Iterator<HeaderCell> iterator = this.model.getHeaderCellList().iterator(); 

    while (iterator.hasNext()) 
    { 
     HeaderCell headerCell = iterator.next(); 

     String columnHeader = headerCell.getTitle(); 

     if (columnHeader == null) 
     { 
      columnHeader = StringUtils.capitalize(headerCell.getBeanPropertyName()); 
     } 

     Cell hdrCell = getCell(columnHeader); 
     hdrCell.setGrayFill(0.9f); 
     hdrCell.setHeader(true); 
     tablePDF.addCell(hdrCell); 

    } 
} 


protected void generateRows() throws JspException, BadElementException 
{ 
    // 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()) 
    { 
     Row row = rowIterator.next(); 

     // 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); 

      Cell cell = getCell(ObjectUtils.toString(value)); 

      tablePDF.addCell(cell); 
     } 
    } 
    Object value = this.model.getFooter().trim(); 

    Cell cell = getCell(ObjectUtils.toString(value).replace("\t","")); 
    //cell.setBackgroundColor(new Color(206, 204, 207)); 
    cell.setGrayFill(0.9f); 
    cell.setColspan(this.model.getHeaderCellList().size()); 
    cell.setVerticalAlignment(Element.ALIGN_TOP); 
    cell.setHorizontalAlignment(Element.ALIGN_LEFT); 
    cell.setLeading(8); 


    tablePDF.addCell(cell); 
} 


private Cell getCell(String value) throws BadElementException 
{ 
    Cell cell = new Cell(new Chunk(StringUtils.trimToEmpty(value), smallFont)); 
    cell.setVerticalAlignment(Element.ALIGN_TOP); 
    cell.setLeading(8); 
    return cell; 
} 


static class PdfGenerationException extends BaseNestableJspTagException 
{ 


    private static final long serialVersionUID = 899149338534L; 


    public PdfGenerationException(Throwable cause) 
    { 
     super(myPdfExportView.class, Messages.getString("PdfView.errorexporting"), cause); //$NON-NLS-1$ 
    } 


    public SeverityEnum getSeverity() 
    { 
     return SeverityEnum.ERROR; 
    } 
} 
} 

Примечание: Вы можете изменить шрифты в класс выше. Вы можете поместить цвета в этот класс.

Сделать displaytag.properties файл в папку ресурсов и добавьте следующие значения

export.pdf.class=decorators.myPdfExportView 

Я надеюсь, что этот пример будет работать для вас. Но есть и другие способы сделать это, используя Apache fop. Таким образом вам нужно указать style sheet для pdf. Но я думаю, что это сложнее.

Если вы хотите пойти с этим Here is the example

 Смежные вопросы

  • Нет связанных вопросов^_^