Example usage for com.itextpdf.text.pdf PdfPTable setKeepTogether

List of usage examples for com.itextpdf.text.pdf PdfPTable setKeepTogether

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfPTable setKeepTogether.

Prototype

public void setKeepTogether(final boolean keepTogether) 

Source Link

Document

If true the table will be kept on one page if it fits, by forcing a new page if it doesn't fit on the current page.

Usage

From source file:com.github.wolfposd.imsqti2pdf.PDFCreator.java

License:Open Source License

private void writeQuestions(Paragraph paragraph, Document document, boolean showCorrectAnswer,
        ArrayList<Question> qlist) throws DocumentException, IOException {
    for (int i = 0; i < qlist.size(); i++) {
        Question question = qlist.get(i);
        paragraph.clear();//w  ww .ja va 2s . c o m

        // addQuestionNumber(paragraph, i, qlist.size());

        addQuestionText(paragraph, question, i);

        addAnswerTexts(paragraph, showCorrectAnswer, question);

        fixFonts(paragraph);

        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100);
        table.setKeepTogether(true);

        PdfPCell cell = new PdfPCell();
        cell.addElement(paragraph);
        cell.setBorderColor(BaseColor.WHITE);
        cell.setBorder(PdfPCell.NO_BORDER);

        table.addCell(cell);

        document.add(table);
    }

}

From source file:com.github.wolfposd.imsqti2pdf.PDFCreator.java

License:Open Source License

private void addQuestionText(Paragraph paragraph, Question question, int questionnumber) throws IOException {
    String fixedFonts = question.questiontext.replace("font-size: 12pt", "font-size: 10pt");

    fixedFonts = fixedFonts.replace("face=\"courier new\"", "face=\"Courier\"");

    fixedFonts = fixedFonts.replace("src=\"media/", getPathToMedia());

    ArrayList<Element> htmllist = (ArrayList<Element>) HTMLWorker.parseToList(new StringReader(fixedFonts),
            null);//from  w  w w.  ja v a2 s.co  m

    ArrayList<Paragraph> codeParagraphs = new ArrayList<Paragraph>();

    for (int i = 0; i < htmllist.size(); i++) {
        Element e = htmllist.get(i);
        if (e instanceof Paragraph) {
            Paragraph p = (Paragraph) e;
            if (i == 0) {
                p.setIndentationLeft(INDENTATION);
                p.getFont().setSize(OVERALLFONTSIZE);
                p.add(0, getQuestionNumberChunk(p.getFont(), questionnumber));
                p.add(getPointsChunk(p.getFont(), question));
                paragraph.add(p);
            } else {
                codeParagraphs.add(p);
            }
        }
    }
    if (codeParagraphs.size() > 0) {
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(90);
        table.setKeepTogether(true);

        Paragraph codeParagraph = new Paragraph();

        for (Paragraph p : codeParagraphs) {
            p.setIndentationLeft(INDENTATION);
            p.getFont().setSize(OVERALLFONTSIZE);
            codeParagraph.add(p);
            fixFonts(p);
        }
        codeParagraph.add(Chunk.NEWLINE);

        PdfPCell cell = new PdfPCell();
        cell.addElement(codeParagraph);
        cell.setBorderColor(BaseColor.BLACK);
        table.addCell(cell);

        paragraph.add(Chunk.NEWLINE);
        paragraph.add(table);
    }
}

From source file:de.aidger.utils.pdf.BalanceReportConverter.java

License:Open Source License

/**
 * Writes a semester table and adds the groups of that semester to it.
 * /*from www . ja v  a 2s . c om*/
 * @param semester
 *            The name of the semester to be added.
 */
@SuppressWarnings("unchecked")
private void createSemester(String semester) {
    balanceReportGroups = new ArrayList<ArrayList>();
    try {
        Font semesterTitleFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 13);
        Font semesterNameFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 13);

        PdfPTable finalSemesterTable = new PdfPTable(1);

        PdfPTable semesterTitleTable = new PdfPTable(new float[] { 0.2f, 0.8f });

        PdfPCell semesterCell = new PdfPCell(new Phrase(_("Semester"), semesterTitleFont));
        semesterCell.setBorder(0);
        semesterTitleTable.addCell(semesterCell);

        semesterCell = new PdfPCell(new Phrase(semester, semesterNameFont));
        semesterCell.setBorder(0);
        semesterTitleTable.addCell(semesterCell);

        semesterCell = new PdfPCell(semesterTitleTable);
        semesterCell.setBorder(0);
        semesterCell.setPaddingTop(7.0f);
        finalSemesterTable.addCell(semesterCell);

        PdfPTable contentTable = new PdfPTable(1);

        /*
         * As long as there are groups for this Balance report, create new
         * group tables.
         */
        List<Course> courses = null;
        if (semester != null) {
            courses = (new Course()).getCoursesBySemester(semester);
        } else {
            courses = new ArrayList<Course>();
            List<Course> unsortedCourses = new Course().getAll();
            for (Course course : unsortedCourses) {
                if (course.getSemester() == null) {
                    courses.add(new Course(course));
                }
            }
        }
        List<Course> filteredCourses = balanceHelper.filterCourses(courses, filters);
        for (Course course : filteredCourses) {
            PdfPTable groupTable = null;
            if (balanceReportGroups.isEmpty()) {
                groupTable = createGroup(course);
            } else {
                boolean foundGroup = false;
                for (int i = 0; i <= balanceReportGroups.size() - 1; i++) {
                    if (((ArrayList) balanceReportGroups.get(i)).get(1).equals(course.getGroup())) {
                        foundGroup = true;
                        break;
                    }
                }
                if (!foundGroup) {
                    groupTable = createGroup(course);
                }
            }
        }
        for (int i = 0; i <= balanceReportGroups.size() - 1; i++) {
            PdfPCell cell = new PdfPCell((PdfPTable) ((ArrayList) balanceReportGroups.get(i)).get(0));
            cell.setBorder(0);
            cell.setPaddingBottom(8.0f);
            contentTable.addCell(cell);
        }
        PdfPCell contentCell = new PdfPCell(contentTable);
        contentCell.setPaddingLeft(10.0f);
        contentCell.setBorder(1);
        finalSemesterTable.addCell(contentCell);
        finalSemesterTable.setKeepTogether(true);
        document.add(finalSemesterTable);
    } catch (Exception e) {
        Logger.error(e.getMessage());
    }
}

From source file:de.aidger.utils.pdf.BalanceReportConverter.java

License:Open Source License

/**
 * Creates a new group table with the title of the group. Adds the table and
 * its title to the group table vector.//from w ww  . j a  v  a  2 s .c  om
 * 
 * @param course
 *            The course for which a group shall be created.
 * @return The PdfPTable of the group.
 */
@SuppressWarnings("unchecked")
private PdfPTable createGroup(Course course) {
    balanceReportGroupCreator = new BalanceReportGroupCreator(course, calculationMethod);
    List<Course> courses = null;
    sums = new ArrayList<Object>();
    try {
        if (course.getSemester() != null) {
            courses = (new Course()).getCoursesBySemester(course.getSemester());
        } else {
            courses = new ArrayList<Course>();
            List<Course> unsortedCourses = new Course().getAll();
            for (Course currentCourse : unsortedCourses) {
                if (currentCourse.getSemester() == null) {
                    courses.add(new Course(currentCourse));
                }
            }
        }
    } catch (SienaException e) {
        UI.displayError(e.toString());
    }
    List<Course> filteredCourses = balanceHelper.filterCourses(courses, filters);
    ArrayList<Long> addedCourses = new ArrayList<Long>();
    addedCourses.add(course.getId());
    for (Course filteredCourse : filteredCourses) {
        if (!addedCourses.contains(filteredCourse.getId())
                && filteredCourse.getGroup().equals(course.getGroup())) {
            balanceReportGroupCreator.addCourse(filteredCourse);
            addedCourses.add(filteredCourse.getId());
        }
    }
    ArrayList<Integer> costUnits = new ArrayList<Integer>();
    ArrayList<BalanceCourse> balanceCourses = balanceReportGroupCreator.getBalanceCourses();
    ArrayList<String> titles = new ArrayList<String>();
    String[] courseTitles = { _("Title"), _("Part"), _("Lecturer"), _("Target Audience"), _("Planned AWS"),
            _("Basic needed AWS") };
    for (int i = 0; i < courseTitles.length; i++) {
        titles.add(courseTitles[i]);
    }
    for (Object balanceCourse : balanceCourses) {
        for (BudgetCost budgetCost : ((BalanceCourse) balanceCourse).getBudgetCosts()) {
            int budgetCostId = budgetCost.getId();
            String budgetCostName = budgetCost.getName();
            if (!costUnits.contains(budgetCostId)) {
                costUnits.add(budgetCostId);
                titles.add(_("Budget costs from") + " " + budgetCostName);
            }
        }
    }
    int columnCount = titles.size();
    Font tableTitleFont;
    Font tableContentFont;
    try {
        tableContentFont = new Font(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED),
                9);
        tableTitleFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 9);

        Font groupTitleFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 11);
        Font groupNameFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 11);

        PdfPTable groupTable = new PdfPTable(1);
        PdfPTable groupNameTable = new PdfPTable(new float[] { 0.2f, 0.8f });
        PdfPCell groupTitle = new PdfPCell(new Phrase(_("Group"), groupTitleFont));
        groupTitle.setBorder(2);
        groupNameTable.addCell(groupTitle);
        PdfPCell groupName = new PdfPCell(new Phrase(course.getGroup(), groupNameFont));
        groupName.setBorder(2);
        groupNameTable.addCell(groupName);
        PdfPCell groupContent = new PdfPCell(groupNameTable);
        groupContent.setBorder(0);
        groupContent.setPaddingTop(3.0f);
        groupContent.setPaddingBottom(2.0f);
        groupTable.addCell(groupContent);
        float[] columnWidths = new float[columnCount];
        columnWidths[0] = (200 / columnCount);
        columnWidths[1] = (50 / columnCount);
        columnWidths[2] = (100 / columnCount);
        columnWidths[3] = (150 / columnCount);
        columnWidths[4] = (100 / columnCount);
        for (int i = 5; i < columnCount; i++) {
            columnWidths[i] = (100 / columnCount);
        }
        PdfPTable groupContentTable = new PdfPTable(columnWidths);
        /*
         * Create the titles of the table entries.
         */
        for (int i = 0; i < titles.size(); i++) {
            PdfPCell cell = new PdfPCell(new Phrase(titles.get(i), tableTitleFont));
            if (i != 0) {
                cell.setBorder(6);
            } else {
                cell.setBorder(2);
            }
            groupContentTable.addCell(cell);
        }

        PdfPCell cell = new PdfPCell(groupContentTable);
        cell.setBorder(0);
        groupTable.addCell(cell);
        sums.add(_("Sum"));
        sums.add("");
        sums.add("");
        sums.add("");
        sums.add(0.0);
        sums.add(0.0);
        for (Object balanceCourse : balanceCourses) {
            groupTable.addCell(addRow((BalanceCourse) balanceCourse, columnWidths, costUnits));
        }
        PdfPTable emptyRow = new PdfPTable(columnWidths);
        PdfPTable sumRow = new PdfPTable(columnWidths);
        for (int i = 0; i < sums.size(); i++) {
            cell = new PdfPCell(new Phrase(""));
            if (i != 0) {
                cell.setBorder(Rectangle.TOP + Rectangle.LEFT);
            } else {
                cell.setBorder(Rectangle.TOP);
            }
            emptyRow.addCell(cell);
            if (i < 4) {
                cell = new PdfPCell(new Phrase(new Phrase(sums.get(i).toString(), tableContentFont)));
            } else {
                /*
                 * Round to the configured precision.
                 */
                int decimalPlace = Integer.parseInt(Runtime.getInstance().getOption("rounding", "2"));
                double rounded = new BigDecimal((Double) sums.get(i))
                        .setScale(decimalPlace, BigDecimal.ROUND_HALF_EVEN).doubleValue();
                cell = new PdfPCell(
                        new Phrase(new BigDecimal(rounded).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString(),
                                tableContentFont));
            }
            if (i != 0) {
                cell.setBorder(Rectangle.TOP + Rectangle.LEFT);
            } else {
                cell.setBorder(Rectangle.TOP);
            }
            sumRow.addCell(cell);
        }
        cell = new PdfPCell(emptyRow);
        cell.setBorder(0);
        groupTable.addCell(cell);
        cell = new PdfPCell(sumRow);
        cell.setBorder(0);
        groupTable.addCell(cell);
        groupTable.setKeepTogether(true);

        balanceReportGroups.add(new ArrayList<Object>());
        int i = balanceReportGroups.size() - 1;
        ((ArrayList) balanceReportGroups.get(i)).add(groupTable);
        ((ArrayList) balanceReportGroups.get(i)).add(course.getGroup());

        return groupTable;
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:eu.aniketos.wp1.ststool.report.pdfgenerator.AbstractContentFactory.java

License:Open Source License

protected PdfPTable createTable(List<String[]> headers) {

    if (headers == null || headers.size() < 1)
        throw new RuntimeException("Table with 0 column");

    PdfPTable table = new PdfPTable(headers.size());
    for (String[] header : headers) {
        table.addCell(getHeaderCell(header));
    }//w  ww. java  2s  .  co m
    if (headers.size() > 2) {
        table.setWidthPercentage(100);
    }
    //table.setHeaderRows(1);
    table.setKeepTogether(!splitTable());

    return table;
}

From source file:fr.ybonnel.breizhcamppdf.PdfRenderer.java

License:Apache License

private void createTalksPages(List<Talk> talksToExplain) throws DocumentException, IOException {
    document.setPageSize(PageSize.A4);/*w w  w.j a  v  a  2  s .  co m*/
    document.newPage();

    Paragraph paragraph = new Paragraph("Liste des talks");
    paragraph.setSpacingAfter(25);
    paragraph.getFont().setSize(25);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    document.add(paragraph);

    for (TalkDetail talk : Lists.transform(talksToExplain, new Function<Talk, TalkDetail>() {
        @Override
        public TalkDetail apply(Talk input) {
            return TalkService.INSTANCE.getTalkDetail(input);
        }
    })) {

        if (talk == null) {
            continue;
        }

        Paragraph empty = new Paragraph(" ");
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100);
        table.setKeepTogether(true);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        PdfPCell cell;
        Chunk titleTalk = new Chunk(talk.getTitle(), talkFontTitle);
        titleTalk.setLocalDestination("talk" + talk.getId());
        float[] withTitle = { 0.05f, 0.95f };
        PdfPTable titleWithFormat = new PdfPTable(withTitle);
        titleWithFormat.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        titleWithFormat.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

        Image image = AvatarService.INSTANCE.getImage(PdfRenderer.class
                .getResource("/formats/" + talk.getTalk().getFormat().replaceAll(" ", "") + ".png"));
        titleWithFormat.addCell(image);
        titleWithFormat.addCell(new Paragraph(titleTalk));

        table.addCell(titleWithFormat);

        table.addCell(empty);

        table.addCell(new Paragraph("Salle " + talk.getTalk().getRoom() + " de " + talk.getTalk().getStart()
                + "  " + talk.getTalk().getEnd(), presentFont));

        table.addCell(empty);

        cell = new PdfPCell();
        cell.setBorder(0);
        cell.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        for (Element element : HTMLWorker
                .parseToList(new StringReader(markdownProcessor.markdown(talk.getDescription())), null)) {
            if (element instanceof Paragraph) {
                ((Paragraph) element).setAlignment(Element.ALIGN_JUSTIFIED);
            }
            cell.addElement(element);
        }
        table.addCell(cell);

        table.addCell(empty);

        table.addCell(new Paragraph("Prsent par :", presentFont));

        float[] widthSpeaker = { 0.05f, 0.95f };
        for (Speaker speaker : talk.getSpeakers()) {
            PdfPTable speakerWithAvatar = new PdfPTable(widthSpeaker);
            speakerWithAvatar.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            speakerWithAvatar.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

            speakerWithAvatar.addCell(AvatarService.INSTANCE.getImage(speaker.getAvatar()));
            speakerWithAvatar.addCell(new Phrase(speaker.getFullname()));
            table.addCell(speakerWithAvatar);
        }

        table.addCell(empty);
        table.addCell(empty);
        document.add(table);
    }
}

From source file:gov.nih.nci.firebird.service.registration.AbstractPdfWriterGenerator.java

License:Open Source License

PdfPTable createTable(int numberOfColumns) {
    PdfPTable table = new PdfPTable(numberOfColumns);
    table.setWidthPercentage(ONE_HUNDRED_PERCENT);
    table.setSplitRows(false);//from  w ww .j  a  va 2s .  co m
    table.setSpacingAfter(TABLE_SPACING);
    table.setKeepTogether(true);
    return table;
}

From source file:org.smap.sdal.managers.PDFSurveyManager.java

License:Open Source License

private void processForm(Parser parser, Document document, ArrayList<Result> record, String basePath,
        String serverRoot, boolean generateBlank, int depth, int length, int[] repIndexes, GlobalVariables gv,
        boolean appendix, ArrayList<ArrayList<Result>> parentRecords, String remoteUser, int oId)
        throws DocumentException, IOException, SQLException {

    // Check that the depth of repeats hasn't exceeded the maximum
    if (depth > repIndexes.length - 1) {
        depth = repIndexes.length - 1;//  ww w  .  j  av a2s  .c o m
    }

    boolean firstQuestion = true;
    for (int j = 0; j < record.size(); j++) {
        Result r = record.get(j);
        if (r.type.equals("form")) {

            firstQuestion = true; // Make sure there is a gap when we return from the sub form
            // If this is a blank template check to see the number of times we should repeat this sub form
            if (generateBlank) {
                int blankRepeats = getBlankRepeats(r.appearance);
                for (int k = 0; k < blankRepeats; k++) {
                    repIndexes[depth] = k;
                    processForm(parser, document, r.subForm.get(0), basePath, serverRoot, generateBlank,
                            depth + 1, k, repIndexes, gv, appendix, null, remoteUser, oId);
                }
            } else {
                for (int k = 0; k < r.subForm.size(); k++) {
                    // Maintain array list of parent records in order to look up ${values}
                    parentRecords.add(0, record); // Push this record in at the beginning of the list as we want to search most recent first
                    repIndexes[depth] = k;
                    processForm(parser, document, r.subForm.get(k), basePath, serverRoot, generateBlank,
                            depth + 1, k, repIndexes, gv, appendix, parentRecords, remoteUser, oId);
                }
            }
        } else {
            // Process the question

            Form form = survey.forms.get(r.fIdx);
            Question question = getQuestionFromResult(sd, r, form);

            if (question != null) {

                if (includeResult(r, question, appendix, gv, generateBlank)) {
                    if (question.type.equals("begin group")) {
                        if (question.isNewPage()) {
                            document.newPage();
                        }
                    } else if (question.type.equals("end group")) {
                        //ignore
                    } else {

                        Row row = prepareRow(record, survey, j, gv, length, appendix, parentRecords,
                                generateBlank);
                        PdfPTable newTable = processRow(parser, row, basePath, serverRoot, generateBlank, depth,
                                repIndexes, gv, remoteUser, oId);

                        newTable.setWidthPercentage(100);
                        newTable.setKeepTogether(true);

                        // Add a gap if this is the first question of the record
                        // or the previous row was at a different depth
                        if (firstQuestion) {
                            newTable.setSpacingBefore(5);
                        } else {
                            newTable.setSpacingBefore(row.spaceBefore());
                        }
                        firstQuestion = false;

                        // Start a new page if the first question needs to be on a new page
                        if (row.items.get(0).isNewPage) {
                            document.newPage();
                        }
                        document.add(newTable);
                        j += row.items.size() - 1; // Jump over multiple questions if more than one was added to the row
                    }
                }
            } else {
                log.info("Question Idx not found: " + r.qIdx);
            }

        }
    }

    return;
}