Example usage for com.lowagie.text Element ALIGN_CENTER

List of usage examples for com.lowagie.text Element ALIGN_CENTER

Introduction

In this page you can find the example usage for com.lowagie.text Element ALIGN_CENTER.

Prototype

int ALIGN_CENTER

To view the source code for com.lowagie.text Element ALIGN_CENTER.

Click Source Link

Document

A possible value for paragraph alignment.

Usage

From source file:Cotizacion.ExportarPDF.java

private static void acomodarDatosTablaProductos(Paragraph subCatPart) throws BadElementException {
    numeroFilas = LogicaCotizacion.numero;
    cantidadTabla = new String[numeroFilas];
    productoTabla = new String[numeroFilas];
    precioTabla = new String[numeroFilas];
    totalTabla = new String[numeroFilas];
    descripcionTabla = new String[numeroFilas];

    PdfPTable tabla = new PdfPTable(5);
    tabla.setWidthPercentage(100);// ww w  . ja va2 s.com

    PdfPCell celda = new PdfPCell(new Paragraph("Producto"));
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    celda.setBackgroundColor(new Color(0, 175, 239));
    tabla.addCell(celda);
    celda = new PdfPCell(new Paragraph("Descripcin"));
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    celda.setBackgroundColor(new Color(0, 175, 239));
    tabla.addCell(celda);
    celda = new PdfPCell(new Paragraph("P/U"));
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    celda.setBackgroundColor(new Color(0, 175, 239));
    tabla.addCell(celda);
    celda = new PdfPCell(new Paragraph("Cantidad"));
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    celda.setBackgroundColor(new Color(0, 175, 239));
    tabla.addCell(celda);
    celda = new PdfPCell(new Paragraph("Total"));
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    celda.setBackgroundColor(new Color(0, 175, 239));
    tabla.addCell(celda);
    for (int i = 0; i < numeroFilas; i++) {
        productoTabla[i] = "" + Cotizacion.PanelCotizacion.tablaProductos.getValueAt(i, 0);
        tabla.addCell("   " + productoTabla[i]);
        descripcionTabla[i] = "" + Cotizacion.PanelCotizacion.tablaProductos.getValueAt(i, 1);
        tabla.addCell("" + descripcionTabla[i]);
        precioTabla[i] = "" + Cotizacion.PanelCotizacion.tablaProductos.getValueAt(i, 2);
        tabla.addCell("$  " + precioTabla[i]);
        cantidadTabla[i] = "" + Cotizacion.PanelCotizacion.tablaProductos.getValueAt(i, 3);
        tabla.addCell("   " + cantidadTabla[i]);
        totalTabla[i] = "" + Cotizacion.PanelCotizacion.tablaProductos.getValueAt(i, 4);
        tabla.addCell("$  " + totalTabla[i]);
    }
    agregarLineasEnBlanco(subCatPart, 1);
    subCatPart.add(tabla);
}

From source file:datasoul.servicelist.ServiceListExporterDocument.java

License:Open Source License

public void addServicePlan() throws DocumentException {

    ServiceListTable slt = ServiceListTable.getActiveInstance();

    Paragraph p = new Paragraph(
            java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("SERVICE PLAN"),
            FontFactory.getFont(FontFactory.HELVETICA, 12));
    p.setAlignment(Element.ALIGN_CENTER);
    document.add(p);//from w ww .  j  ava  2  s.  com

    p = new Paragraph(slt.getTitle(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16));
    p.setAlignment(Element.ALIGN_CENTER);
    document.add(p);

    Table t = new Table(4);
    t.setWidths(new int[] { 10, 5, 50, 35 });
    t.setPadding(2.0f);
    t.setWidth(100.0f);

    t.addCell(createHeaderCell(
            java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("TIME")));
    t.addCell(
            createHeaderCell(java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("MIN")));
    t.addCell(createHeaderCell(
            java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("TITLE")));
    t.addCell(createHeaderCell(
            java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("NOTES")));

    for (int i = 0; i < slt.getRowCount(); i++) {

        ServiceItem si = (ServiceItem) slt.getServiceItem(i);
        Cell c;

        // Start time
        c = new Cell(si.getStartTime());
        c.setMaxLines(1);
        c.setVerticalAlignment(Cell.ALIGN_MIDDLE);
        c.setHorizontalAlignment(Cell.ALIGN_CENTER);
        t.addCell(c);

        // Duration
        c = new Cell(Integer.toString(si.getDuration()));
        c.setMaxLines(1);
        c.setVerticalAlignment(Cell.ALIGN_MIDDLE);
        c.setHorizontalAlignment(Cell.ALIGN_RIGHT);
        t.addCell(c);

        // Title
        c = new Cell(si.getTitle());
        c.setVerticalAlignment(Cell.ALIGN_MIDDLE);
        t.addCell(c);

        // Notes
        c = new Cell(si.getNotes());
        c.setVerticalAlignment(Cell.ALIGN_MIDDLE);
        t.addCell(c);

    }

    document.add(t);

    p = new Paragraph(java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("NOTES"),
            FontFactory.getFont(FontFactory.HELVETICA_BOLD));
    document.add(p);

    p = new Paragraph(slt.getNotes(), FontFactory.getFont(FontFactory.HELVETICA));
    p.setIndentationLeft(10.0f);
    document.add(p);

    document.newPage();

}

From source file:de.appplant.cordova.plugin.printer.Printer.java

License:Apache License

/**
 * Slices the screenshot into pages, merges those into a single pdf
 * and saves it in the public accessible /sdcard dir.
 *///from  ww  w.  j  a  v a  2s  . c  o m
private File saveWebViewAsPdf(Bitmap screenshot) {
    try {

        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File(sdCard.getAbsolutePath() + "/" + this.publicTmpDir + "/");
        dir.mkdirs();
        File file;
        FileOutputStream stream;

        double pageWidth = PageSize.A4.getWidth() * 0.85; // width of the image is 85% of the page
        double pageHeight = PageSize.A4.getHeight() * 0.80; // max height of the image is 80% of the page
        double pageHeightToWithRelation = pageHeight / pageWidth; // e.g.: 1.33 (4/3)

        Bitmap currPage;
        int totalSize = screenshot.getHeight();
        int currPos = 0;
        int currPageCount = 0;
        int sliceWidth = screenshot.getWidth();
        int sliceHeight = (int) Math.round(sliceWidth * pageHeightToWithRelation);
        while (totalSize > currPos && currPageCount < 100) // max 100 pages
        {
            currPageCount++;

            Log.v(LOG_TAG, "Creating page nr. " + currPageCount);

            // slice bitmap
            currPage = Bitmap.createBitmap(screenshot, 0, currPos, sliceWidth,
                    (int) Math.min(sliceHeight, totalSize - currPos));

            // save page as png
            stream = new FileOutputStream(new File(dir, "print-page-" + currPageCount + ".png"));
            currPage.compress(Bitmap.CompressFormat.PNG, 100, stream);
            stream.close();

            // move current position indicator
            currPos += sliceHeight;
        }

        // create pdf
        Log.v(LOG_TAG, "Creating pdf");
        Document document = new Document();
        File filePdf = new File(dir, this.printTitle + ".pdf"); // change the output name of the pdf here
        PdfWriter.getInstance(document, new FileOutputStream(filePdf));
        document.open();
        for (int i = 1; i <= currPageCount; ++i) {
            Log.v(LOG_TAG, "Adding page nr. " + i + " to the pdf file.");
            file = new File(dir, "print-page-" + i + ".png");
            Image image = Image.getInstance(file.getAbsolutePath());
            image.scaleToFit((float) pageWidth, 9999);
            image.setAlignment(Element.ALIGN_CENTER);
            document.add(image);
            document.newPage();
        }
        document.close();

        // delete tmp image files
        for (int i = 1; i <= currPageCount; ++i) {
            file = new File(dir, "print-page-" + i + ".png");
            file.delete();
        }

        return filePdf;

    } catch (IOException e) {
        Log.e(LOG_TAG, "ERROR: " + e.getMessage());
        e.printStackTrace();
        // return error answer to cordova
        PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        result.setKeepCallback(false);
        ctx.sendPluginResult(result);
    } catch (DocumentException e) {
        Log.e(LOG_TAG, "ERROR: " + e.getMessage());
        e.printStackTrace();
        // return error answer to cordova
        PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        result.setKeepCallback(false);
        ctx.sendPluginResult(result);
    }

    Log.e(LOG_TAG, "Uncaught ERROR!");

    return null;
}

From source file:de.dhbw.humbuch.util.PDFHandler.java

/**
 * Use the configuration information to fill the table cells
 * @param tableBuilder Table configuration
 */// w  w  w .j  a v a2s  .com
private static void fillTableWithContent(TableBuilder tableBuilder) {
    PdfPCell cell = null;
    for (int i = 0; i < tableBuilder.contentArray.length; i++) {
        if (tableBuilder.contentArray[i] == null || tableBuilder.contentArray[i].equals("null")) {
            tableBuilder.contentArray[i] = "";
        }
        if (tableBuilder.font != null) {
            cell = new PdfPCell(new Phrase(tableBuilder.contentArray[i], tableBuilder.font));
        } else {
            cell = new PdfPCell(new Phrase(tableBuilder.contentArray[i]));
        }
        if (tableBuilder.isAlignedCentrally) {
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        }
        if (!tableBuilder.withBorder) {
            cell.setBorder(0);
        }
        if (tableBuilder.padding != 0f) {
            cell.setPadding(tableBuilder.padding);
        }
        if (tableBuilder.leading != 0f) {
            cell.setLeading(tableBuilder.leading, tableBuilder.leading);
        }
        tableBuilder.table.addCell(cell);
    }
}

From source file:de.jdufner.sudoku.generator.pdf.PdfCellHandler.java

License:Open Source License

private void formatZelle(final int zeile, final int spalte, final PdfPCell cell) {
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setBorderColor(new Color(//
            Integer.parseInt(getPdfStyle().getProperty("sudoku.board.border.color.red")), //
            Integer.parseInt(getPdfStyle().getProperty("sudoku.board.border.color.green")), //
            Integer.parseInt(getPdfStyle().getProperty("sudoku.board.border.color.blue"))));

    if (isEvenBlockIndex(zeile, spalte)) {
        cell.setBackgroundColor(new Color(//
                Integer.parseInt(getPdfStyle().getProperty("sudoku.board.background.odd.color.red")), //
                Integer.parseInt(getPdfStyle().getProperty("sudoku.board.background.odd.color.green")), //
                Integer.parseInt(getPdfStyle().getProperty("sudoku.board.background.odd.color.blue"))));
    } else {//from  ww w.j  a v  a2  s  .  c o  m
        cell.setBackgroundColor(new Color(//
                Integer.parseInt(getPdfStyle().getProperty("sudoku.board.background.even.color.red")), //
                Integer.parseInt(getPdfStyle().getProperty("sudoku.board.background.even.color.green")), //
                Integer.parseInt(getPdfStyle().getProperty("sudoku.board.background.even.color.blue"))));
    }
    cell.setBorderWidth(PdfConstants.RAHMEN_DUENN);
    if (BoxUtils.isFirstRowInBlock(zeile, getSudokuSize())) {
        cell.setBorderWidthTop(PdfConstants.RAHMEN_DICK);
    } else {
        cell.setBorderWidthTop(PdfConstants.RAHMEN_DUENN);
    }
    if (BoxUtils.isLastColumnInRow(spalte, getSudokuSize())) {
        cell.setBorderWidthRight(PdfConstants.RAHMEN_DICK);
    } else {
        cell.setBorderWidthRight(PdfConstants.RAHMEN_DUENN);
    }
    if (BoxUtils.isLastRowInColumn(zeile, getSudokuSize())) {
        cell.setBorderWidthBottom(PdfConstants.RAHMEN_DICK);
    } else {
        cell.setBorderWidthBottom(PdfConstants.RAHMEN_DUENN);
    }
    if (BoxUtils.isFirstColumnInBlock(spalte, getSudokuSize())) {
        cell.setBorderWidthLeft(PdfConstants.RAHMEN_DICK);
    } else {
        cell.setBorderWidthLeft(PdfConstants.RAHMEN_DUENN);
    }
    cell.setFixedHeight(27f);
}

From source file:de.jdufner.sudoku.generator.pdf.PdfCellHandler.java

License:Open Source License

/**
 * //from www. j a  va 2s. com
 * @return 3x3 Tabelle gefllt mit Kandidaten 1-9
 */
private PdfPTable buildCandidates() {
    final float CANDIDATE_FONT_SIZE = 6f;
    final float CANDIDATE_PADDING = 1f;
    PdfPTable candidates = new PdfPTable(3);
    PdfPCell[][] candidate = new PdfPCell[3][3];
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            Paragraph p = new Paragraph(String.valueOf(i * 3 + j + 1));
            p.getFont().setSize(CANDIDATE_FONT_SIZE);
            candidate[i][j] = new PdfPCell(p);
            candidate[i][j].setPadding(CANDIDATE_PADDING);
            candidate[i][j].setHorizontalAlignment(Element.ALIGN_CENTER);
            candidate[i][j].setVerticalAlignment(Element.ALIGN_MIDDLE);
            candidate[i][j].setBorderColor(new Color(PdfConstants.RAHMEN_FARBE[0], PdfConstants.RAHMEN_FARBE[1],
                    PdfConstants.RAHMEN_FARBE[2]));
            candidate[i][j].setBorderWidth(PdfConstants.RAHMEN_KEIN);
            if (i > 0) {
                candidate[i][j].setBorderWidthTop(PdfConstants.RAHMEN_DUENN);
            }
            if (j > 0) {
                candidate[i][j].setBorderWidthLeft(PdfConstants.RAHMEN_DUENN);
            }
            candidates.addCell(candidate[i][j]);
        }
    }
    return candidates;
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

private PdfPTable writePdfMetaTable(List<SudokuData> sudokus) throws DocumentException {
    // Tabelle fr Formatierung von 2 Sudokus nebeneinander
    PdfPTable metaTable = new PdfPTable(2);
    metaTable.getDefaultCell().setBorder(0);
    metaTable.getDefaultCell().setPadding(5);
    metaTable.setWidthPercentage(100);//from   w w w .  j  a  va 2  s .co m
    metaTable.setHorizontalAlignment(Element.ALIGN_CENTER);

    int cells = 0;
    for (SudokuData sudoku : sudokus) {
        metaTable.addCell(writePdfTable(sudoku));
        cells++;
    }
    final int rest = cells % 2;
    for (int i = 0; i < rest; i++) {
        metaTable.addCell("");
    }

    metaTable.setComplete(true);
    return metaTable;
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

private void writeFrontpage(String name, Document document, List<PdfSolution> solutions)
        throws DocumentException {
    document.open();/* w  ww. j  ava2 s  .c o m*/
    Paragraph p = new Paragraph(name);
    p.setAlignment(Element.ALIGN_CENTER);
    p.setSpacingBefore(20f);
    p.setSpacingAfter(20f);
    document.add(p);
    PdfPTable table = new PdfPTable(17);
    table.setWidthPercentage(100);
    int[] width = { 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
    table.setWidths(width);
    PdfPCell cell;
    table.addCell(buildHeaderCell("Name", 90, true, false));
    table.addCell(buildHeaderCell("Schwierigkeitsgrad", 90, false, false));
    table.addCell(buildHeaderCell("Besetzte Zellen", 90, false, false));
    table.addCell(buildHeaderCell("Simple", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Single", 90, false, false));
    table.addCell(buildHeaderCell("Naked Pair", 90, false, false));
    table.addCell(buildHeaderCell("Naked Triple", 90, false, false));
    table.addCell(buildHeaderCell("Naked Quad", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Pair", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Triple", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Quad", 90, false, false));
    table.addCell(buildHeaderCell("Intersection Removal", 90, false, false));
    table.addCell(buildHeaderCell("Y-Wing", 90, false, false));
    table.addCell(buildHeaderCell("X-Wing", 90, false, false));
    table.addCell(buildHeaderCell("Jellyfish", 90, false, false));
    table.addCell(buildHeaderCell("Swordfish", 90, false, false));
    table.addCell(buildHeaderCell("Backtracking", 90, false, true));
    boolean even = false;
    for (PdfSolution solution : solutions) {
        table.addCell(buildBodyNumberCell(solution.getId(), even, true, false));
        table.addCell(buildBodyTextCell(solution.getLevel().toString(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getFixed(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategySimple(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenSingle(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyNakedPair(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyNakedTriple(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyNakedQuad(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenPair(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenTriple(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenQuad(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyIntersectionRemoval(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyYwing(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyXwing(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyJellyfish(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategySwordfish(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyBacktracking(), even, false, true));
        even = (even ? false : true);
    }
    document.add(table);
    document.close();
}

From source file:de.tr1.cooperator.manager.web.CreateSubscriberListAction.java

License:Open Source License

/**
 * This method is called by the struts-framework if the submit-button is pressed.
 * It creates a PDF-File and puts in into the output-stream of the response.
 *//*from w  w  w .  j  a va2 s.  c  o m*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    CreateSubscriberListForm myForm = (CreateSubscriberListForm) form;
    boolean bSortByName;

    if (myForm.getSortBy().equals(myForm.SORTBYPN))
        bSortByName = false;
    else
        bSortByName = true;

    //create Collection for the results...
    Event eEvent = EventManager.getInstance().getEventByID(myForm.getEventID());
    Collection cSubscriberList = UserManager.getInstance().getUsersByCollection(eEvent.getSubscriberList());
    Collection cExamResults = EventResultManager.getInstance().getResults(eEvent.getID());

    Iterator cSubscriberListIT = cSubscriberList.iterator();
    Collection cSubscriberResultList = new ArrayList();

    while (cSubscriberListIT.hasNext()) {
        User CurUser = (User) cSubscriberListIT.next();
        String UserPNR = CurUser.getPersonalNumber();

        Iterator cExamResultsIT = cExamResults.iterator();
        ExamResult curExamResult = null;
        String ResultUserPNR = null;
        while (cExamResultsIT.hasNext()) {
            curExamResult = (ExamResult) cExamResultsIT.next();

            ResultUserPNR = curExamResult.getUserPersonalNumber();
            if (UserPNR.equals(ResultUserPNR))
                break;
        }

        if (UserPNR.equals(ResultUserPNR)) {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser,
                        "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            }
        } else {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "-");
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser, "-");
                cSubscriberResultList.add(URS);
            }
        }

    }

    //sort List
    Collections.sort((List) cSubscriberResultList);

    BaseFont bf;
    //36pt = 0.5inch
    Document document = new Document(PageSize.A4, 36, 36, 72, 72);

    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
        Log.addLog("CreateSubscriberListAction: Error creating BaseFont: " + e);
        //2do: add ErrorMessage and return to inputFormular!
        return mapping.findForward("GeneralFailure");
    }

    //calculate the number of cols and their width
    int cols = 0;
    ArrayList alWidth = new ArrayList();
    float boldItalicFactor = 1.2f;
    if (myForm.getShowNumber())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowPersonalNumber())
        alWidth.add(new Float(
                boldItalicFactor * bf.getWidthPoint(TABLEHEADER_PERSONALNUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowName())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NAME, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowEmail())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_EMAIL, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowResult())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_RESULT, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddInfoField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_INFO, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddSignField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_SIGN, TABLEHEADER_FONTSIZE)));

    cols = alWidth.size();

    float totalWidth = 0;
    //calculate the whole length
    Iterator alIterator = alWidth.iterator();
    for (; alIterator.hasNext(); totalWidth += ((Float) alIterator.next()).floatValue())
        ;

    //calculate relativ width for the table
    float[] width = new float[cols];
    alIterator = alWidth.iterator();
    int i = 0;
    while (alIterator.hasNext()) {
        float pixLength = ((Float) alIterator.next()).floatValue();
        //alWidthRelativ.add( new Float( pixLength/totalWidth ) );
        width[i] = pixLength / totalWidth;
        i++;
    }

    //needed for the shrink (enlarge?)
    float shrinkFactor;

    try {
        //1st: set correct outputstream
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

        //1.5st: set content-stuff
        response.setContentType("application/pdf");

        //2nd: set EventManager for PageEvents to Helper
        writer.setPageEvent(
                new CreateSubscriberListActionHelper(myForm.getHeaderLeft(), myForm.getHeaderRight()));

        //3rd: open document for editing the content
        document.open();

        //4th: add content
        Phrase pInfoText = new Phrase(myForm.getInfoText(), new Font(bf, 12, Font.BOLD));
        document.add(pInfoText);

        //PdfPTable( cols )
        PdfPTable table = new PdfPTable(width);

        float documentWidth = document.right() - document.left();
        if (documentWidth < totalWidth) {
            table.setTotalWidth(documentWidth);
            shrinkFactor = documentWidth / totalWidth;
        } else {
            table.setTotalWidth(totalWidth);
            shrinkFactor = 1;
        }
        table.setLockedWidth(true);

        Font headerFont = new Font(bf, TABLEHEADER_FONTSIZE * shrinkFactor, Font.BOLDITALIC);
        Font cellFont = new Font(bf, TABLECELL_FONTSIZE * shrinkFactor, Font.NORMAL);

        if (myForm.getShowNumber())
            table.addCell(new Phrase(TABLEHEADER_NUMBER, headerFont));
        if (myForm.getShowPersonalNumber())
            table.addCell(new Phrase(TABLEHEADER_PERSONALNUMBER, headerFont));
        if (myForm.getShowName())
            table.addCell(new Phrase(TABLEHEADER_NAME, headerFont));
        if (myForm.getShowEmail())
            table.addCell(new Phrase(TABLEHEADER_EMAIL, headerFont));
        if (myForm.getShowResult())
            table.addCell(new Phrase(TABLEHEADER_RESULT, headerFont));
        if (myForm.getAddInfoField())
            table.addCell(new Phrase(TABLEHEADER_INFO, headerFont));
        if (myForm.getAddSignField())
            table.addCell(new Phrase(TABLEHEADER_SIGN, headerFont));

        //fill table
        Iterator iSRL = cSubscriberResultList.iterator();
        int counter = 1;
        while (iSRL.hasNext()) {
            UserResult curResult = (UserResult) iSRL.next();

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            if (myForm.getShowNumber())
                table.addCell(new Phrase("" + counter++, cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            if (myForm.getShowPersonalNumber())
                table.addCell(new Phrase(curResult.getPersonalNumber(), cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            if (myForm.getShowName())
                table.addCell(new Phrase(curResult.getSurname() + ", " + curResult.getFirstName(), cellFont));
            if (myForm.getShowEmail())
                table.addCell(new Phrase(curResult.getEmailAddress(), cellFont));
            if (myForm.getShowResult())
                table.addCell(new Phrase(curResult.getResult(), cellFont));
            if (myForm.getAddInfoField())
                table.addCell(new Phrase("", cellFont));
            if (myForm.getAddSignField())
                table.addCell(new Phrase("", cellFont));
        }

        //set how many rows are header...
        table.setHeaderRows(1);

        document.add(table);

        //5th: close document, write the output to the stream...
        document.close();
    } catch (Exception de) {
        Log.addLog("CreateSubscriberListAction: Error creating PDF: " + de);
    }

    //we dont need to return a forward, because we write directly to the outputstream!
    return null;
}

From source file:de.xirp.report.ReportGenerator.java

License:Open Source License

/**
 * Adds the title page with the given header string to the PDF
 * {@link com.lowagie.text.Document}.//w  w w.  j  ava2s .co m
 * 
 * @param heading
 *            The header text.
 * @throws DocumentException
 *             if something went wrong adding the page.
 * @see com.lowagie.text.Document
 */
private static void addTitle(String heading) throws DocumentException {

    para = getParagraph(heading, HEADER, Element.ALIGN_CENTER);
    document.add(para);
    addSkip(3);
    para = getParagraph(Constants.NON_UNICODE_APP_NAME, IMAGE, Image.ALIGN_CENTER);
    document.add(para);

    addSkip();

    para = getParagraph(I18n.getString("ReportGenerator.report.header.website"), TEXT, //$NON-NLS-1$
            Element.ALIGN_CENTER);
    document.add(para);

    para = getParagraph(Constants.LINE_SEPARATOR, TEXT, Element.ALIGN_CENTER);
    TEXT.setColor(new Color(0, 0, 255));
    Anchor anchor = new Anchor(I18n.getString("ReportGenerator.report.websiteLink"), TEXT); //$NON-NLS-1$
    anchor.setReference(I18n.getString("ReportGenerator.report.websiteLink")); //$NON-NLS-1$
    anchor.setName("homepage"); //$NON-NLS-1$
    para.add(anchor);
    document.add(para);
    document.newPage();
    TEXT.setColor(new Color(0, 0, 0));

    document.newPage();
}