Java Examples for com.itextpdf.text.pdf.PdfPTable
The following java examples will help you to understand the usage of com.itextpdf.text.pdf.PdfPTable. These source code samples are taken from different open source projects.
Example 1
| Project: cucumber-contrib-master File: Configuration.java View source code |
public void writePreambule(Document document) throws DocumentException {
String preambule = getPreambule();
if (preambule == null) {
return;
}
List<Element> elements = markdownContent(preambule);
for (Element element : elements) {
if (element instanceof PdfPTable)
extendTableToWidth((PdfPTable) element, document.right() - document.left());
document.add(element);
}
}Example 2
| Project: gutenberg-master File: FontawesomePdfTest.java View source code |
private File generateAwesomeFontPdf() throws DocumentException, IOException {
File fileOut = openDocument("awesomeFont");
BaseFont bf = BaseFont.createFont("font/FontAwesome.otf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(bf, 12);
FontAwesome awesome = FontAwesome.getInstance();
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(288 / 5.23f);
table.setWidths(new int[] { 2, 1 });
for (String key : awesome.keys().toSortedList(stringComparator())) {
table.addCell(new PdfPCell(new Phrase(key)));
table.addCell(new PdfPCell(new Phrase(awesome.get(key), font)));
}
document.add(table);
closeDocument();
return fileOut;
}Example 3
| Project: spring-boot-sample-master File: PdfView.java View source code |
@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {
PdfPTable table = new PdfPTable(2);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
// 这里为了测试,实际应用ä¸ï¼Œæˆ‘们从modelä¸è¯»å?–值
table.addCell("ID");
table.addCell("NAME");
table.addCell("100");
table.addCell("Shanhy");
document.add(table);
}Example 4
| Project: neohort-master File: link.java View source code |
public void executeLast(Hashtable _tagLibrary, Hashtable _beanLibrary) {
try {
int _align = getField_Int(new PdfPCell(new Phrase("")).getClass(), "ALIGN_" + internal_style.getALIGN(), 0);
com.itextpdf.text.Font font = getFont();
BaseColor _bColor = getField_Color(internal_style.getBACK_COLOR(), BaseColor.WHITE);
String content = prepareContentString(internal_style.getFORMAT());
Object canvas_prev = null;
try {
canvas_prev = ((java.util.Vector) (((report_element_base) _beanLibrary.get("SYSTEM:" + iConst.iHORT_SYSTEM_Canvas)).getContent())).lastElement();
} catch (Exception e) {
}
if (canvas_prev != null && (canvas_prev instanceof com.itextpdf.text.pdf.PdfPCell || canvas_prev instanceof com.itextpdf.text.pdf.PdfPTable)) {
int border = 15;
try {
border = Integer.valueOf(internal_style.getBORDER()).intValue();
} catch (Exception e) {
}
float padding = 0;
try {
padding = Float.valueOf(internal_style.getPADDING()).floatValue();
} catch (Exception e) {
}
PdfAction anAction = new PdfAction(getLINK());
Chunk chunk = new Chunk(content);
chunk.setAction(anAction);
chunk.setFont(font);
PdfPCell cell = new PdfPCell(new Phrase(chunk));
cell.setHorizontalAlignment(_align);
cell.setBorder(border);
cell.setBackgroundColor(_bColor);
if (padding != 0)
cell.setPadding(padding);
if (!internal_style.getDIRECTION().equals("") && internal_style.getDIRECTION().equalsIgnoreCase("RTL")) {
if (cell != null)
cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
}
((java.util.Vector) (((report_element_base) _beanLibrary.get("SYSTEM:" + iConst.iHORT_SYSTEM_Canvas)).getContent())).add(cell);
} else {
Anchor anchor = new Anchor(content, font);
anchor.setReference(getLINK());
anchor.setName(getID());
((java.util.Vector) (((report_element_base) _beanLibrary.get("SYSTEM:" + iConst.iHORT_SYSTEM_Canvas)).getContent())).add(anchor);
}
if (_tagLibrary.get(getName() + ":" + getID()) == null)
_tagLibrary.remove(getName() + ":" + getID() + "_ids_" + this.motore.hashCode());
else
_tagLibrary.remove(getName() + ":" + getID());
} catch (Exception e) {
setError(e, iStub.log_WARN);
}
}Example 5
| Project: BIS-BDT-Citizen-master File: PdfReportView.java View source code |
public static void addUserData(Document document, ReportModel reportModel) throws DocumentException {
//add line feed
document.add(new Paragraph(" "));
Paragraph paragraph = new Paragraph("My business", FONT[1]);
document.add(paragraph);
//add line feed
document.add(new Paragraph(" "));
// a table with three columns
PdfPTable table = new PdfPTable(2);
table.setHorizontalAlignment(Element.ALIGN_LEFT);
table.setWidthPercentage(50);
table.setSpacingBefore(5);
// we add a cell with colspan 2
PdfPCell cell = new PdfPCell(new Phrase("Information provided", FONT[2]));
cell.setColspan(2);
//cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
//cell.setGrayFill(0.9f);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.setPadding(5);
table.addCell(cell);
if (StringUtils.isNotBlank(reportModel.getBusinessAge())) {
table.addCell("Business age");
table.addCell(new PdfPCell(new Phrase(reportModel.getBusinessAge(), FONT[6])));
}
if (StringUtils.isNotBlank(reportModel.getLegalStructure())) {
table.addCell("Legal structure");
table.addCell(new PdfPCell(new Phrase(reportModel.getLegalStructure(), FONT[6])));
}
if (StringUtils.isNotBlank(reportModel.getPostCode())) {
table.addCell("Location");
table.addCell(new PdfPCell(new Phrase(reportModel.getPostCode(), FONT[6])));
}
if (StringUtils.isNotBlank(reportModel.getWorkforce())) {
table.addCell("Workforce");
table.addCell(new PdfPCell(new Phrase(reportModel.getWorkforce(), FONT[6])));
}
if (StringUtils.isNotBlank(reportModel.getSector())) {
table.addCell("Sector");
table.addCell(new PdfPCell(new Phrase(reportModel.getSector(), FONT[6])));
}
document.add(table);
}Example 6
| Project: itextpdf-master File: ColumnText.java View source code |
protected void setSimpleVars(final ColumnText org) {
maxY = org.maxY;
minY = org.minY;
alignment = org.alignment;
leftWall = null;
if (org.leftWall != null) {
leftWall = new ArrayList<float[]>(org.leftWall);
}
rightWall = null;
if (org.rightWall != null) {
rightWall = new ArrayList<float[]>(org.rightWall);
}
yLine = org.yLine;
currentLeading = org.currentLeading;
fixedLeading = org.fixedLeading;
multipliedLeading = org.multipliedLeading;
canvas = org.canvas;
canvases = org.canvases;
lineStatus = org.lineStatus;
indent = org.indent;
followingIndent = org.followingIndent;
rightIndent = org.rightIndent;
extraParagraphSpace = org.extraParagraphSpace;
rectangularWidth = org.rectangularWidth;
rectangularMode = org.rectangularMode;
spaceCharRatio = org.spaceCharRatio;
lastWasNewline = org.lastWasNewline;
repeatFirstLineIndent = org.repeatFirstLineIndent;
linesWritten = org.linesWritten;
arabicOptions = org.arabicOptions;
runDirection = org.runDirection;
descender = org.descender;
composite = org.composite;
splittedRow = org.splittedRow;
if (org.composite) {
compositeElements = new LinkedList<Element>();
for (Element element : org.compositeElements) {
if (element instanceof PdfPTable) {
compositeElements.add(new PdfPTable((PdfPTable) element));
} else {
compositeElements.add(element);
}
}
if (org.compositeColumn != null) {
compositeColumn = duplicate(org.compositeColumn);
}
}
listIdx = org.listIdx;
rowIdx = org.rowIdx;
firstLineY = org.firstLineY;
leftX = org.leftX;
rightX = org.rightX;
firstLineYDone = org.firstLineYDone;
waitPhrase = org.waitPhrase;
useAscender = org.useAscender;
filledWidth = org.filledWidth;
adjustFirstLine = org.adjustFirstLine;
inheritGraphicState = org.inheritGraphicState;
ignoreSpacingBefore = org.ignoreSpacingBefore;
}Example 7
| Project: micmiu-xmlworker-master File: Table.java View source code |
/*
* (non-Javadoc)
*
* @see
* com.itextpdf.tool.xml.TagProcessor#endElement(com.itextpdf.tool.xml.Tag,
* java.util.List, com.itextpdf.text.Document)
*/
@Override
public List<Element> end(final WorkerContext ctx, final Tag tag, final List<Element> currentContent) {
try {
boolean percentage = false;
String widthValue = tag.getCSS().get(HTML.Attribute.WIDTH);
if (widthValue == null) {
widthValue = tag.getAttributes().get(HTML.Attribute.WIDTH);
}
if (widthValue != null && widthValue.trim().endsWith("%")) {
percentage = true;
}
int numberOfColumns = 0;
List<TableRowElement> tableRows = new ArrayList<TableRowElement>(currentContent.size());
List<Element> invalidRowElements = new ArrayList<Element>(1);
String repeatHeader = tag.getCSS().get(CSS.Property.REPEAT_HEADER);
String repeatFooter = tag.getCSS().get(CSS.Property.REPEAT_FOOTER);
int headerRows = 0;
int footerRows = 0;
for (Element e : currentContent) {
int localNumCols = 0;
if (e instanceof TableRowElement) {
TableRowElement tableRowElement = (TableRowElement) e;
for (HtmlCell cell : tableRowElement.getContent()) {
localNumCols += cell.getColspan();
}
if (localNumCols > numberOfColumns) {
numberOfColumns = localNumCols;
}
tableRows.add(tableRowElement);
if (repeatHeader != null && repeatHeader.equalsIgnoreCase("yes") && tableRowElement.getPlace().equals(TableRowElement.Place.HEADER)) {
headerRows++;
}
if (repeatFooter != null && repeatFooter.equalsIgnoreCase("yes") && tableRowElement.getPlace().equals(TableRowElement.Place.FOOTER)) {
footerRows++;
}
} else {
invalidRowElements.add(e);
}
}
if (repeatFooter == null || !repeatFooter.equalsIgnoreCase("yes")) {
Collections.sort(tableRows, new NormalRowComparator());
} else {
Collections.sort(tableRows, new RepeatedRowComparator());
}
PdfPTable table = new PdfPTable(numberOfColumns);
table.setHeaderRows(headerRows + footerRows);
table.setFooterRows(footerRows);
TableStyleValues styleValues = setStyleValues(tag);
table.setTableEvent(new TableBorderEvent(styleValues));
setVerticalMargin(table, tag, styleValues, ctx);
widenLastCell(tableRows, styleValues.getHorBorderSpacing());
float[] columnWidths = new float[numberOfColumns];
float[] widestWords = new float[numberOfColumns];
float[] fixedWidths = new float[numberOfColumns];
float[] colspanWidestWords = new float[numberOfColumns];
int[] rowspanValue = new int[numberOfColumns];
float largestColumn = 0;
float largestColspanColumn = 0;
int indexOfLargestColumn = -1;
int indexOfLargestColspanColumn = -1;
// Initial fill of the widths arrays
for (TableRowElement row : tableRows) {
int column = 0;
for (HtmlCell cell : row.getContent()) {
// rowspan value of higher cell in this column.
while (rowspanValue[column] > 1) {
rowspanValue[column] = rowspanValue[column] - 1;
++column;
}
// needed for last column).
if (cell.getRowspan() > 1 && column != numberOfColumns - 1) {
rowspanValue[column] = cell.getRowspan() - 1;
}
int colspan = cell.getColspan();
if (cell.getFixedWidth() != 0) {
float fixedWidth = cell.getFixedWidth() + getCellStartWidth(cell);
fixedWidth /= colspan;
for (int i = 0; i < colspan; i++) {
int c = column + i;
if (fixedWidth > fixedWidths[c]) {
fixedWidths[c] = fixedWidth;
columnWidths[c] = fixedWidth;
}
}
}
if (cell.getCompositeElements() != null) {
float[] widthValues = setCellWidthAndWidestWord(cell);
float cellWidth = widthValues[0] / colspan;
float widestWordOfCell = widthValues[1] / colspan;
for (int i = 0; i < colspan; i++) {
int c = column + i;
if (fixedWidths[c] == 0 && cellWidth > columnWidths[c]) {
columnWidths[c] = cellWidth;
if (colspan == 1) {
if (cellWidth > largestColumn) {
largestColumn = cellWidth;
indexOfLargestColumn = c;
}
} else {
if (cellWidth > largestColspanColumn) {
largestColspanColumn = cellWidth;
indexOfLargestColspanColumn = c;
}
}
}
if (colspan == 1) {
if (widestWordOfCell > widestWords[c]) {
widestWords[c] = widestWordOfCell;
}
} else {
if (widestWordOfCell > colspanWidestWords[c]) {
colspanWidestWords[c] = widestWordOfCell;
}
}
}
}
if (colspan > 1) {
if (LOG.isLogging(Level.TRACE)) {
LOG.trace(String.format(LocaleMessages.getInstance().getMessage(LocaleMessages.COLSPAN), colspan));
}
column += colspan - 1;
}
column++;
}
}
if (indexOfLargestColumn == -1) {
indexOfLargestColumn = indexOfLargestColspanColumn;
if (indexOfLargestColumn == -1) {
indexOfLargestColumn = 0;
}
for (int column = 0; column < numberOfColumns; column++) {
widestWords[column] = colspanWidestWords[column];
}
}
float outerWidth = getTableOuterWidth(tag, styleValues.getHorBorderSpacing(), ctx);
float initialTotalWidth = getTableWidth(columnWidths, 0);
// float targetWidth = calculateTargetWidth(tag, columnWidths, outerWidth, ctx);
float targetWidth = 0;
HtmlPipelineContext htmlPipelineContext = getHtmlPipelineContext(ctx);
float max = htmlPipelineContext.getPageSize().getWidth() - outerWidth;
boolean tableWidthFixed = false;
if (tag.getAttributes().get(CSS.Property.WIDTH) != null || tag.getCSS().get(CSS.Property.WIDTH) != null) {
targetWidth = new WidthCalculator().getWidth(tag, htmlPipelineContext.getRootTags(), htmlPipelineContext.getPageSize().getWidth());
if (targetWidth > max) {
targetWidth = max;
}
tableWidthFixed = true;
} else if (initialTotalWidth <= max) {
targetWidth = initialTotalWidth;
} else if (null == tag.getParent() || (null != tag.getParent() && htmlPipelineContext.getRootTags().contains(tag.getParent().getName()))) {
targetWidth = max;
} else /* this table is an inner table and width adjustment is done in outer table */
{
targetWidth = getTableWidth(columnWidths, outerWidth);
}
float totalFixedColumnWidth = getTableWidth(fixedWidths, 0);
float targetPercentage = 0;
if (// all column widths are fixed
totalFixedColumnWidth == initialTotalWidth) {
targetPercentage = targetWidth / initialTotalWidth;
if (initialTotalWidth > targetWidth) {
for (int column = 0; column < columnWidths.length; column++) {
columnWidths[column] *= targetPercentage;
}
} else if (tableWidthFixed && targetPercentage != 1) {
for (int column = 0; column < columnWidths.length; column++) {
columnWidths[column] *= targetPercentage;
}
}
} else {
targetPercentage = (targetWidth - totalFixedColumnWidth) / (initialTotalWidth - totalFixedColumnWidth);
// is too large for the given targetWidth.
if (initialTotalWidth > targetWidth) {
float leftToReduce = 0;
for (int column = 0; column < columnWidths.length; column++) {
if (fixedWidths[column] == 0) {
// column.
if (widestWords[column] <= columnWidths[column] * targetPercentage) {
columnWidths[column] *= targetPercentage;
// else take the widest word and calculate space
// left to
// reduce.
} else {
columnWidths[column] = widestWords[column];
leftToReduce += widestWords[column] - columnWidths[column] * targetPercentage;
}
// if widestWord of a column does not fit in the
// fixedWidth,
// set the column width to the widestWord.
} else if (fixedWidths[column] < widestWords[column]) {
columnWidths[column] = widestWords[column];
leftToReduce += widestWords[column] - fixedWidths[column];
}
}
if (leftToReduce != 0) {
// widestWord still fits in the reduced column.
if (widestWords[indexOfLargestColumn] <= columnWidths[indexOfLargestColumn] - leftToReduce) {
columnWidths[indexOfLargestColumn] -= leftToReduce;
} else // set all none fixed columns to their minimum, with the
{
// widestWord array.
for (int column = 0; leftToReduce != 0 && column < columnWidths.length; column++) {
if (fixedWidths[column] == 0 && columnWidths[column] > widestWords[column]) {
float difference = columnWidths[column] - widestWords[column];
if (difference <= leftToReduce) {
leftToReduce -= difference;
columnWidths[column] = widestWords[column];
} else {
columnWidths[column] -= leftToReduce;
leftToReduce = 0;
}
}
}
if (leftToReduce != 0) {
// If the table has an insufficient fixed width
// by
// an
// attribute or style, try to enlarge the table
// to
// its
// minimum width (= widestWords array).
float pageWidth = getHtmlPipelineContext(ctx).getPageSize().getWidth();
if (getTableWidth(widestWords, outerWidth) < pageWidth) {
targetWidth = getTableWidth(widestWords, outerWidth);
leftToReduce = 0;
} else {
// If all columnWidths are set to the
// widestWordWidths and the table is still
// to
// wide
// content will fall off the edge of a page,
// which
// is similar to HTML.
targetWidth = pageWidth - outerWidth;
leftToReduce = 0;
}
}
}
}
// Enlarge width of columns to fit the targetWidth.
} else if (initialTotalWidth < targetWidth) {
for (int column = 0; column < columnWidths.length; column++) {
if (fixedWidths[column] == 0) {
columnWidths[column] *= targetPercentage;
}
}
}
}
try {
table.setTotalWidth(columnWidths);
table.setLockedWidth(true);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
} catch (DocumentException e) {
throw new RuntimeWorkerException(LocaleMessages.getInstance().getMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
}
Float tableHeight = new HeightCalculator().getHeight(tag, getHtmlPipelineContext(ctx).getPageSize().getHeight());
int rowNumber = 0;
for (TableRowElement row : tableRows) {
int columnNumber = -1;
Float computedRowHeight = null;
if (tableHeight != null && tableRows.indexOf(row) == tableRows.size() - 1) {
float computedTableHeigt = table.calculateHeights();
computedRowHeight = tableHeight - computedTableHeigt;
}
for (HtmlCell cell : row.getContent()) {
List<Element> compositeElements = cell.getCompositeElements();
if (compositeElements != null) {
for (Element baseLevel : compositeElements) {
if (baseLevel instanceof PdfPTable) {
TableStyleValues cellValues = cell.getCellValues();
float totalBordersWidth = cellValues.isLastInRow() ? styleValues.getHorBorderSpacing() * 2 : styleValues.getHorBorderSpacing();
totalBordersWidth += cellValues.getBorderWidthLeft() + cellValues.getBorderWidthRight();
float columnWidth = 0;
for (int currentColumnNumber = columnNumber + 1; currentColumnNumber <= columnNumber + cell.getColspan(); currentColumnNumber++) {
columnWidth += columnWidths[currentColumnNumber];
}
PdfPTableEvent tableEvent = ((PdfPTable) baseLevel).getTableEvent();
TableStyleValues innerStyleValues = ((TableBorderEvent) tableEvent).getTableStyleValues();
totalBordersWidth += innerStyleValues.getBorderWidthLeft();
totalBordersWidth += innerStyleValues.getBorderWidthRight();
((PdfPTable) baseLevel).setTotalWidth(columnWidth - totalBordersWidth);
}
}
}
columnNumber += cell.getColspan();
table.addCell(cell);
}
table.completeRow();
if (computedRowHeight != null && computedRowHeight > 0) {
float rowHeight = table.getRow(rowNumber).getMaxHeights();
if (rowHeight < computedRowHeight) {
table.getRow(rowNumber).setMaxHeights(computedRowHeight);
}
}
rowNumber++;
}
if (percentage) {
table.setWidthPercentage(utils.parsePxInCmMmPcToPt(widthValue));
table.setLockedWidth(false);
}
List<Element> elems = new ArrayList<Element>();
if (invalidRowElements.size() > 0) {
// all invalid row elements taken as caption
int i = 0;
Tag captionTag = tag.getChildren().get(i++);
while (!captionTag.getName().equalsIgnoreCase(HTML.Tag.CAPTION) && i < tag.getChildren().size()) {
captionTag = tag.getChildren().get(i);
i++;
}
String captionSideValue = captionTag.getCSS().get(CSS.Property.CAPTION_SIDE);
if (captionSideValue != null && captionSideValue.equalsIgnoreCase(CSS.Value.BOTTOM)) {
elems.add(table);
elems.addAll(invalidRowElements);
} else {
elems.addAll(invalidRowElements);
elems.add(table);
}
} else {
elems.add(table);
}
return elems;
} catch (NoCustomContextException e) {
throw new RuntimeWorkerException(LocaleMessages.getInstance().getMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e);
}
}Example 8
| Project: exporter-master File: PdfFileBuilder.java View source code |
@Override
protected void resetContent() {
document = new Document();
table = new PdfPTable(getNumberofColumns());
try {
PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
document.open();
}Example 9
| Project: tzatziki-master File: ScenarioOutlineEmitter.java View source code |
private void emitStepInErrorLegend(ITextContext emitterContext) {
Styles styles = emitterContext.styles();
PdfPTable table = new PdfPTable(new float[] { 1f, 24f });
table.addCell(noBorder(topRight(new PdfPCell(stepInErrorMarker(styles)))));
table.addCell(noBorder(new PdfPCell(new Phrase(": First step in error within the scenario", new FontCopier(styles.defaultFont()).italic().get()))));
table.setSpacingBefore(10f);
table.setSpacingAfter(10f);
emitterContext.append(table);
}Example 10
| Project: xdocreport-master File: StylableDocumentSection.java View source code |
private List<ColumnText> fillTable(float height) {
// copy text for simulation
List<ColumnText> tt = null;
if (breakHandlingParent == null && colIdx >= layoutTable.getNumberOfColumns()) {
// more column breaks than available column
// we try not to lose content
// but results may be different than in open office
// anyway it is logical error made by document creator
tt = new ArrayList<ColumnText>();
ColumnText t = createColumnText();
tt.add(t);
for (int i = 0; i < texts.size(); i++) {
PdfPTable table = new PdfPTable(1);
table.setWidthPercentage(100.0f);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.setPadding(0.0f);
cell.setColumn(ColumnText.duplicate(texts.get(i)));
table.addCell(cell);
t.addElement(table);
}
} else {
tt = new ArrayList<ColumnText>(texts);
for (int i = 0; i < tt.size(); i++) {
tt.set(i, ColumnText.duplicate(tt.get(i)));
}
}
// clear layout table
clearTable(layoutTable, true);
setWidthIfNecessary();
// try to fill cells with text
ColumnText t = tt.get(0);
for (PdfPCell cell : layoutTable.getRow(0).getCells()) {
cell.setFixedHeight(height >= 0.0f ? height : -1.0f);
cell.setColumn(ColumnText.duplicate(t));
//
t.setSimpleColumn(cell.getLeft() + cell.getPaddingLeft(), height >= 0.0f ? -height : PdfPRow.BOTTOM_LIMIT, cell.getRight() - cell.getPaddingRight(), 0);
int res = 0;
try {
res = t.go(true);
} catch (DocumentException e) {
throw new XWPFConverterException(e);
}
if (!ColumnText.hasMoreText(res)) {
// no overflow in current column
if (tt.size() == 1) {
// no more text
return null;
} else {
// some text waiting for new column
tt.remove(0);
t = tt.get(0);
}
}
}
return tt;
}Example 11
| Project: ABMS-master File: PdfFileFromExcelCreator.java View source code |
public static void createPDFfromExcel(File excelFile) throws Exception {
String currentMonth = DateUtils.getCurrentMonth();
FileInputStream inputStream = new FileInputStream(excelFile);
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
Document document = new Document(PageSize.A4.rotate());
PdfWriter.getInstance(document, new FileOutputStream(System.getProperty("user.dir") + "/files/general/Upkeep_" + currentMonth + ".pdf"));
document.open();
int numberOfCells = getNumberOfCells(sheet);
PdfPTable table = new PdfPTable(numberOfCells);
table.setWidthPercentage(100);
PdfPCell pdfCell;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
pdfCell = new PdfPCell(new Phrase(cell.getStringCellValue()));
table.addCell(pdfCell);
}
}
document.add(table);
document.close();
workbook.close();
zipFiles(currentMonth);
}Example 12
| Project: CaseTracker-master File: Export.java View source code |
private PdfPTable createTable(List<String> headers, List<String[]> cells) { PdfPTable table = new PdfPTable(headers.size()); Font boldFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD); logger.info("Filling in the table"); for (int i = 0; i < headers.size(); i++) { PdfPCell cell = new PdfPCell(new Phrase(headers.get(i), boldFont)); table.addCell(cell); } for (int j = 0; j < cells.size(); j++) { for (int k = 0; k < cells.get(j).length; k++) { PdfPCell cell = new PdfPCell(new Phrase(cells.get(j)[k])); table.addCell(cell); } } return table; }
Example 13
| Project: Corendon-master File: LuggageResolvedPDF.java View source code |
private static void addContent(File file, Document document, Luggage luggage, Customer customer) throws DocumentException {
Paragraph paragraph = new Paragraph();
addEmptyLine(paragraph, 1);
// TITLE
paragraph.add(new Paragraph("Luggage resolved report", titleFont));
String username = (EmployeeModel.getDefault().currentEmployee.username);
addEmptyLine(paragraph, 1);
paragraph.add(new //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Paragraph(//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"Report generated by: " + username + ", " + new Date(), smallBold));
addEmptyLine(paragraph, 3);
paragraph.add(new Paragraph("This document is a report of a resolved luggage case. It contains info of the resolved luggage and the associated customer.", smallBold));
addEmptyLine(paragraph, 1);
//generate table with the data of luggage in the PDF
PdfPTable table = new PdfPTable(2);
PdfPCell c1 = new PdfPCell(new Phrase("Datatype"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
PdfPCell c2 = new PdfPCell(new Phrase("Value"));
c2.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c2);
table.addCell("Color");
table.addCell(luggage.color.getHex());
table.addCell("Status");
table.addCell(luggage.status.getName());
table.addCell("Employee");
table.addCell(luggage.employee.firstName + " " + luggage.employee.lastName);
table.addCell("Airport");
table.addCell(luggage.airport.getName());
table.addCell("Dimensions");
table.addCell(luggage.dimensions);
table.addCell("Label");
table.addCell(luggage.label);
table.addCell("Notes");
table.addCell(luggage.notes);
table.addCell("Weight");
table.addCell(luggage.weight);
table.addCell("Brand");
table.addCell(luggage.brand.getName());
//generate customer table
Paragraph emptylines = new Paragraph();
addEmptyLine(emptylines, 3);
PdfPTable table2 = new PdfPTable(2);
table2.addCell(c1);
table2.addCell(c2);
table2.addCell("First name");
table2.addCell(customer.firstName);
table2.addCell("Last name");
table2.addCell(customer.lastName);
table2.addCell("Address");
table2.addCell(customer.address);
table2.addCell("Zipcode");
table2.addCell(customer.zipcode);
table2.addCell("State");
table2.addCell(customer.state);
// table2.addCell("Country");
// table2.addCell(customer.country.name);
table2.addCell("Email");
table2.addCell(customer.email);
table2.addCell("Phonenumber");
table2.addCell(customer.phone);
document.add(paragraph);
document.add(table);
document.add(emptylines);
document.add(table2);
try {
Desktop.getDesktop().open(file);
} catch (IOException ex) {
System.out.println("You need to have default program set to open .PDF files.");
}
}Example 14
| Project: elmis-master File: RequisitionPdfModelTest.java View source code |
@Test
public void shouldGetHeaderForEmergencyRnr() throws Exception {
mockMessageServiceCalls();
when(messageService.message("requisition.type.emergency")).thenReturn("Emergency");
PdfPTable header = requisitionPdfModel.getRequisitionHeader();
assertRowValues(header.getRow(0), "Report and Requisition for: Yellow Fever (Warehouse)");
assertRowValues(header.getRow(1), "Facility: F1", "Operated By: MOH", "Maximum Stock level: 100", "Emergency Order Point: 50.5");
assertRowValues(header.getRow(2), "Facility Code: F10010", "levelName: Arusha", "parentLevelName: Zambia", "Reporting Period: 01/01/2012 - 01/02/2012", "Requisition Type: Emergency");
assertThat(header.getSpacingAfter(), is(RequisitionPdfModel.PARAGRAPH_SPACING));
}Example 15
| Project: molgenis_apps-legacy-master File: LabelGenerator.java View source code |
public void startDocument(File pdfFile) throws LabelGeneratorException {
document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new LabelGeneratorException();
} catch (DocumentException e) {
e.printStackTrace();
throw new LabelGeneratorException();
}
document.open();
table = new PdfPTable(nrOfColumns);
}Example 16
| Project: patientview-master File: PdfDocumentDataBuilder.java View source code |
public byte[] build(DocumentData documentData) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
Document document = new Document(PageSize.A4, 0, 0, 20, 20);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
writer.setFullCompression();
writer.setLinearPageMode();
document.open();
PdfPTable table = new PdfPTable(documentData.getHeaders().size());
table.setWidthPercentage(90);
// create the header cells
for (String s : documentData.getHeaders()) {
table.addCell(createHeadingCell(s));
}
// create the data row cells
for (List<String> l : documentData.getRows()) {
for (String s : l) {
table.addCell(createRowCell(s));
}
}
document.add(table);
document.close();
} catch (Exception e) {
LOGGER.error("Could not build pdf " + e.getMessage());
}
return outputStream.toByteArray();
}Example 17
| Project: weplantaforest-master File: PdfReceiptView.java View source code |
public void writePdfDataToOutputStream(OutputStream toWrite, String imagePath, Receipt receipt) throws Exception {
// create pdf
final Document doc = new Document();
final PdfWriter pdfWriter = PdfWriter.getInstance(doc, toWrite);
pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), Locale.GERMAN);
cal.setTimeInMillis(System.currentTimeMillis());
final String date = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.YEAR);
_imagePath = imagePath;
doc.open();
int amountOfCarts = receipt.getCarts().size();
PdfContentByte cb = pdfWriter.getDirectContent();
pdfHelper.addLogo(cb, _imagePath, 262f, 720f);
createGeometricObjects(cb, amountOfCarts, doc);
PdfHelper.createAdress(cb, 75f, 710f);
createReceiptHeaderAndTextBelow(cb);
createUserFields(cb, receipt, doc);
PdfPTable priceTable = createPriceTable(cb, receipt);
PdfPTable dateTable = createDateTable(cb, receipt);
PdfPTable hintTable = createHintTable(cb);
PdfPTable lawTable = createLawTable(cb);
PdfPTable signatureTable = createSignatureTable(cb, date);
// hint block
if (amountOfCarts < 3) {
PdfHelper.createHeaderBlock(cb, 1, 1);
priceTable.writeSelectedRows(0, 3 + amountOfCarts, 85f, 390f, cb);
dateTable.writeSelectedRows(0, 3 + amountOfCarts, 395f, 390f, cb);
lawTable.writeSelectedRows(0, 6, 75f, 310f - (amountOfCarts + 1) * 16f, cb);
signatureTable.writeSelectedRows(0, 2, 75f, 225f - (amountOfCarts + 1) * 16f, cb);
cb.saveState();
cb.setRGBColorFill(0xE0, 0xDE, 0xDF);
cb.rectangle(0.0f, 0.0f, 595.0f, 100.0f);
cb.fill();
cb.stroke();
cb.restoreState();
hintTable.writeSelectedRows(0, 7, 75f, 90f, cb);
} else if (amountOfCarts >= 3 && amountOfCarts < 9) {
PdfHelper.createHeaderBlock(cb, 1, 2);
priceTable.writeSelectedRows(0, 3 + amountOfCarts, 85f, 390f, cb);
dateTable.writeSelectedRows(0, 3 + amountOfCarts, 395f, 390f, cb);
lawTable.writeSelectedRows(0, 6, 75f, 310f - (amountOfCarts + 1) * 16f, cb);
signatureTable.writeSelectedRows(0, 2, 75f, 225f - (amountOfCarts + 1) * 16f, cb);
doc.newPage();
PdfHelper.createHeaderBlock(cb, 2, 2);
cb.saveState();
cb.setRGBColorFill(0xE0, 0xDE, 0xDF);
cb.rectangle(0.0f, 722.0f, 595.0f, 100.0f);
cb.fill();
cb.stroke();
cb.restoreState();
hintTable.writeSelectedRows(0, 7, 75f, 812f, cb);
} else if (amountOfCarts >= 9 && amountOfCarts < 14) {
PdfHelper.createHeaderBlock(cb, 1, 2);
priceTable.writeSelectedRows(0, 3 + amountOfCarts, 85f, 390f, cb);
dateTable.writeSelectedRows(0, 3 + amountOfCarts, 395f, 390f, cb);
lawTable.writeSelectedRows(0, 6, 75f, 310f - (amountOfCarts + 1) * 16f, cb);
doc.newPage();
PdfHelper.createHeaderBlock(cb, 2, 2);
signatureTable.writeSelectedRows(0, 2, 75f, 812f, cb);
cb.saveState();
cb.setRGBColorFill(0xE0, 0xDE, 0xDF);
cb.rectangle(0.0f, 625.0f, 595.0f, 100.0f);
cb.fill();
cb.stroke();
cb.restoreState();
hintTable.writeSelectedRows(0, 7, 75f, 725f, cb);
} else if (amountOfCarts >= 14 && amountOfCarts < 20) {
PdfHelper.createHeaderBlock(cb, 1, 2);
priceTable.writeSelectedRows(0, 3 + amountOfCarts, 85f, 390f, cb);
dateTable.writeSelectedRows(0, 3 + amountOfCarts, 395f, 390f, cb);
doc.newPage();
PdfHelper.createHeaderBlock(cb, 2, 2);
lawTable.writeSelectedRows(0, 6, 75f, 812, cb);
signatureTable.writeSelectedRows(0, 2, 75f, 717, cb);
cb.saveState();
cb.setRGBColorFill(0xE0, 0xDE, 0xDF);
cb.rectangle(0.0f, 525.0f, 595.0f, 100.0f);
cb.fill();
cb.stroke();
cb.restoreState();
hintTable.writeSelectedRows(0, 7, 75f, 625f, cb);
} else if (amountOfCarts >= 20) {
PdfHelper.createHeaderBlock(cb, 1, 2);
priceTable.writeSelectedRows(0, 21, 85f, 390f, cb);
dateTable.writeSelectedRows(0, 21, 395f, 390f, cb);
doc.newPage();
PdfHelper.createHeaderBlock(cb, 2, 2);
// grey block
cb.saveState();
cb.setRGBColorFill(0xE0, 0xDE, 0xDF);
cb.rectangle(0.0f, 822f - (amountOfCarts - 18 + 1) * 16f - 8f, 595.0f, (amountOfCarts - 18 + 1) * 16f + 8f);
cb.fill();
cb.stroke();
cb.restoreState();
// price block
cb.saveState();
cb.setRGBColorFill(0xFC, 0xFC, 0xFC);
cb.rectangle(75.0f, 812f - (amountOfCarts - 18 + 1) * 16f + 12f, 295f, (amountOfCarts - 18 + 1) * 16f - 12f);
cb.fill();
cb.stroke();
cb.restoreState();
// date block
cb.saveState();
cb.setRGBColorFill(0xFC, 0xFC, 0xFC);
cb.rectangle(385.0f, 812f - (amountOfCarts - 18 + 1) * 16f + 12f, 135f, (amountOfCarts - 18 + 1) * 16f - 12f);
cb.fill();
cb.stroke();
cb.restoreState();
priceTable.writeSelectedRows(21, 22 + (amountOfCarts - 19), 85f, 812f, cb);
dateTable.writeSelectedRows(21, 22 + (amountOfCarts - 19), 395f, 812f, cb);
lawTable.writeSelectedRows(0, 6, 75f, 812 - (amountOfCarts - 18 + 1) * 16f, cb);
signatureTable.writeSelectedRows(0, 2, 75f, 727 - (amountOfCarts - 18 + 1) * 16f, cb);
cb.saveState();
cb.setRGBColorFill(0xE0, 0xDE, 0xDF);
cb.rectangle(0.0f, 550.0f - (amountOfCarts - 18 + 1) * 16f, 595.0f, 100.0f);
cb.fill();
cb.stroke();
cb.restoreState();
hintTable.writeSelectedRows(0, 7, 75f, 630f - (amountOfCarts - 18 + 1) * 16f, cb);
}
doc.close();
}Example 18
| Project: yougi-master File: EventAttendeeReport.java View source code |
public void printReport(List<Attendee> attendees) throws DocumentException {
// 520
float[] columnSizes = { 20, 220, 220, 60 };
PdfPTable table = new PdfPTable(columnSizes.length);
table.setLockedWidth(true);
table.setTotalWidth(columnSizes);
PdfPCell headerCell = new PdfPCell(new Phrase("JUG Management"));
headerCell.setColspan(4);
headerCell.setBackgroundColor(BaseColor.ORANGE);
headerCell.setPadding(3);
table.addCell(headerCell);
table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
PdfPCell checkCell = new PdfPCell(new Phrase(" "));
checkCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(checkCell);
PdfPCell productCell = new PdfPCell(new Phrase("Nome"));
productCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
productCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
table.addCell(productCell);
PdfPCell currentPurchaseCell = new PdfPCell(new Phrase("Email"));
currentPurchaseCell.setPadding(3);
currentPurchaseCell.setHorizontalAlignment(Element.ALIGN_CENTER);
currentPurchaseCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(currentPurchaseCell);
PdfPCell previousPurchaseCell = new PdfPCell(new Phrase("Presente"));
previousPurchaseCell.setPadding(3);
previousPurchaseCell.setHorizontalAlignment(Element.ALIGN_CENTER);
previousPurchaseCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(previousPurchaseCell);
table.getDefaultCell().setBackgroundColor(null);
table.setHeaderRows(2);
Font font = new Font(Font.FontFamily.HELVETICA, 9);
int seq = 1;
for (Attendee attendee : attendees) {
table.addCell(new Phrase(String.valueOf(seq++), font));
table.addCell(new Phrase(attendee.getAttendee().getFullName(), font));
table.addCell(new Phrase(attendee.getAttendee().getEmail(), font));
table.addCell(" ");
}
document.add(table);
}Example 19
| Project: Assignments-master File: ColumnText.java View source code |
protected void setSimpleVars(final ColumnText org) {
maxY = org.maxY;
minY = org.minY;
alignment = org.alignment;
leftWall = null;
if (org.leftWall != null) {
leftWall = new ArrayList<float[]>(org.leftWall);
}
rightWall = null;
if (org.rightWall != null) {
rightWall = new ArrayList<float[]>(org.rightWall);
}
yLine = org.yLine;
currentLeading = org.currentLeading;
fixedLeading = org.fixedLeading;
multipliedLeading = org.multipliedLeading;
canvas = org.canvas;
canvases = org.canvases;
lineStatus = org.lineStatus;
indent = org.indent;
followingIndent = org.followingIndent;
rightIndent = org.rightIndent;
extraParagraphSpace = org.extraParagraphSpace;
rectangularWidth = org.rectangularWidth;
rectangularMode = org.rectangularMode;
spaceCharRatio = org.spaceCharRatio;
lastWasNewline = org.lastWasNewline;
repeatFirstLineIndent = org.repeatFirstLineIndent;
linesWritten = org.linesWritten;
arabicOptions = org.arabicOptions;
runDirection = org.runDirection;
descender = org.descender;
composite = org.composite;
splittedRow = org.splittedRow;
if (org.composite) {
compositeElements = new LinkedList<Element>();
for (Element element : org.compositeElements) {
if (element instanceof PdfPTable) {
compositeElements.add(new PdfPTable((PdfPTable) element));
} else {
compositeElements.add(element);
}
}
if (org.compositeColumn != null) {
compositeColumn = duplicate(org.compositeColumn);
}
}
listIdx = org.listIdx;
rowIdx = org.rowIdx;
firstLineY = org.firstLineY;
leftX = org.leftX;
rightX = org.rightX;
firstLineYDone = org.firstLineYDone;
waitPhrase = org.waitPhrase;
useAscender = org.useAscender;
filledWidth = org.filledWidth;
adjustFirstLine = org.adjustFirstLine;
inheritGraphicState = org.inheritGraphicState;
ignoreSpacingBefore = org.ignoreSpacingBefore;
}Example 20
| Project: Consent2Share-master File: ConsentPdfGeneratorImpl.java View source code |
/*
* (non-Javadoc)
*
* @see gov.samhsa.consent2share.domain.consent.ConsentPdfGenerator#
* generate42CfrPart2Pdf(gov.samhsa.consent2share.domain.consent.Consent)
*/
@Override
public byte[] generate42CfrPart2Pdf(Consent consent) {
Assert.notNull(consent, "Consent is required.");
// Step 1
Document document = new Document();
ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
try {
Font fontbold = FontFactory.getFont("Helvetica", 12, Font.BOLD);
Font fontheader = FontFactory.getFont("Helvetica", 19, Font.BOLD);
Font fontnotification = FontFactory.getFont("Helvetica", 16, Font.ITALIC);
PdfWriter.getInstance(document, pdfOutputStream);
document.open();
Paragraph consentID = new Paragraph(20);
consentID.setAlignment(Element.ALIGN_LEFT);
Chunk chuckId = new Chunk();
chuckId.append("Consent Reference Number: ");
String consentIdString = String.valueOf(consent.getConsentReferenceId());
chuckId.append(consentIdString);
consentID.add(chuckId);
Paragraph paragraph1 = new Paragraph(20);
paragraph1.setSpacingAfter(10);
paragraph1.setAlignment(Element.ALIGN_CENTER);
Chunk chunk = new Chunk(consent.getDescription(), fontheader);
paragraph1.add(chunk);
Paragraph paragraph2 = new Paragraph(20);
paragraph2.setSpacingBefore(10);
PdfPTable headerNotification = new PdfPTable(1);
headerNotification.setHorizontalAlignment(Element.ALIGN_CENTER);
headerNotification.setWidthPercentage(100f);
headerNotification.addCell(new PdfPCell(new Phrase("***PLEASE READ THE ENTIRE FORM BEFORE SIGNING BELOW***", fontnotification)));
Chunk chunk2 = new Chunk("Patient (name and information of person whose health information is being disclosed): \n\n", fontbold);
Chunk chunk31 = new Chunk("Name (First Middle Last):");
Chunk chunk32 = new Chunk("Date of Birth(mm/dd/yyyy): ");
Chunk chunk33 = new Chunk("Street: ");
Chunk chunk34 = new Chunk("City: ");
Chunk chunk35 = new Chunk("State: ");
Chunk chunk36 = new Chunk("Zip: ");
String patientName = consent.getPatient().getFirstName() + " " + consent.getPatient().getLastName() + "\n";
Chunk chunkDob = null;
Chunk chunkStreet = null;
Chunk chunkCity = null;
Chunk chunkState = null;
Chunk chunkZip = null;
if (consent.getPatient().getBirthDay() != null) {
chunkDob = new Chunk(String.format("%tm/%td/%tY", consent.getPatient().getBirthDay(), consent.getPatient().getBirthDay(), consent.getPatient().getBirthDay()) + "\n");
chunkDob.setUnderline(1, -2);
}
if (consent.getPatient().getAddress() != null) {
if (consent.getPatient().getAddress().getStreetAddressLine() != null) {
chunkStreet = new Chunk(consent.getPatient().getAddress().getStreetAddressLine() + "\n");
chunkStreet.setUnderline(1, -2);
}
if (consent.getPatient().getAddress().getCity() != null) {
chunkCity = new Chunk(consent.getPatient().getAddress().getCity() + " ");
chunkCity.setUnderline(1, -2);
}
if (consent.getPatient().getAddress().getStateCode() != null) {
chunkState = new Chunk(consent.getPatient().getAddress().getStateCode().getDisplayName() + " ");
chunkState.setUnderline(1, -2);
}
if (consent.getPatient().getAddress().getPostalCode() != null) {
chunkZip = new Chunk(consent.getPatient().getAddress().getPostalCode());
chunkZip.setUnderline(1, -2);
}
}
Chunk chunk3 = new Chunk(patientName);
chunk3.setUnderline(1, -2);
Chunk chunk4 = new Chunk("authorizes ");
Chunk chunk6 = new Chunk(" to disclose to ");
Chunk chunk8 = new Chunk("Share the following medical information", fontbold);
chunk8.setUnderline(1, -2);
paragraph2.add(headerNotification);
paragraph2.add(chunk2);
paragraph2.add(chunk31);
paragraph2.add(chunk3);
if (chunkDob != null) {
paragraph2.add(chunk32);
paragraph2.add(chunkDob);
}
if (consent.getPatient().getAddress() != null) {
paragraph2.add(chunk33);
paragraph2.add(chunkStreet);
paragraph2.add(chunk34);
paragraph2.add(chunkCity);
paragraph2.add(chunk35);
paragraph2.add(chunkState);
paragraph2.add(chunk36);
paragraph2.add(chunkZip);
}
paragraph2.add(new Chunk("\n\n"));
paragraph2.add(chunk4);
paragraph2.add(createConsentMadeFromTable(consent));
paragraph2.add(chunk6);
paragraph2.add(createConsentMadeToTable(consent));
paragraph2.add(chunk8);
// Do Not Share Sensitivity List
Paragraph sensitivityParagraph = getSensitivityParagraph(consent);
// Do Not Share Clinical Document Type List
Paragraph clinicalDocumentTypeParagraph = getClinicalDocumentTypeParagraph(consent);
// Do Not Share Clinical Document Section Type List
Paragraph clinicalDocumentSectionTypeParagraph = getClinicalDocumentSectionTypeParagraph(consent);
Paragraph clinicalConceptCodesParagraph = getClinicalConceptCodesParagraph(consent);
Chunk chunk9 = null;
if (sensitivityParagraph != null || clinicalDocumentTypeParagraph != null || clinicalDocumentSectionTypeParagraph != null || clinicalConceptCodesParagraph != null) {
// chunk9 = new Chunk(" except the following:");
chunk9 = new Chunk(" :\n\n");
// chunk9.setUnderline(1, -2);
} else {
chunk9 = new Chunk(".");
}
paragraph2.add(chunk9);
Paragraph paragraph4 = new Paragraph(20);
paragraph4.setSpacingAfter(10);
paragraph4.setSpacingBefore(10);
Chunk chunk11 = new Chunk("Share for the following purpose(s):", fontbold);
chunk11.setUnderline(1, -2);
paragraph4.add(new Chunk("\n"));
paragraph4.add(chunk11);
// Do Not Share Purpose of Use List
Paragraph purposeOfUseParagraph = getPurposeOfUseParagraph(consent);
Paragraph paragraph5 = new Paragraph(20);
paragraph5.setSpacingBefore(10);
Chunk chunk13 = new Chunk("I understand that my records are protected under the federal regulations governing Confidentiality of Alcohol and Drug Abuse Patient Records, 42 CFR Part 2, and cannot be disclosed without my written consent unless otherwise provided for in the regulations, and may not be redisclosed without my written permission or as otherwise permitted by 42 CFR part 2. I also understand that I may revoke this consent at any time except to the extent that action has been taken in reliance on it, and that in any event this consent expires automatically as follows:");
paragraph5.add(chunk13);
Paragraph paragraph6 = new Paragraph(20);
Chunk chunk14;
if (consent.getEndDate() != null) {
chunk14 = new Chunk(String.format("Expiration Date: %tm/%td/%ty", consent.getEndDate(), consent.getEndDate(), consent.getEndDate()));
} else {
chunk14 = new Chunk("N/A");
}
chunk14.setUnderline(1, -2);
Chunk chunk15;
if (consent.getEndDate() != null) {
chunk15 = new Chunk(String.format("Effective Date: %tm/%td/%ty\n", consent.getStartDate(), consent.getStartDate(), consent.getStartDate()));
} else {
chunk15 = new Chunk("N/A");
}
chunk15.setUnderline(1, -2);
paragraph6.add(chunk15);
paragraph6.add(chunk14);
document.add(consentID);
document.add(paragraph1);
document.add(paragraph2);
if (sensitivityParagraph != null) {
document.add(sensitivityParagraph);
}
if (clinicalDocumentTypeParagraph != null) {
document.add(clinicalDocumentTypeParagraph);
}
if (clinicalDocumentSectionTypeParagraph != null) {
document.add(clinicalDocumentSectionTypeParagraph);
}
if (clinicalConceptCodesParagraph != null) {
document.add(clinicalConceptCodesParagraph);
}
document.add(paragraph4);
if (purposeOfUseParagraph != null) {
document.add(purposeOfUseParagraph);
}
document.add(paragraph5);
document.add(paragraph6);
// Step 5
document.close();
} catch (Throwable e) {
e.printStackTrace();
throw new ConsentPdfGenerationException("Excecption when trying to generate pdf", e);
}
byte[] pdfBytes = pdfOutputStream.toByteArray();
return pdfBytes;
}Example 21
| Project: dandelion-samples-master File: MyCustomExportClass.java View source code |
private void addTable(Document document) throws DocumentException {
PdfPCell cell = null;
// Compute the column count in order to initialize the iText table
int columnCount = table.getLastHeaderRow().getColumns(ReservedFormat.ALL, ReservedFormat.PDF).size();
if (columnCount != 0) {
PdfPTable pdfTable = new PdfPTable(columnCount);
pdfTable.setWidthPercentage(100f);
// Header
if (exportConf != null && exportConf.getIncludeHeader()) {
for (HtmlRow htmlRow : table.getHeadRows()) {
for (HtmlColumn column : htmlRow.getColumns(ReservedFormat.ALL, ReservedFormat.PDF)) {
cell = new PdfPCell();
cell.setPhrase(new Phrase(column.getContent().toString()));
pdfTable.addCell(cell);
}
}
}
for (HtmlRow htmlRow : table.getBodyRows()) {
for (HtmlColumn column : htmlRow.getColumns(ReservedFormat.ALL, ReservedFormat.PDF)) {
cell = new PdfPCell();
cell.setPhrase(new Phrase(column.getContent().toString()));
pdfTable.addCell(cell);
}
}
document.add(pdfTable);
}
}Example 22
| Project: fi-smp-master File: PdfGen.java View source code |
private void createPage(com.itextpdf.text.Document document, ElmoDocument doc) throws DocumentException {
Paragraph p = new Paragraph();
p.add(new Phrase("Transcript for " + doc.getPersonName() + " (" + doc.getBirthday() + ")", FONT_HEADING));
document.add(p);
p = new Paragraph();
p.add(new Phrase("Institution: " + doc.getInstitutionName(), FONT_BOLD));
document.add(p);
p = new Paragraph();
p.add(new Phrase(" "));
document.add(p);
PdfPTable table = new PdfPTable(new float[] { 15, 30, 15, 10, 10, 8, 8 });
table.setWidthPercentage(100);
table.addCell(createHeaderCell("Code"));
table.addCell(createHeaderCell("Title"));
table.addCell(createHeaderCell("Level"));
table.addCell(createHeaderCell("Type"));
table.addCell(createHeaderCell("Credits"));
table.addCell(createHeaderCell("Result"));
table.addCell(createHeaderCell("Date"));
for (ElmoResult res : doc.getResults()) {
table.addCell(createCell(res.getCode()));
table.addCell(createCell(res.getName()));
table.addCell(createCell(res.getLevel()));
table.addCell(createCell(res.getType()));
table.addCell(createCell(res.getCredits()));
table.addCell(createCell(res.getResult()));
table.addCell(createCell(res.getDate()));
}
document.add(table);
}Example 23
| Project: HUSACCT-master File: PDFReportWriter.java View source code |
private void createTable() throws DocumentException {
Phrase title = new Phrase();
title.setFont(new Font(FontFamily.HELVETICA, 13F, Font.BOLD, BaseColor.BLUE));
title.add("Violations");
document.add(new Paragraph(title));
document.add(new Paragraph(" "));
PdfPTable pdfTable = new PdfPTable(report.getLocaleColumnHeaders().length);
pdfTable.setWidths(new int[] { 3, 4, 1, 2, 2, 1 });
pdfTable.setWidthPercentage(100);
for (String columnHeader : report.getLocaleColumnHeaders()) {
addCellToTable(pdfTable, columnHeader, BaseColor.GRAY, true);
}
for (Violation violation : report.getViolations().getValue()) {
// Source
if (violation.getClassPathFrom() != null && !violation.getClassPathFrom().trim().equals("")) {
addCellToTable(pdfTable, violation.getClassPathFrom(), BaseColor.WHITE, false);
} else {
addCellToTable(pdfTable, "", BaseColor.WHITE, false);
}
// Rule
String message = taskServiceImpl.getMessage(violation);
if (message != null) {
addCellToTable(pdfTable, message, BaseColor.WHITE, false);
} else {
addCellToTable(pdfTable, "", BaseColor.WHITE, false);
}
// LineNumber
if (!(violation.getLinenumber() == 0)) {
addCellToTable(pdfTable, "" + violation.getLinenumber(), BaseColor.WHITE, false);
} else {
addCellToTable(pdfTable, "", BaseColor.WHITE, false);
}
// DependencyKind
if (violation.getViolationTypeKey() != null) {
addCellToTable(pdfTable, getDependencyKindValue(violation.getViolationTypeKey(), violation.getIsIndirect()), BaseColor.WHITE, false);
} else {
addCellToTable(pdfTable, "", BaseColor.WHITE, false);
}
// Target
if (violation.getClassPathFrom() != null && !violation.getClassPathFrom().trim().equals("")) {
addCellToTable(pdfTable, violation.getClassPathTo(), BaseColor.WHITE, false);
} else {
addCellToTable(pdfTable, "", BaseColor.WHITE, false);
}
// Severity
if (violation.getSeverity() != null) {
addCellToTable(pdfTable, "" + violation.getSeverity().getSeverityKeyTranslated(), BaseColor.WHITE, false);
} else {
addCellToTable(pdfTable, "", BaseColor.WHITE, false);
}
}
document.add(pdfTable);
}Example 24
| Project: passtab-master File: PDFOutput.java View source code |
private void createPDF(OutputStream out, String[][] array) throws IOException, DocumentException {
Document document = new Document(PageSize.LETTER.rotate());
PdfWriter.getInstance(document, out);
document.open();
PdfPTable table = new PdfPTable(array[0].length);
table.setTotalWidth((float) array.length * PDFOutput.CELL_WIDTH);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
addCell(table, array[i][j], (j % 2) != 0, (i % 2) != 0, j == 0, i == 0);
}
}
document.add(table);
document.close();
}Example 25
| Project: amos-ss15-proj3-master File: MatrixTools.java View source code |
/**
* /**
* saves matrix to {@code path} in pdf format
* @param matrix matrix to save
* @param path file where matrix will be saved
*/
public static boolean SaveMatrixToPdf(RequirementsTraceabilityMatrixByImpact matrix, File path, String matrixTitle) {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(path));
document.open();
document.addTitle(matrixTitle);
Paragraph headerPar = new Paragraph("Traceability Matrix");
//new line
headerPar.add(new Paragraph(" "));
document.add(headerPar);
java.util.List<String> reqs = matrix.getRequirements();
//table setup
//reqs + "file name" col
PdfPTable table = new PdfPTable(reqs.size() + 1);
table.setHeaderRows(1);
table.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
table.setWidthPercentage(100);
table.setSpacingBefore(0);
table.setSpacingAfter(0);
//file name col width/req col width 4:1
float[] widths = new float[reqs.size() + 1];
widths[0] = 4;
for (int i = 0; i < reqs.size(); i++) {
widths[i + 1] = 1;
}
table.setWidths(widths);
//header row
//add filename col to header
addCell(table, "File name", 10, Element.ALIGN_LEFT);
//add req cols to header
for (String req : reqs) {
addCell(table, "req-" + req, 8, Element.ALIGN_CENTER);
}
//content, row by row:
for (int i = 0; i < matrix.getFiles().size(); i++) {
//filename col
String fileName = matrix.getFiles().get(i);
addCell(table, fileName, 5, Element.ALIGN_LEFT, 18);
//impact value cols
for (String req : reqs) {
RequirementFileImpactValue value = matrix.getImpactValue(new RequirementFilePair(req, fileName));
if (value == null) {
value = new RequirementFileImpactValue(0);
}
//round
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
String valString = df.format(value.getImpactPercentage());
addCell(table, valString, 10, Element.ALIGN_CENTER);
}
}
document.add(table);
} catch (DocumentExceptionFileNotFoundException | e) {
e.printStackTrace();
return false;
} finally {
document.close();
}
return true;
}Example 26
| Project: kagura-master File: ExportHandler.java View source code |
/**
* Takes the output and transforms it into a PDF file.
* @param out Output stream.
* @param rows Rows of data from reporting-core
* @param columns Columns to list on report
*/
public void generatePdf(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) {
try {
Document document = new Document();
PdfWriter.getInstance(document, out);
if (columns == null) {
if (rows.size() > 0)
return;
columns = new ArrayList<ColumnDef>(CollectionUtils.collect(rows.get(0).keySet(), new Transformer() {
@Override
public Object transform(final Object input) {
return new ColumnDef() {
{
setName((String) input);
}
};
}
}));
}
if (columns.size() > 14)
document.setPageSize(PageSize.A1);
else if (columns.size() > 10)
document.setPageSize(PageSize.A2);
else if (columns.size() > 7)
document.setPageSize(PageSize.A3);
else
document.setPageSize(PageSize.A4);
document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL, BaseColor.BLACK);
Font headerFont = FontFactory.getFont(FontFactory.COURIER, 8, Font.BOLD, BaseColor.BLACK);
int size = columns.size();
PdfPTable table = new PdfPTable(size);
for (ColumnDef column : columns) {
PdfPCell c1 = new PdfPCell(new Phrase(column.getName(), headerFont));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
}
table.setHeaderRows(1);
if (rows != null)
for (Map<String, Object> row : rows) {
for (ColumnDef column : columns) {
table.addCell(new Phrase(String.valueOf(row.get(column.getName())), font));
}
}
document.add(table);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}Example 27
| Project: opencirm-master File: PDFViewReport.java View source code |
public void onEndPage(PdfWriter writer, Document d) {
float cellHeight = d.topMargin();
Rectangle page = d.getPageSize();
PdfPTable head = new PdfPTable(1);
head.setTotalWidth(page.getWidth());
PdfPCell c = new PdfPCell(new Phrase(getTitle(), bigBoldFont));
c.setHorizontalAlignment(Element.ALIGN_CENTER);
c.setFixedHeight(cellHeight);
c.setBorder(PdfPCell.NO_BORDER);
head.addCell(c);
float temp = page.getHeight() - cellHeight + head.getTotalHeight();
head.writeSelectedRows(0, -1, 0, temp, writer.getDirectContent());
head = new PdfPTable(1);
head.setTotalWidth(page.getWidth());
c = new PdfPCell(new Phrase(getTime(), bigNormalFont));
c.setHorizontalAlignment(Element.ALIGN_CENTER);
c.setFixedHeight(cellHeight);
c.setBorder(PdfPCell.NO_BORDER);
head.addCell(c);
//table header requires absolute positioning
head.writeSelectedRows(0, -1, 0, temp - 15, writer.getDirectContent());
}Example 28
| Project: Openfire-master File: EmailSenderUtility.java View source code |
public void createPdfAttachment(OutputStream outputStream) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, outputStream);
document.open();
document.addTitle("Monitoring Report");
document.addSubject("PDF Document");
document.addKeywords("iText, email");
document.addAuthor("JMX");
document.addCreator("JMX");
Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
//Make the Get call to get the data from Jolokia endpoint.
HttpClient httpClient = new HttpClient();
String monData = httpClient.getMemoryData();
Log.info("Monitoring Data JSON:" + monData);
//Converting json string to java object for easy manipulation.
Map outNode = new Genson().deserialize(monData, Map.class);
Map requestNode = (Map) outNode.get("request");
Map valueNode = (Map) outNode.get("value");
HashMap<String, String> monitoringData = new HashMap<String, String>();
monitoringData.put("Current Date", date.toString());
monitoringData.put("Report Date", outNode.get("timestamp").toString());
monitoringData.put("Maximum Heap Memory", valueNode.get("max").toString());
monitoringData.put("Committed Heap Memory", valueNode.get("committed").toString());
monitoringData.put("Init Heap Memory", valueNode.get("init").toString());
monitoringData.put("Used Heap Memory", valueNode.get("used").toString());
Font boldFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
PdfPTable table = new PdfPTable(2);
table.setSpacingBefore(5);
table.addCell(new Phrase("Monitor", boldFont));
table.addCell(new Phrase("Value", boldFont));
for (Map.Entry<String, String> entry : monitoringData.entrySet()) {
table.addCell(entry.getKey());
System.out.println(entry.getKey());
if (entry.getValue() != "" && entry.getValue() != null) {
table.addCell(entry.getValue());
System.out.println(entry.getValue());
} else {
table.addCell("NOT AVAILABLE");
}
}
table.setHorizontalAlignment(Element.ALIGN_CENTER);
document.add(table);
document.close();
}Example 29
| Project: PDFAInspector-master File: TableWrapper.java View source code |
/**
* Creates a new PdfPTable based on the info assembled
* in the table stub.
* @return a PdfPTable
*/
public PdfPTable createTable() {
// no rows = simplest table possible
if (rows.isEmpty())
return new PdfPTable(1);
// how many columns?
int ncol = 0;
for (PdfPCell pc : rows.get(0)) {
ncol += pc.getColspan();
}
PdfPTable table = new PdfPTable(ncol);
// table width
String width = styles.get(HtmlTags.WIDTH);
if (width == null)
table.setWidthPercentage(100);
else {
if (width.endsWith("%"))
table.setWidthPercentage(Float.parseFloat(width.substring(0, width.length() - 1)));
else {
table.setTotalWidth(Float.parseFloat(width));
table.setLockedWidth(true);
}
}
// horizontal alignment
String alignment = styles.get(HtmlTags.ALIGN);
int align = Element.ALIGN_LEFT;
if (alignment != null) {
align = HtmlUtilities.alignmentValue(alignment);
}
table.setHorizontalAlignment(align);
// column widths
try {
if (colWidths != null)
table.setWidths(colWidths);
} catch (Exception e) {
}
// add the cells
for (List<PdfPCell> col : rows) {
for (PdfPCell pc : col) {
table.addCell(pc);
}
}
return table;
}Example 30
| Project: saga-master File: PdfReporter.java View source code |
private PdfPTable createTable(final TestRunCoverageStatistics runStats) throws DocumentException { final PdfPTable table = new PdfPTable(4); table.setSpacingBefore(10); table.setSpacingAfter(10); table.setWidthPercentage(100); table.setHeaderRows(1); table.setWidths(new int[] { 70, 10, 10, 10 }); addHeader(table); addTotalRow(runStats, table); addFileStatsRows(runStats, table); return table; }
Example 31
| Project: Trainings-master File: ExportStatController.java View source code |
private boolean addVisitingTrainings(Document document, User user, int chapterNumber, com.itextpdf.text.List summaryContent) throws DocumentException {
List<Training> trainings;
if (user.getRole() == UserRole.EXTERNAL_VISITOR)
trainings = ((ExternalVisitor) user).getVisitingTrainings();
else if (user.getRole() == UserRole.EMPLOYEE)
trainings = ((Employee) user).getVisitingTrainings();
else
return false;
document.newPage();
Anchor anchor = new Anchor("Visiting trainings", catFont);
anchor.setName("Visiting trainings");
Chapter chapter = new Chapter(new Paragraph(anchor), chapterNumber);
Paragraph emptyLine = new Paragraph();
addEmptyLine(emptyLine, 1);
chapter.add(emptyLine);
List<String> headers = Arrays.asList("Name", "Absences", "All");
PdfPTable trainingsTable = createTableWithHeader(headers);
chapter.add(trainingsTable);
List<String> absenceHeaders = Arrays.asList("Day", "Absence reason");
int allAbsenceCount = 0;
int lecturesCount = 0;
for (Training training : trainings) {
List<String> trainingDays = new ArrayList<>();
List<String> trainingReasons = new ArrayList<>();
List<Entry> entries = entryService.getAllEntriesByTrainingId(training.getId());
int absentCount = 0;
for (Entry entry : entries) {
Absentee absentee = absenteeService.getAbsentee(user.getId(), entry.getId());
if (absentee != null) {
absentCount++;
trainingDays.add(dateFormat.format(entry.getBeginTime()));
trainingReasons.add(absentee.getReason());
}
}
lecturesCount += entries.size();
allAbsenceCount += absentCount;
if (absentCount > 0) {
Paragraph paragraph = new Paragraph(training.getName(), subFont);
addEmptyLine(paragraph, 1);
Section subSection = chapter.addSection(paragraph);
PdfPTable absenceTable = createTableWithHeader(absenceHeaders);
for (int j = 0; j < trainingDays.size(); j++) {
absenceTable.addCell(trainingDays.get(j));
absenceTable.addCell(trainingReasons.get(j));
}
subSection.add(absenceTable);
}
trainingsTable.addCell(training.getName());
trainingsTable.addCell(String.valueOf(absentCount));
trainingsTable.addCell(String.valueOf(entries.size()));
}
double percent = (double) allAbsenceCount / lecturesCount * 100;
summaryContent.add(new ListItem("Lectures attended: " + lecturesCount));
summaryContent.add(new ListItem("Lectures skipped: " + allAbsenceCount + " (" + doubleFormat.format(percent) + "%)"));
document.add(chapter);
return true;
}Example 32
| Project: transgalactica-master File: ITextFicheSalairePdfItemWriter.java View source code |
private void addElementsSalaire(Document document, SalaireTo salaire) throws DocumentException {
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
table.setWidths(new float[] { 65, 35 });
table.setExtendLastRow(true);
table.setRunDirection(rundirection);
table.setHeaderRows(2);
table.setFooterRows(1);
table.getDefaultCell().setPaddingTop(5);
table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(new Phrase(getMessage("message.element.titreDetail"), textFont));
table.addCell(new Phrase(getMessage("message.element.titreMontant"), textFont));
table.getDefaultCell().setBackgroundColor(null);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(new Phrase(getMessage("message.element.total"), emphaseFont));
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(new Phrase(salaire.getSalaire().toString(), emphaseFont));
// detail des elements de salaire
table.getDefaultCell().setBorder(Rectangle.LEFT | Rectangle.RIGHT);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(new Phrase(getMessage("message.element.salaire"), textFont));
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(new Phrase(salaire.getSalaireBase().toString(), textFont));
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(new Phrase(getMessage("message.element.anciennete"), textFont));
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(new Phrase(salaire.getPrimeAnciennete().toString(), textFont));
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(new Phrase(getMessage("message.element.experience"), textFont));
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(new Phrase(salaire.getPrimeExperience().toString(), textFont));
document.add(table);
}Example 33
| Project: wgen-iText-master File: HTMLWorker.java View source code |
public void endElement(String tag) {
if (!tagsSupported.contains(tag))
return;
try {
String follow = FactoryProperties.followTags.get(tag);
if (follow != null) {
cprops.removeChain(follow);
return;
}
if (tag.equals("font") || tag.equals("span")) {
cprops.removeChain(tag);
return;
}
if (tag.equals("a")) {
if (currentParagraph == null) {
currentParagraph = new Paragraph();
}
boolean skip = false;
if (interfaceProps != null) {
ALink i = (ALink) interfaceProps.get("alink_interface");
if (i != null)
skip = i.process(currentParagraph, cprops);
}
if (!skip) {
String href = cprops.getProperty("href");
if (href != null) {
for (Chunk ck : currentParagraph.getChunks()) {
ck.setAnchor(href);
}
}
}
Paragraph tmp = (Paragraph) stack.pop();
Phrase tmp2 = new Phrase();
tmp2.add(currentParagraph);
tmp.add(tmp2);
currentParagraph = tmp;
cprops.removeChain("a");
return;
}
if (tag.equals("br")) {
return;
}
if (currentParagraph != null) {
if (stack.empty())
document.add(currentParagraph);
else {
Element obj = stack.pop();
if (obj instanceof TextElementArray) {
TextElementArray current = (TextElementArray) obj;
current.add(currentParagraph);
}
stack.push(obj);
}
}
currentParagraph = null;
if (tag.equals(HtmlTags.UNORDEREDLIST) || tag.equals(HtmlTags.ORDEREDLIST)) {
if (pendingLI)
endElement(HtmlTags.LISTITEM);
skipText = false;
cprops.removeChain(tag);
if (stack.empty())
return;
Element obj = stack.pop();
if (!(obj instanceof com.itextpdf.text.List)) {
stack.push(obj);
return;
}
if (stack.empty())
document.add(obj);
else
((TextElementArray) stack.peek()).add(obj);
return;
}
if (tag.equals(HtmlTags.LISTITEM)) {
pendingLI = false;
skipText = true;
cprops.removeChain(tag);
if (stack.empty())
return;
Element obj = stack.pop();
if (!(obj instanceof ListItem)) {
stack.push(obj);
return;
}
if (stack.empty()) {
document.add(obj);
return;
}
Element list = stack.pop();
if (!(list instanceof com.itextpdf.text.List)) {
stack.push(list);
return;
}
ListItem item = (ListItem) obj;
((com.itextpdf.text.List) list).add(item);
ArrayList<Chunk> cks = item.getChunks();
if (!cks.isEmpty())
item.getListSymbol().setFont(cks.get(0).getFont());
stack.push(list);
return;
}
if (tag.equals("div") || tag.equals("body")) {
cprops.removeChain(tag);
return;
}
if (tag.equals(HtmlTags.PRE)) {
cprops.removeChain(tag);
isPRE = false;
return;
}
if (tag.equals("p")) {
cprops.removeChain(tag);
return;
}
if (tag.equals("h1") || tag.equals("h2") || tag.equals("h3") || tag.equals("h4") || tag.equals("h5") || tag.equals("h6")) {
cprops.removeChain(tag);
return;
}
if (tag.equals("table")) {
if (pendingTR)
endElement("tr");
cprops.removeChain("table");
IncTable table = (IncTable) stack.pop();
PdfPTable tb = table.buildTable();
tb.setSplitRows(true);
if (stack.empty())
document.add(tb);
else
((TextElementArray) stack.peek()).add(tb);
boolean state[] = tableState.pop();
pendingTR = state[0];
pendingTD = state[1];
skipText = false;
return;
}
if (tag.equals("tr")) {
if (pendingTD)
endElement("td");
pendingTR = false;
cprops.removeChain("tr");
ArrayList<PdfPCell> cells = new ArrayList<PdfPCell>();
ArrayList<Float> fixedCellwidths = new ArrayList<Float>();
IncTable table = null;
while (true) {
Element obj = stack.pop();
if (obj instanceof IncCell) {
IncCell newCell = (IncCell) obj;
fixedCellwidths.add(newCell.getFixedWidth());
cells.add(newCell.getCell());
}
if (obj instanceof IncTable) {
table = (IncTable) obj;
break;
}
}
table.addFixedCellWidths(fixedCellwidths);
table.addCols(cells);
table.endRow();
stack.push(table);
skipText = true;
return;
}
if (tag.equals("td") || tag.equals("th")) {
pendingTD = false;
cprops.removeChain("td");
skipText = true;
return;
}
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}Example 34
| Project: wildrank-desktop-master File: PDFWriter.java View source code |
public PdfPTable createTable(PDFType type) throws IOException { progress.setValue(0); progress.setMaximum(1); // a table with two columns PdfPTable table = new PdfPTable(4); // List all our notes files File notesFolder = new File(FileUtilities.getSyncedDirectory() + File.separator + "notes"); File pitFolder = new File(FileUtilities.getNonsyncedDirectory() + File.separator + "pittexts"); Logger.getInstance().log("Folder path: " + pitFolder.getAbsolutePath()); List<File> pitFiles = new ArrayList<File>(); FileUtilities.listFilesInDirectory(pitFolder, pitFiles); if (type == PDFType.TYPE_PIT || type == PDFType.TYPE_ALL) { for (File file : pitFiles) { table.addCell(teamCell(file)); boolean sisterFound = false; if (type == PDFType.TYPE_ALL) { List<File> otherFiles = new ArrayList<File>(); FileUtilities.listFilesInDirectory(notesFolder, otherFiles); for (File otherFile : otherFiles) { if (getTeam(file).equals(getTeam(otherFile))) { sisterFound = true; teamsDone.add(getTeam(otherFile)); table.addCell(dataCell(otherFile, file, type)); } } } if (!sisterFound) { table.addCell(dataCell(null, file, type)); } } } if (type == PDFType.TYPE_NOTES || type == PDFType.TYPE_ALL) { List<File> otherFiles = new ArrayList<File>(); FileUtilities.listFilesInDirectory(notesFolder, otherFiles); for (File otherFile : otherFiles) { boolean found = false; if (type == PDFType.TYPE_ALL) { for (int i = 0; i < teamsDone.size(); i++) { if (getTeam(otherFile).equals(teamsDone.get(i))) { found = true; } } } if (!found) { table.addCell(teamCell(otherFile)); table.addCell(dataCell(otherFile, null, type)); } } } return table; }
Example 35
| Project: yaqp-turbo-master File: Algorithm.java View source code |
@Override
public PDFObject getPDF() {
PDFObject pdf = new PDFObject();
pdf.setPdfTitle(getMeta().identifier);
pdf.setPdfKeywords(getMeta().subject);
Paragraph p1 = new Paragraph(new Chunk("OpenTox - Algorithm Report\n\n", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 14)));
pdf.addElement(p1);
try {
PdfPTable table = new PdfPTable(2);
table.setWidths(new int[] { 10, 50 });
PdfPCell cell = new PdfPCell(new Paragraph("Algorithm Presentation - General"));
cell.setColspan(2);
cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));
table.addCell(cell);
table.addCell("Name");
table.addCell(getMeta().getName());
table.addCell("Title");
table.addCell(getMeta().title);
table.addCell("Subject");
table.addCell(getMeta().subject);
table.addCell("Description");
table.addCell(getMeta().description);
table.addCell("Identifier");
table.addCell(getMeta().identifier);
pdf.addElement(table);
pdf.addElement(new Paragraph("\n\n\n"));
table = new PdfPTable(2);
table.setWidths(new int[] { 10, 50 });
cell = new PdfPCell(new Paragraph("General Meta Information"));
cell.setColspan(2);
cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));
table.addCell(cell);
table.addCell("Type");
table.addCell(getMeta().type);
table.addCell("Creator");
table.addCell(getMeta().creator);
table.addCell("Publisher");
table.addCell(getMeta().publisher);
table.addCell("Relation");
table.addCell(getMeta().relation);
table.addCell("Rights");
table.addCell(getMeta().rights);
table.addCell("Source");
table.addCell(getMeta().source);
table.addCell("Provenance");
table.addCell(getMeta().provenance);
table.addCell("Contributor");
table.addCell(getMeta().contributor);
table.addCell("Language");
table.addCell(getMeta().language.getDisplayLanguage());
table.addCell("Created on");
table.addCell(getMeta().date.toString());
table.addCell("Formats");
ArrayList<MediaType> listMedia = getMeta().format;
String formatTableEntry = "";
for (int i = 0; i < listMedia.size(); i++) {
formatTableEntry += listMedia.get(i).toString();
if (i < listMedia.size() - 1) {
formatTableEntry += "\n";
}
}
table.addCell(formatTableEntry);
table.addCell("Audience");
ArrayList<Audience> audiences = getMeta().audience;
String auds = "";
for (int i = 0; i < audiences.size(); i++) {
auds += audiences.get(i).getName();
if (i < audiences.size() - 1) {
auds += "\n";
}
}
table.addCell(auds);
pdf.addElement(table);
pdf.addElement(new Paragraph("\n\n\n"));
table = new PdfPTable(4);
table.setWidths(new int[] { 30, 30, 30, 30 });
cell = new PdfPCell(new Paragraph("Algorithm Parameters"));
cell.setColspan(4);
cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));
table.addCell(cell);
table.addCell("Parameter Name");
table.addCell("XSD DataType");
table.addCell("Default Value");
table.addCell("Scope");
Map<String, AlgorithmParameter> algParameters = getMeta().getParameters();
Set<Entry<String, AlgorithmParameter>> entrySet = algParameters.entrySet();
for (Entry e : entrySet) {
String pName = (String) e.getKey();
AlgorithmParameter ap = (AlgorithmParameter) e.getValue();
table.addCell(pName);
table.addCell(ap.dataType.getURI());
table.addCell(ap.paramValue.toString());
table.addCell(ap.paramScope.toString());
}
pdf.addElement(table);
pdf.addElement(new Paragraph("\n\n\n"));
table = new PdfPTable(1);
cell = new PdfPCell(new Paragraph("Ontologies"));
cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));
table.addCell(cell);
OTAlgorithmTypes type = getMeta().getAlgorithmType();
table.addCell(type.getURI());
Set<Resource> superOntologies = type.getSuperEntities();
Iterator<Resource> it = superOntologies.iterator();
while (it.hasNext()) {
table.addCell(it.next().getURI());
}
pdf.addElement(table);
} catch (final DocumentException ex) {
YaqpLogger.LOG.log(new Warning(getClass(), "XCF316 - Pdf Exception :" + ex.toString()));
}
return pdf;
}Example 36
| Project: aidGer-master File: BalanceReportConverter.java View source code |
/*
* (non-Javadoc)
*
* @see
* com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(com.itextpdf
* .text.pdf.PdfWriter, com.itextpdf.text.Document)
*/
@Override
public void onStartPage(PdfWriter writer, Document document) {
PdfPTable table = new PdfPTable(3);
table.setTotalWidth(writer.getPageSize().getRight() - document.rightMargin() - document.leftMargin());
try {
Font pageTitleFont = new Font(BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 18);
Font authorNameFont = new Font(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 8);
PdfPCell left = new PdfPCell();
PdfPCell center;
if (writer.getCurrentPageNumber() == 1) {
center = new PdfPCell(new Phrase(name, pageTitleFont));
} else {
center = new PdfPCell(new Phrase(""));
}
center.setHorizontalAlignment(Element.ALIGN_CENTER);
center.setVerticalAlignment(Element.ALIGN_BOTTOM);
center.setBorder(Rectangle.BOTTOM);
PdfPCell right = new PdfPCell(new Phrase(_("Author") + ": " + Runtime.getInstance().getOption("name"), authorNameFont));
right.setVerticalAlignment(Element.ALIGN_TOP);
right.setHorizontalAlignment(Element.ALIGN_RIGHT);
left.setBorder(0);
center.setBorder(0);
right.setBorder(0);
left.setPaddingBottom(10);
center.setPaddingBottom(10);
right.setPaddingBottom(10);
table.addCell(left);
table.addCell(center);
table.addCell(right);
table.writeSelectedRows(0, -1, document.leftMargin(), document.getPageSize().getTop() - 15, writer.getDirectContent());
} catch (DocumentException e1) {
} catch (IOException e1) {
e1.printStackTrace();
}
}Example 37
| Project: BrewShopApp-master File: PdfRecipeWriter.java View source code |
private void addRecipeInfo(Document document) throws DocumentException {
int iconRes = mRecipe.getStyle().getIconDrawable();
Image image = loadDrawable(iconRes, 40);
Paragraph namePara = new Paragraph();
namePara.setSpacingBefore(0);
namePara.add(new Phrase(mRecipe.getName() + "\n", HEADER_FONT));
namePara.add(new Phrase("\n", new Font(Font.FontFamily.TIMES_ROMAN, 2)));
namePara.add(new Phrase(mRecipe.getStyle().getDisplayName(), SMALL_FONT));
PdfPTable table = new PdfPTable(new float[] { 50, 400 });
table.setHorizontalAlignment(Element.ALIGN_LEFT);
PdfPCell cellOne = new PdfPCell(image);
cellOne.setBorder(Rectangle.NO_BORDER);
PdfPCell cellTwo = new PdfPCell(namePara);
cellTwo.setBorder(Rectangle.NO_BORDER);
table.addCell(cellOne);
table.addCell(cellTwo);
document.add(table);
addLineSeparator(document);
Paragraph setupPara = new Paragraph();
setupPara.add(new Phrase("Batch Volume: " + mConverter.fromGallonsWithUnits(mRecipe.getBatchVolume(), 1), NORMAL_FONT));
setupPara.add(new Phrase("\n\n", SPACING_FONT));
setupPara.add(new Phrase("Boil Volume: " + mConverter.fromGallonsWithUnits(mRecipe.getBoilVolume(), 1), NORMAL_FONT));
setupPara.add(new Phrase("\n\n", SPACING_FONT));
setupPara.add(new Phrase("Boil Time: " + Util.fromDouble(mRecipe.getBoilTime(), 0) + " minutes", NORMAL_FONT));
setupPara.add(new Phrase("\n\n", SPACING_FONT));
setupPara.add(new Phrase("Efficiency: " + Util.fromDouble(mRecipe.getEfficiency(), 1) + "%", NORMAL_FONT));
Paragraph para = new Paragraph();
String og = "";
switch(mSettings.getExtractUnits()) {
case SPECIFIC_GRAVITY:
og = Util.fromDouble(mRecipe.getOg(), 3, false);
break;
case DEGREES_PLATO:
og = Util.fromDouble(mRecipe.getOgPlato(), 1, false) + "°P";
break;
}
para.add(new Phrase("OG: " + og, NORMAL_FONT));
para.add(new Phrase("\n\n", SPACING_FONT));
para.add(new Phrase("IBU: " + Util.fromDouble(mRecipe.getTotalIbu(), 1), NORMAL_FONT));
para.add(new Phrase("\n\n", SPACING_FONT));
para.add(new Phrase("SRM: " + Util.fromDouble(mRecipe.getSrm(), 1), NORMAL_FONT));
para.add(new Phrase("\n\n", SPACING_FONT));
String fg = "n/a";
if (mRecipe.hasYeast()) {
switch(mSettings.getExtractUnits()) {
case SPECIFIC_GRAVITY:
fg = Util.fromDouble(mRecipe.getFg(), 3, false);
break;
case DEGREES_PLATO:
fg = Util.fromDouble(mRecipe.getFgPlato(), 1, false) + "°P";
break;
}
}
para.add(new Phrase("Estimated FG: " + fg, NORMAL_FONT));
para.add(new Phrase("\n\n", SPACING_FONT));
String abv = "n/a";
if (mRecipe.hasYeast()) {
abv = Util.fromDouble(mRecipe.getAbv(), 1) + "%";
}
para.add(new Phrase("Estimated ABV: " + abv, NORMAL_FONT));
PdfPTable statsTable = new PdfPTable(new float[] { 200, 200 });
statsTable.setHorizontalAlignment(Element.ALIGN_LEFT);
PdfPCell statsCellOne = new PdfPCell(para);
statsCellOne.setBorder(Rectangle.NO_BORDER);
PdfPCell statsCellTwo = new PdfPCell(setupPara);
statsCellTwo.setBorder(Rectangle.NO_BORDER);
statsTable.addCell(statsCellOne);
statsTable.addCell(statsCellTwo);
document.add(statsTable);
}Example 38
| Project: controlalumno-master File: PdfManager.java View source code |
// crea un pdf con todo el formato de un alumno
public static void crearPdfAlumno(Context context, Curso curso, Alumno alumno) {
try {
mContext = context;
unicode = BaseFont.createFont(fontFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
catFont = new Font(unicode, 22, Font.BOLD, BaseColor.BLACK);
subFont = new Font(unicode, 16, Font.BOLD, BaseColor.BLACK);
smallBold = new Font(unicode, 12, Font.BOLD, BaseColor.BLACK);
smallFont = new Font(unicode, 12, Font.NORMAL, BaseColor.BLACK);
italicFont = new Font(unicode, 12, Font.ITALIC, BaseColor.BLACK);
italicFontBold = new Font(unicode, 12, Font.ITALIC | Font.BOLD, BaseColor.BLACK);
String fullFileName = createDirectoryAndFileName(alumno.getNombre());
if (fullFileName.length() > 0) {
// /////////////////////
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(fullFileName));
document.open();
document.addTitle(context.getResources().getString(R.string.pdf_titulo) + alumno.getNombre());
document.addSubject(context.getResources().getString(R.string.pdf_asunto));
document.addKeywords(context.getResources().getString(R.string.pdf_keywords) + alumno.getNombre());
document.addAuthor(Properties.getMail());
document.addCreator(Properties.getMail());
// /////////////////////
Bitmap bitMap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitMap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
byte[] bitMapData = stream.toByteArray();
Image image = Image.getInstance(bitMapData);
image.setAbsolutePosition(400f, 650f);
document.add(image);
// /////////////////////
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
preface.add(new Paragraph(alumno.getNombre(), catFont));
preface.add(new Paragraph(context.getResources().getString(R.string.pdf_curso) + curso.getCurso(), italicFont));
preface.add(new Paragraph(context.getResources().getString(R.string.pdf_fecha) + new Date().toString(), italicFont));
preface.add(new Paragraph(context.getResources().getString(R.string.pdf_nota_maxima) + alumno.getNotaMax(), smallFont));
preface.add(new Paragraph(context.getResources().getString(R.string.pdf_nota_minima) + alumno.getNotaMin(), smallFont));
preface.add(new Paragraph(context.getResources().getString(R.string.pdf_estado) + alumno.getEstado(), smallFont));
preface.add(new Paragraph(context.getResources().getString(R.string.pdf_promedio) + alumno.getPromedio(), smallFont));
addEmptyLine(preface, 1);
document.add(preface);
// /////////////////////
Paragraph paragraph = new Paragraph();
int TABLE_COLUMNS = 3;
PdfPTable table = new PdfPTable(TABLE_COLUMNS);
float[] columnWidths = new float[] { 80f, 200f, 230f };
table.setWidths(columnWidths);
table.setWidthPercentage(100);
// Definimos los tÃtulos para cada una de las 5 columnas
PdfPCell cell = new PdfPCell(new Phrase(context.getResources().getString(R.string.pdf_nota), smallBold));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase(context.getResources().getString(R.string.pdf_fecha1), smallBold));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase(context.getResources().getString(R.string.pdf_anotacion), smallBold));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
// Creamos la fila de la tabla con las cabeceras
table.setHeaderRows(1);
// Creamos las lineas con los artÃculos de la factura;
for (int i = 0; i < alumno.getHistorial().getNotas().length; i++) {
PdfPCell cell1 = new PdfPCell();
cell1.setPhrase(new Phrase(alumno.getHistorial().getNotas()[i].getNota() + "", smallFont));
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell1);
cell1.setPhrase(new Phrase(alumno.getHistorial().getNotas()[i].getFecha().toString(), smallFont));
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell1);
cell1.setPhrase(new Phrase(alumno.getHistorial().getNotas()[i].getAnotacion(), smallFont));
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell1);
}
paragraph.add(table);
document.add(paragraph);
// /////////////////////
document.close();
Toast.makeText(mContext, context.getResources().getString(R.string.pdf_toast), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}Example 39
| Project: mouseinventory-master File: PdfServlet.java View source code |
private Element getMouseListPdf(HttpServletRequest request) throws Exception {
int holderID = stringToInt(request.getParameter("holder_id"));
int geneID = stringToInt(request.getParameter("geneID"));
int mouseTypeID = stringToInt(request.getParameter("mousetype_id"));
int creOnly = stringToInt(request.getParameter("creonly"));
int facilityID = stringToInt(request.getParameter("facility_id"));
int offset = -1;
int limit = -1;
String orderBy = request.getParameter("orderby");
String searchTerms = request.getParameter("searchterms");
String status = request.getParameter("status");
if (orderBy == null || orderBy.isEmpty()) {
orderBy = "mouse.name";
}
if (status == null) {
status = "all";
}
if (status == "all" && !request.isUserInRole("administrator")) {
throw new Exception("You must be an administrator to view all mouse records");
}
if (creOnly < 0) {
creOnly = 0;
}
Holder holder = DBConnect.getHolder(holderID);
Gene gene = DBConnect.getGene(geneID);
Facility facility = DBConnect.getFacility(facilityID);
ArrayList<MouseRecord> mice = DBConnect.getMouseRecords(mouseTypeID, orderBy, holderID, geneID, status, searchTerms, false, creOnly, facilityID, limit, offset);
ArrayList<MouseType> mouseTypes = DBConnect.getMouseTypes();
String mouseTypeStr = "Listing";
String mouseCountStr = "";
if (mouseTypeID != -1) {
for (MouseType type : mouseTypes) {
if (type.getMouseTypeID() == mouseTypeID) {
mouseTypeStr += " " + type.getTypeName();
break;
}
}
} else {
mouseTypeStr += " all";
}
mouseCountStr = Integer.toString(mice.size()) + " records total, as of " + new Date().toString();
mouseTypeStr += " records";
if (facility != null) {
mouseTypeStr += " in facility " + facility.getFacilityName();
}
if (holder != null) {
mouseTypeStr += " held by " + holder.getFullname();
} else if (gene != null) {
mouseTypeStr += " with gene " + gene.getSymbol() + " " + gene.getFullname();
}
if (creOnly > 0) {
mouseTypeStr += " with expressed sequence type CRE";
}
if (searchTerms != null && !searchTerms.isEmpty()) {
mouseTypeStr += " matching search term '" + searchTerms + "'";
}
if (!status.equals("live") && !status.equals("all") && request.isUserInRole("administrator")) {
mouseTypeStr += " with status='" + status + "'";
}
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
table.setWidths(new int[] { 1, 5 });
for (MouseRecord mouse : mice) {
PdfPCell left = cell(getMouseNameAndNumber(mouse));
table.addCell(left);
PdfPTable subtable = new PdfPTable(2);
subtable.setWidths(new int[] { 5, 4 });
subtable.addCell(cell(getMouseCategory(mouse)));
int commentRowSpan = mouse.isIS() ? 1 : 2;
subtable.addCell(cell(getFormattedMouseComment(mouse.getGeneralComment()), commentRowSpan, 1));
if (!mouse.isIS()) {
subtable.addCell(cell(getMouseDetails(mouse)));
}
subtable.addCell(cell(getHolderList(mouse), 1, 2));
PdfPCell right = new PdfPCell(subtable);
right.setBorder(Rectangle.NO_BORDER);
table.addCell(right);
}
Phrase list = phr();
documentName = mouseTypeStr;
list.add(phr(mouseTypeStr, FONT_TITLE));
list.add(NL);
list.add(phr(mouseCountStr, FONT_BOLD));
list.add(table);
return list;
}Example 40
| Project: PortableSigner2-master File: PDFSigner.java View source code |
/** Creates a new instance of DoSignPDF */
public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password, Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment, String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin, float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException {
try {
//System.out.println("-> DoSignPDF <-");
//System.out.println("Eingabedatei: " + pdfInputFileName);
//System.out.println("Ausgabedatei: " + pdfOutputFileName);
//System.out.println("Signaturdatei: " + pkcs12FileName);
//System.out.println("Signaturblock?: " + signText);
//System.out.println("Sprache der Blocks: " + signLanguage);
//System.out.println("Signaturlogo: " + sigLogo);
System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin);
Rectangle signatureBlock;
java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);
pkcs12 = new GetPKCS12(pkcs12FileName, password);
PdfReader reader = null;
try {
// System.out.println("Password:" + ownerPassword.toString());
if (ownerPassword == null)
reader = new PdfReader(pdfInputFileName);
else
reader = new PdfReader(pdfInputFileName, ownerPassword);
} catch (IOException e) {
throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeOpened"), true, e.getLocalizedMessage());
}
FileOutputStream fout = null;
try {
fout = new FileOutputStream(pdfOutputFileName);
} catch (FileNotFoundException e) {
throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"), true, e.getLocalizedMessage());
}
PdfStamper stp = null;
try {
Date datum = new Date(System.currentTimeMillis());
int pages = reader.getNumberOfPages();
Rectangle size = reader.getPageSize(pages);
stp = PdfStamper.createSignature(reader, fout, '\0', null, true);
HashMap<String, String> pdfInfo = reader.getInfo();
// thanks to Markus Feisst
String pdfInfoProducer = "";
if (pdfInfo.get("Producer") != null) {
pdfInfoProducer = pdfInfo.get("Producer").toString();
pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")";
} else {
pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")";
}
pdfInfo.put("Producer", pdfInfoProducer);
//System.err.print("++ Producer:" + pdfInfo.get("Producer").toString());
stp.setMoreInfo(pdfInfo);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XmpWriter xmp = new XmpWriter(baos, pdfInfo);
xmp.close();
stp.setXmpMetadata(baos.toByteArray());
if (signText) {
String greet, signator, datestr, ca, serial, special, note, urn, urnvalue;
int specialcount = 0;
int sigpage;
int rightMarginPT, leftMarginPT;
float verticalPositionPT;
ResourceBundle block = ResourceBundle.getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage);
greet = block.getString("greeting");
signator = block.getString("signator");
datestr = block.getString("date");
ca = block.getString("issuer");
serial = block.getString("serial");
special = block.getString("special");
note = block.getString("note");
urn = block.getString("urn");
urnvalue = block.getString("urnvalue");
//sigcomment = block.getString(signLanguage + "-comment");
// upper y
float topy = size.getTop();
System.err.println("Top: " + topy * ptToCm);
// right x
float rightx = size.getRight();
System.err.println("Right: " + rightx * ptToCm);
if (!noExtraPage) {
sigpage = pages + 1;
stp.insertPage(sigpage, size);
// 30pt left, 30pt right, 20pt from top
rightMarginPT = 30;
leftMarginPT = 30;
verticalPositionPT = topy - 20;
} else {
if (signLastPage) {
sigpage = pages;
} else {
sigpage = 1;
}
System.err.println("Page: " + sigpage);
rightMarginPT = Math.round(rightMargin / ptToCm);
leftMarginPT = Math.round(leftMargin / ptToCm);
verticalPositionPT = topy - Math.round(verticalPos / ptToCm);
}
if (!GetPKCS12.atEgovOID.equals("")) {
specialcount = 1;
}
PdfContentByte content = stp.getOverContent(sigpage);
float[] cellsize = new float[2];
cellsize[0] = 100f;
// rightx = width of page
// 60 = 2x30 margins
// cellsize[0] = description row
// cellsize[1] = 0
// 70 = logo width
cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70;
// Pagetable = Greeting, signatureblock, comment
// sigpagetable = outer table
// consist: greetingcell, signatureblock , commentcell
PdfPTable signatureBlockCompleteTable = new PdfPTable(2);
PdfPTable signatureTextTable = new PdfPTable(2);
PdfPCell signatureBlockHeadingCell = new PdfPCell(new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12))));
signatureBlockHeadingCell.setPaddingBottom(5);
signatureBlockHeadingCell.setColspan(2);
signatureBlockHeadingCell.setBorderWidth(0f);
signatureBlockCompleteTable.addCell(signatureBlockHeadingCell);
// inner table start
// Line 1
signatureTextTable.addCell(new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
signatureTextTable.addCell(new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10))));
// Line 2
signatureTextTable.addCell(new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
signatureTextTable.addCell(new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10))));
// Line 3
signatureTextTable.addCell(new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
signatureTextTable.addCell(new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10))));
// Line 4
signatureTextTable.addCell(new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
signatureTextTable.addCell(new Paragraph(new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10))));
// Line 5
if (specialcount == 1) {
signatureTextTable.addCell(new Paragraph(new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
signatureTextTable.addCell(new Paragraph(new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10))));
}
signatureTextTable.addCell(new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
signatureTextTable.addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10))));
signatureTextTable.setTotalWidth(cellsize);
System.err.println("signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm);
// inner table end
signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
Image logo;
// System.out.println("Logo:" + sigLogo + ":");
if (sigLogo == null || "".equals(sigLogo)) {
logo = Image.getInstance(getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png"));
} else {
logo = Image.getInstance(sigLogo);
}
PdfPCell logocell = new PdfPCell();
logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
logocell.setImage(logo);
signatureBlockCompleteTable.addCell(logocell);
PdfPCell incell = new PdfPCell(signatureTextTable);
incell.setBorderWidth(0f);
signatureBlockCompleteTable.addCell(incell);
PdfPCell commentcell = new PdfPCell(new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10))));
PdfPCell notecell = new PdfPCell(new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
// commentcell.setBorderWidth(0f);
if (!sigComment.equals("")) {
signatureBlockCompleteTable.addCell(notecell);
signatureBlockCompleteTable.addCell(commentcell);
}
float[] cells = { 70, cellsize[0] + cellsize[1] };
signatureBlockCompleteTable.setTotalWidth(cells);
System.err.println("signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm);
signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT, verticalPositionPT, content);
System.err.println("signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm);
signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20, topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20);
// //////
// AcroFields af = reader.getAcroFields();
// ArrayList names = af.getSignatureNames();
// for (int k = 0; k < names.size(); ++k) {
// String name = (String) names.get(k);
// System.out.println("Signature name: " + name);
// System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name));
// System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
// PdfPKCS7 pk = af.verifySignature(name);
// X509Certificate tempsigner = pk.getSigningCertificate();
// Calendar cal = pk.getSignDate();
// Certificate pkc[] = pk.getCertificates();
// java.util.ResourceBundle tempoid =
// java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID");
// String tmpEgovOID = "";
//
// for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) {
// String element = o.nextElement();
// // System.out.println(element + ":" + oid.getString(element));
// if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) {
// if (!tmpEgovOID.equals("")) {
// tmpEgovOID += ", ";
// }
// tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")";
// }
// }
// //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
// System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString());
// System.out.println("\tDatum: " + cal.getTime().toString());
// System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString());
// System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber());
// if (!tmpEgovOID.equals("")) {
// System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID);
// }
// System.out.println("\n");
// System.out.println("\tDocument modified: " + !pk.verify());
//// Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
//// if (fails == null) {
//// System.out.println("\tCertificates verified against the KeyStore");
//// } else {
//// System.out.println("\tCertificate failed: " + fails[1]);
//// }
// }
//
// //////
} else {
// fake definition
signatureBlock = new Rectangle(0, 0, 0, 0);
}
PdfSignatureAppearance sap = stp.getSignatureAppearance();
// sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null,
// PdfSignatureAppearance.WINCER_SIGNED );
sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null);
sap.setReason(signReason);
sap.setLocation(signLocation);
// }
if (finalize) {
sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
} else {
sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
}
stp.close();
/* MODIFY BY: Denis Torresan
Main.setResult(
java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"),
false,
"");
*/
} catch (Exception e) {
throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage());
}
} catch (KeyStoreException kse) {
throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage());
}
}Example 41
| Project: bloatit-master File: InvoicePdfGenerator.java View source code |
private void addDetailTable(final String deliveryName, final BigDecimal price) throws DocumentException, InvalidPositionException {
final PdfPTable table = new PdfPTable(4);
table.addCell(createTableHeaderCell("Description of service"));
table.addCell(createTableHeaderCell("Qty"));
table.addCell(createTableHeaderCell("Unit price"));
table.addCell(createTableHeaderCell("Amount"));
table.addCell(createTableBodyCell(deliveryName));
table.addCell(createTableBodyCell("1"));
table.addCell(createTableBodyCell(price));
table.addCell(createTableBodyCell(price));
table.setWidthPercentage(100);
final float[] widths = { 300f, 66f, 120f, 85f };
table.setWidths(widths);
setLeft(430, table);
}Example 42
| Project: ExcelToBarcode-master File: MainController.java View source code |
/** Show one label by taking one row and printing it on the document */
private void showOneLabel(Row r, PdfPTable t, PdfWriter writer, LabelFormat labelFormat) throws DocumentException {
if (t == null)
throw new NullPointerException("table parameter was null");
if (r == null) {
// there is a missing row
// so insert a blank cell and move on
final PdfPCell cell = new PdfPCell();
cell.setFixedHeight(labelFormat.getHeight() * 72);
// a tenth of an inch
cell.setPadding(0.1f * 72);
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
// FIXME - make this more smart
cell.addElement(new Paragraph(" "));
t.addCell(cell);
return;
}
if (lineConfigurations == null)
throw new NullPointerException("Line configurations was null!");
final PdfPCell cell = new PdfPCell();
cell.setFixedHeight(labelFormat.getHeight() * 72);
// a tenth of an inch
cell.setPadding(0.1f * 72);
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
cell.setBorder(Rectangle.NO_BORDER);
// calculate barcode height
final float barcodeHeight = cell.getFixedHeight() / lineConfigurations.size();
for (LineConfiguration lineConfiguration : lineConfigurations) {
LOG.info("Showing row: " + r.getRowNum() + ", line config: " + lineConfiguration);
if (lineConfiguration.getLineType() == TEXT) {
final org.apache.poi.ss.usermodel.Cell excelCell = r.getCell(lineConfiguration.getColumnNumber());
final Cell myCell = r.getCell(lineConfiguration.getColumnNumber());
if (myCell == null) {
cell.addElement(new Paragraph(" "));
} else {
final Paragraph p = new Paragraph(getTrimmedString(myCell), findFont(excelCell));
p.setLeading(0.8f * fontSizeRatio * barcodeHeight);
// p.setLeading(10);
if (excelCell.getCellStyle().getAlignment() == CellStyle.ALIGN_LEFT)
p.setAlignment(Paragraph.ALIGN_LEFT);
else if (excelCell.getCellStyle().getAlignment() == CellStyle.ALIGN_CENTER)
p.setAlignment(Paragraph.ALIGN_CENTER);
else if (excelCell.getCellStyle().getAlignment() == CellStyle.ALIGN_RIGHT)
p.setAlignment(Paragraph.ALIGN_RIGHT);
p.setSpacingAfter(barcodeHeight * 0.2f);
cell.addElement(p);
}
} else {
final Barcode128 code128 = new Barcode128();
code128.setGenerateChecksum(true);
final Cell myCell = r.getCell(lineConfiguration.getColumnNumber());
if (myCell == null)
code128.setCode(" ");
else
code128.setCode(getTrimmedString(myCell));
final Image image = code128.createImageWithBarcode(writer.getDirectContent(), null, null);
image.scaleToFit(labelFormat.getWidth() * 72, 0.9f * barcodeHeight);
image.setAlignment(Image.ALIGN_CENTER);
cell.addElement(image);
}
// set cell height:
// http://itextpdf.com/examples/iia.php?id=81
}
t.addCell(cell);
}Example 43
| Project: expense-tracker-master File: GenerateReport.java View source code |
private void addTable(Document document) throws DocumentException {
PdfPTable table = new PdfPTable(5);
table.setWidthPercentage(90);
table.getDefaultCell().setPadding(5.0F);
float totalWidth = ((table.getWidthPercentage() * writer.getPageSize().getWidth()) / 100);
float widths[] = { totalWidth / 10, totalWidth / 5, totalWidth / 5, (3 * totalWidth) / 10, totalWidth / 5 };
table.setWidths(widths);
PdfPCell c1 = new PdfPCell(new Phrase("Sr. No.", tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Date", tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Location", tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Description", tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Amount", tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.setSplitRows(true);
addDataToTable(table, document);
}Example 44
| Project: ganttproject-master File: ThemeImpl.java View source code |
private void writeAttributes(PdfPTable table, LinkedHashMap<String, String> attrs) {
for (Entry<String, String> nextEntry : attrs.entrySet()) {
{
Paragraph p = new Paragraph(nextEntry.getKey(), getSansRegularBold(12));
PdfPCell cell = new PdfPCell(p);
cell.setBorder(PdfPCell.NO_BORDER);
table.addCell(cell);
}
{
Paragraph p = new Paragraph(nextEntry.getValue(), getSansRegular(12));
PdfPCell cell = new PdfPCell(p);
cell.setBorder(PdfPCell.NO_BORDER);
table.addCell(cell);
}
}
}Example 45
| Project: Magazzino-master File: Format2DocumentReceipt.java View source code |
@Model
public void build(Receipt receipt) throws Exception {
ResourceBundle bundle = ResourceBundle.getBundle("messages");
Document document = new Document();
ByteArrayOutputStream bytesOS = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, bytesOS);
document.open();
Font normalFont = new Font();
PdfContentByte canvas = writer.getDirectContentUnder();
List<Data> imagesJar = receipt.getJar().getFiles();
if (imagesJar != null && imagesJar.size() > 0) {
Image image1 = Image.getInstance(imagesJar.get(0).getData());
image1.setAbsolutePosition(36, 742);
image1.scalePercent(60);
document.add(image1);
}
Phrase phrase1 = new Phrase(bundle.getString("pdf_number_receipt"), normalFont);
Phrase phrase2 = new Phrase(receipt.getCodeReceipt() + "", normalFont);
Phrase phrase3 = new Phrase(bundle.getString("receipt_date"), normalFont);
Phrase phrase4 = new Phrase(receipt.getDate(), normalFont);
Phrase phrase5 = new Phrase(receipt.getCause(), normalFont);
Phrase phrase6 = new Phrase(receipt.getDescription(), normalFont);
Phrase phrase7 = new Phrase(bundle.getString("customer_code") + " " + bundle.getString("customer"), normalFont);
Phrase phrase8 = new Phrase("prova 4: prova 4", normalFont);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase1, 286, 797, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase2, 386, 797, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase3, 286, 777, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase4, 386, 777, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase5, 286, 757, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase6, 386, 757, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase7, 286, 737, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase8, 386, 737, 0);
Phrase phrase9 = new Phrase("prova 4: prova 4", normalFont);
Phrase phrase10 = new Phrase("prova 2: prova 2", normalFont);
Phrase phrase11 = new Phrase("prova 3: prova 3", normalFont);
Phrase phrase12 = new Phrase("prova 4: prova 4", normalFont);
Phrase phrase13 = new Phrase(bundle.getString("pdf_tel"), normalFont);
Phrase phrase14 = new Phrase("prova 2: prova 2", normalFont);
Phrase phrase15 = new Phrase(bundle.getString("pdf_partita_iva_short"), normalFont);
Phrase phrase16 = new Phrase("prova 4: prova 4", normalFont);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase9, 36, 718, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase10, 136, 718, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase11, 36, 698, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase12, 136, 698, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase13, 36, 678, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase14, 136, 678, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase15, 36, 658, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase16, 136, 658, 0);
Phrase phrase17 = new Phrase("Ditta", normalFont);
Phrase phrase18 = new Phrase("prova 2: prova 2", normalFont);
Phrase phrase19 = new Phrase("prova 3: prova 3", normalFont);
Phrase phrase20 = new Phrase("prova 4: prova 4", normalFont);
Phrase phrase21 = new Phrase("prova 4: prova 4", normalFont);
Phrase phrase22 = new Phrase(bundle.getString("pdf_partita_iva_short"), normalFont);
Phrase phrase23 = new Phrase("prova 2: ", normalFont);
Phrase phrase24 = new Phrase(bundle.getString("pdf_cod_fisc"), normalFont);
Phrase phrase25 = new Phrase("prova 2: ", normalFont);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase17, 236, 736, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase18, 236, 708, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase19, 236, 688, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase20, 236, 668, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase21, 386, 668, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase22, 236, 648, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase23, 286, 648, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase24, 356, 648, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase25, 416, 648, 0);
Phrase phrase26 = new Phrase(bundle.getString("article_code"), normalFont);
Phrase phrase27 = new Phrase(bundle.getString("article_description"), normalFont);
Phrase phrase28 = new Phrase(bundle.getString("pdf_number_articles"), normalFont);
Phrase phrase29 = new Phrase(bundle.getString("article_prize"), normalFont);
Phrase phrase30 = new Phrase(bundle.getString("pdf_reduction"), normalFont);
Phrase phrase31 = new Phrase(bundle.getString("pdf_amount"), normalFont);
Phrase phrase32 = new Phrase(bundle.getString("pdf_iva"), normalFont);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase26, 59, 618, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase27, 146, 618, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase28, 208, 618, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase29, 280, 618, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase30, 353, 618, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase31, 422, 618, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase32, 498, 618, 0);
Phrase phrase33 = null;
Phrase phrase34 = null;
Phrase phrase35 = null;
Phrase phrase36 = null;
Phrase phrase37 = null;
Phrase phrase38 = null;
Phrase phrase39 = null;
int i = 0;
for (i = 0; i < 70; i = i + 15) {
phrase33 = new Phrase("dsadasd", normalFont);
phrase34 = new Phrase("dgbsbb", normalFont);
phrase35 = new Phrase("323232", normalFont);
phrase36 = new Phrase("bbgdbdfbdb", normalFont);
phrase37 = new Phrase("wefwew", normalFont);
phrase38 = new Phrase("ewrew", normalFont);
phrase39 = new Phrase("ewr5", normalFont);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase33, 59, 598 - i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase34, 136, 598 - i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase35, 196, 598 - i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase36, 266, 598 - i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase37, 351, 598 - i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase38, 416, 598 - i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase39, 496, 598 - i, 0);
}
int j = 298;
if (i - 298 < 0)
i = 298;
else {
j = i;
i = 588 - i;
}
Phrase phrase40 = new Phrase(bundle.getString("pdf_references").toUpperCase(), normalFont);
Phrase phrase41 = new Phrase(bundle.getString("pdf_delivery").toUpperCase(), normalFont);
Phrase phrase42 = new Phrase(bundle.getString("pdf_payments").toUpperCase(), normalFont);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase40, 105, i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase41, 206, i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase42, 316, i, 0);
Phrase phrase43 = new Phrase("opoppp", normalFont);
Phrase phrase44 = new Phrase("2ws", normalFont);
Phrase phrase45 = new Phrase("78900", normalFont);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase43, 59, i - 20, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase44, 186, i - 20, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase45, 276, i - 20, 0);
Phrase phrase46 = new Phrase(bundle.getString("pdf_sign_producer").toUpperCase(), normalFont);
Phrase phrase47 = new Phrase(bundle.getString("pdf_sign_receiver").toUpperCase(), normalFont);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase46, 154, i - 40, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase47, 321, i - 40, 0);
Phrase phrase48 = new Phrase(bundle.getString("article_imponible"), normalFont);
Phrase phrase49 = new Phrase("opoppp", normalFont);
Phrase phrase50 = new Phrase(bundle.getString("pdf_tax"), normalFont);
Phrase phrase51 = new Phrase("78900", normalFont);
Phrase phrase52 = new Phrase(bundle.getString("pdf_total_receipt"), normalFont);
Phrase phrase53 = new Phrase("2ws", normalFont);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase48, 356, i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase49, 566, i, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase50, 356, i - 25, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase51, 566, i - 25, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase52, 356, i - 50, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase53, 566, i - 50, 0);
PdfPTable table = new PdfPTable(4);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
table.setWidths(new float[] { 47, 18, 18, 17 });
PdfPCell cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.LEFT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.LEFT);
cell.enableBorderSide(PdfPCell.BOTTOM);
cell.enableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
table.addCell(cell);
cell = new PdfPCell();
cell.disableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
document.add(table);
table = new PdfPTable(4);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
table.setWidths(new float[] { 47, 18, 18, 17 });
cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.LEFT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.LEFT);
cell.enableBorderSide(PdfPCell.BOTTOM);
cell.enableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
table.addCell(cell);
cell = new PdfPCell();
cell.disableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
document.add(table);
table = new PdfPTable(4);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
table.setWidths(new float[] { 47, 18, 18, 17 });
cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.LEFT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.LEFT);
cell.enableBorderSide(PdfPCell.BOTTOM);
cell.enableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
table.addCell(cell);
cell = new PdfPCell();
cell.disableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
document.add(table);
table = new PdfPTable(4);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
table.setWidths(new float[] { 47, 18, 18, 17 });
cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.LEFT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.LEFT);
cell.enableBorderSide(PdfPCell.BOTTOM);
cell.enableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
table.addCell(cell);
cell = new PdfPCell();
cell.disableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
document.add(table);
table = new PdfPTable(1);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
cell = new PdfPCell();
cell.disableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.LEFT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(3);
table.addCell(cell);
document.add(table);
table = new PdfPTable(3);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
table.setWidths(new float[] { 38, 48, 14 });
cell.disableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.LEFT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(40);
table.addCell(cell);
cell.enableBorderSide(PdfPCell.RIGHT);
cell.enableBorderSide(PdfPCell.LEFT);
cell.enableBorderSide(PdfPCell.BOTTOM);
cell.enableBorderSide(PdfPCell.TOP);
table.addCell(cell);
cell.disableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.LEFT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
table.addCell(cell);
document.add(table);
table = new PdfPTable(1);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
cell = new PdfPCell();
cell.disableBorderSide(PdfPCell.RIGHT);
cell.disableBorderSide(PdfPCell.LEFT);
cell.disableBorderSide(PdfPCell.BOTTOM);
cell.disableBorderSide(PdfPCell.TOP);
cell.setPadding(3);
table.addCell(cell);
document.add(table);
table = new PdfPTable(7);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
table.setWidths(new float[] { 16, 12, 11, 17, 12, 16, 16 });
cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.RIGHT);
cell.enableBorderSide(PdfPCell.LEFT);
cell.enableBorderSide(PdfPCell.BOTTOM);
cell.enableBorderSide(PdfPCell.TOP);
cell.setPadding(10);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
document.add(table);
table = new PdfPTable(7);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
table.setWidths(new float[] { 16, 12, 11, 17, 12, 16, 16 });
cell = new PdfPCell();
cell.enableBorderSide(PdfPCell.RIGHT);
cell.enableBorderSide(PdfPCell.LEFT);
cell.enableBorderSide(PdfPCell.BOTTOM);
cell.enableBorderSide(PdfPCell.TOP);
cell.setPadding(j * 8 - 2234);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
document.add(table);
table = new PdfPTable(5);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
table.setWidths(new float[] { 20, 20, 20, 20, 20 });
cell = new PdfPCell();
cell.setPadding(20);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
cell.disableBorderSide(PdfPCell.BOTTOM);
table.addCell(cell);
table.addCell(cell);
document.add(table);
table = new PdfPTable(4);
table.getDefaultCell().setPadding(50);
table.setWidthPercentage(105);
table.setWidths(new float[] { 30, 30, 20, 20 });
cell = new PdfPCell();
cell.setPadding(20);
table.addCell(cell);
table.addCell(cell);
cell.disableBorderSide(PdfPCell.TOP);
table.addCell(cell);
table.addCell(cell);
document.add(table);
document.close();
HttpServletResponse response = (HttpServletResponse) extCtx.getResponse();
response.setContentType("application/pdf");
response.addHeader("Content-disposition", "attachment; filename=\"" + bundle.getString("receipt") + "-" + receipt.getDate() + ".pdf\"");
ServletOutputStream os = response.getOutputStream();
os.write(bytesOS.toByteArray());
os.flush();
os.close();
facesContext.responseComplete();
}Example 46
| Project: openrocket-master File: PartsDetailVisitorStrategy.java View source code |
/**
* Add a line to the detail report based upon the type of the component.
*
* @param component the component to print the detail for
*/
private void handle(RocketComponent component) {
//using the Visitor pattern. Unfortunately, it was misunderstood and was removed.
if (component instanceof Stage) {
try {
if (grid != null) {
document.add(grid);
}
document.add(ITextHelper.createPhrase(component.getName()));
grid = new PdfPTable(TABLE_COLUMNS);
grid.setWidthPercentage(100);
grid.setHorizontalAlignment(Element.ALIGN_LEFT);
} catch (DocumentException e) {
}
List<RocketComponent> rc = component.getChildren();
goDeep(rc);
} else if (component instanceof LaunchLug) {
LaunchLug ll = (LaunchLug) component;
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(ll.getMaterial()));
grid.addCell(createOuterInnerDiaCell(ll));
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
} else if (component instanceof NoseCone) {
NoseCone nc = (NoseCone) component;
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(nc.getMaterial()));
grid.addCell(ITextHelper.createCell(nc.getType().getName(), PdfPCell.BOTTOM));
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
List<RocketComponent> rc = component.getChildren();
goDeep(rc);
} else if (component instanceof Transition) {
Transition tran = (Transition) component;
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(tran.getMaterial()));
Chunk fore = new Chunk(FORE_DIAMETER + toLength(tran.getForeRadius() * 2));
fore.setFont(PrintUtilities.NORMAL);
Chunk aft = new Chunk(AFT_DIAMETER + toLength(tran.getAftRadius() * 2));
aft.setFont(PrintUtilities.NORMAL);
final PdfPCell cell = ITextHelper.createCell();
cell.addElement(fore);
cell.addElement(aft);
grid.addCell(cell);
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
List<RocketComponent> rc = component.getChildren();
goDeep(rc);
} else if (component instanceof BodyTube) {
BodyTube bt = (BodyTube) component;
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(bt.getMaterial()));
grid.addCell(createOuterInnerDiaCell(bt));
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
List<RocketComponent> rc = component.getChildren();
goDeep(rc);
} else if (component instanceof FinSet) {
handleFins((FinSet) component);
} else if (component instanceof BodyComponent) {
grid.addCell(component.getName());
grid.completeRow();
List<RocketComponent> rc = component.getChildren();
goDeep(rc);
} else if (component instanceof ExternalComponent) {
ExternalComponent ext = (ExternalComponent) component;
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(ext.getMaterial()));
grid.addCell(ITextHelper.createCell());
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
List<RocketComponent> rc = component.getChildren();
goDeep(rc);
} else if (component instanceof InnerTube) {
InnerTube it = (InnerTube) component;
grid.addCell(iconToImage(component));
final PdfPCell pCell = createNameCell(component.getName(), true, component.getPresetComponent());
grid.addCell(pCell);
grid.addCell(createMaterialCell(it.getMaterial()));
grid.addCell(createOuterInnerDiaCell(it));
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
List<RocketComponent> rc = component.getChildren();
goDeep(rc);
} else if (component instanceof RadiusRingComponent) {
RadiusRingComponent rrc = (RadiusRingComponent) component;
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(rrc.getMaterial()));
if (component instanceof Bulkhead) {
grid.addCell(createDiaCell(rrc.getOuterRadius() * 2));
} else {
grid.addCell(createOuterInnerDiaCell(rrc));
}
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
List<RocketComponent> rc = component.getChildren();
goDeep(rc);
} else if (component instanceof RingComponent) {
RingComponent ring = (RingComponent) component;
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(ring.getMaterial()));
grid.addCell(createOuterInnerDiaCell(ring));
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
List<RocketComponent> rc = component.getChildren();
goDeep(rc);
} else if (component instanceof ShockCord) {
ShockCord ring = (ShockCord) component;
PdfPCell cell = ITextHelper.createCell();
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
cell.setPaddingBottom(12f);
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(ring.getMaterial()));
grid.addCell(cell);
grid.addCell(createLengthCell(ring.getCordLength()));
grid.addCell(createMassCell(component.getMass()));
} else if (component instanceof Parachute) {
Parachute chute = (Parachute) component;
PdfPCell cell = ITextHelper.createCell();
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
cell.setPaddingBottom(12f);
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(chute.getMaterial()));
// if (chute.hasSpillHole()) {
// grid.addCell(createOuterInnerDiaCell(chute.getDiameter()/2, chute.getSpillHoleDiameter()/2));
// }
// else {
grid.addCell(createDiaCell(chute.getDiameter()));
// }
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
grid.addCell(iconToImage(null));
grid.addCell(createNameCell(SHROUD_LINES, true, component.getPresetComponent()));
grid.addCell(createMaterialCell(chute.getLineMaterial()));
grid.addCell(createLinesCell(chute.getLineCount()));
grid.addCell(createLengthCell(chute.getLineLength()));
grid.addCell(cell);
} else if (component instanceof Streamer) {
Streamer ring = (Streamer) component;
PdfPCell cell = ITextHelper.createCell();
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
cell.setPaddingBottom(12f);
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(ring.getMaterial()));
grid.addCell(createStrip(ring));
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
} else if (component instanceof RecoveryDevice) {
RecoveryDevice device = (RecoveryDevice) component;
PdfPCell cell = ITextHelper.createCell();
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
cell.setPaddingBottom(12f);
grid.addCell(iconToImage(component));
grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent()));
grid.addCell(createMaterialCell(device.getMaterial()));
grid.addCell(cell);
grid.addCell(createLengthCell(component.getLength()));
grid.addCell(createMassCell(component.getMass()));
} else if (component instanceof MassObject) {
PdfPCell cell = ITextHelper.createCell();
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
cell.setPaddingBottom(12f);
grid.addCell(iconToImage(component));
final PdfPCell nameCell = createNameCell(component.getName(), true, component.getPresetComponent());
nameCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
nameCell.setPaddingBottom(12f);
grid.addCell(nameCell);
grid.addCell(cell);
grid.addCell(createDiaCell(((MassObject) component).getRadius() * 2));
grid.addCell(cell);
grid.addCell(createMassCell(component.getMass()));
}
}Example 47
| Project: ts-android-master File: PdfPrinter.java View source code |
/**
* Adds the title page
* @param document
* @throws DocumentException
*/
private void addTitlePage(Document document) throws DocumentException {
Paragraph preface = new Paragraph();
preface.setAlignment(Element.ALIGN_CENTER);
addEmptyLine(preface, 1);
// book title
ProjectTranslation projectTranslation = targetTranslation.getProjectTranslation();
Paragraph titleParagraph = (new Paragraph(projectTranslation.getTitle(), titleFont));
titleParagraph.setAlignment(Element.ALIGN_CENTER);
preface.add(titleParagraph);
addEmptyLine(preface, 1);
// book description
preface.add(new Paragraph(projectTranslation.getDescription(), subFont));
// table for vertical alignment
PdfPTable table = new PdfPTable(1);
table.setWidthPercentage(100);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.setMinimumHeight(document.getPageSize().getHeight() - VERTICAL_PADDING * 2);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.addElement(preface);
table.addCell(cell);
document.add(table);
document.newPage();
}Example 48
| Project: evoker-master File: Genoplot.java View source code |
public void printPDFsInBackground() throws IOException {
Enumeration<String> keys = pdfScores.keys();
try {
openPDFs();
} catch (DocumentException /*|IOException ex*/
ex) {
ex.printStackTrace();
throw new IOException("Could not write PDF");
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException("Could not write PDF");
}
File tempFile = null;
try {
tempFile = File.createTempFile("temp", "png");
} catch (IOException e1) {
e1.printStackTrace();
}
tempFile.deleteOnExit();
int progressCounter = 0;
try {
while (keys.hasMoreElements() && !pm.isCanceled()) {
String snp = (String) keys.nextElement();
String score = (String) pdfScores.get(snp);
ArrayList<Image> images = new ArrayList<Image>();
ArrayList<String> stats = new ArrayList<String>();
// loop through all the collections to get the average maf
double totalMaf = 0;
int totalSamples = 0;
for (String collection : db.getCollections()) {
PlotData pd = db.getRecord(snp, collection, getCoordSystem());
pd.computeSummary();
int sampleNum = db.samplesByCollection.get(collection).getNumInds();
totalMaf += pd.getMaf() * sampleNum;
totalSamples += sampleNum;
}
for (String collection : db.getCollections()) {
PlotPanel pp = new PlotPanel(this, collection, db.getRecord(snp, collection, getCoordSystem()), plotWidth, plotHeight, longStats.isSelected(), totalMaf, totalSamples);
pp.refresh();
if (pp.hasData()) {
pp.setDimensions(pp.getMinDim(), pp.getMaxDim());
ChartUtilities.saveChartAsPNG(tempFile, pp.getChart(), 400, 400);
images.add(Image.getInstance(tempFile.getAbsolutePath()));
stats.add(pp.generateInfoStr());
} else {
// print the jpanel displaying the no data
// message
BufferedImage noSNP = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = noSNP.createGraphics();
pp.paint(g2);
g2.dispose();
ImageIO.write(noSNP, "png", tempFile);
images.add(Image.getInstance(tempFile.getAbsolutePath()));
stats.add("");
}
}
PdfPTable table = new PdfPTable(images.size());
PdfPCell snpCell = new PdfPCell(new Paragraph(snp));
snpCell.setColspan(images.size());
snpCell.setBorder(0);
snpCell.setHorizontalAlignment(Element.ALIGN_CENTER);
snpCell.setVerticalAlignment(Element.ALIGN_TOP);
table.addCell(snpCell);
Iterator<Image> ii = images.iterator();
while (ii.hasNext()) {
PdfPCell imageCell = new PdfPCell((Image) ii.next());
imageCell.setBorder(0);
table.addCell(imageCell);
}
Iterator<String> si = stats.iterator();
while (si.hasNext()) {
PdfPCell statsCell = new PdfPCell(new Paragraph((String) si.next()));
statsCell.setBorder(0);
statsCell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(statsCell);
}
if (pdfd.allPlots()) {
allPDF.getDocument().add(table);
allPDF.getDocument().newPage();
}
if (score.matches("1") && pdfd.yesPlots()) {
yesPDF.getDocument().add(table);
yesPDF.getDocument().newPage();
yesPlotNum++;
}
if (score.matches("0") && pdfd.maybePlots()) {
maybePDF.getDocument().add(table);
maybePDF.getDocument().newPage();
maybePlotNum++;
}
if (score.matches("-1") && pdfd.noPlots()) {
noPDF.getDocument().add(table);
noPDF.getDocument().newPage();
noPlotNum++;
}
progressCounter++;
pm.setProgress(progressCounter);
}
closePDFs();
} catch (Exception e) {
}
}Example 49
| Project: nextreports-engine-master File: PdfExporter.java View source code |
private PdfPCell renderPdfCell(BandElement bandElement, Object value, int gridRow, int rowSpan, int colSpan, boolean image, int column) {
Map<String, Object> style = buildCellStyleMap(bandElement, value, gridRow, column, colSpan);
FontFactoryImp fact = new FontFactoryImp();
com.itextpdf.text.Font fnt;
if (bandElement != null) {
fontName = (String) style.get(StyleFormatConstants.FONT_NAME_KEY);
int size = ((Float) style.get(StyleFormatConstants.FONT_SIZE)).intValue();
fnt = getFont(size);
} else {
fnt = getFont(10);
}
PdfPCell cell;
if (image) {
if (value == null) {
cell = new PdfPCell(new Phrase(IMAGE_NOT_FOUND));
} else {
ImageBandElement ibe = (ImageBandElement) bandElement;
try {
byte[] imageBytes = getImage((String) value);
cell = getImageCell(ibe, imageBytes, column, colSpan);
} catch (Exception e) {
cell = new PdfPCell(new Phrase(IMAGE_NOT_LOADED));
}
}
} else if (bandElement instanceof HyperlinkBandElement) {
Hyperlink hyperlink = ((HyperlinkBandElement) bandElement).getHyperlink();
Anchor anchor = new Anchor(hyperlink.getText(), fnt);
anchor.setReference(hyperlink.getUrl());
Phrase ph = new Phrase();
ph.add(anchor);
cell = new PdfPCell(ph);
} else if (bandElement instanceof ReportBandElement) {
Report report = ((ReportBandElement) bandElement).getReport();
ExporterBean eb = null;
try {
eb = getSubreportExporterBean(report);
PdfExporter subExporter = new PdfExporter(eb);
subExporter.export();
PdfPTable innerTable = subExporter.getTable();
cell = new PdfPCell(innerTable);
} catch (Exception e) {
cell = new PdfPCell();
e.printStackTrace();
} finally {
if ((eb != null) && (eb.getResult() != null)) {
eb.getResult().close();
}
}
} else if ((bandElement instanceof VariableBandElement) && (VariableFactory.getVariable(((VariableBandElement) bandElement).getVariable()) instanceof TotalPageNoVariable)) {
try {
cell = new PdfPCell(Image.getInstance(total));
} catch (BadElementException e) {
cell = new PdfPCell(new Phrase("NA"));
}
} else if (bandElement instanceof ImageColumnBandElement) {
try {
String v = StringUtil.getValueAsString(value, null);
if (StringUtil.BLOB.equals(v)) {
cell = new PdfPCell(new Phrase(StringUtil.BLOB));
} else {
byte[] bytes = StringUtil.decodeImage(v);
cell = getImageCell(bandElement, bytes, column, colSpan);
}
} catch (Exception e) {
e.printStackTrace();
cell = new PdfPCell(new Phrase(IMAGE_NOT_LOADED));
}
} else {
String stringValue;
if (style.containsKey(StyleFormatConstants.PATTERN)) {
stringValue = StringUtil.getValueAsString(value, (String) style.get(StyleFormatConstants.PATTERN), getReportLanguage());
} else {
stringValue = StringUtil.getValueAsString(value, null, getReportLanguage());
}
if (stringValue == null) {
stringValue = "";
}
if (stringValue.startsWith("<html>")) {
StringReader reader = new StringReader(stringValue);
List<Element> elems = new ArrayList<Element>();
try {
elems = HTMLWorker.parseToList(reader, new StyleSheet());
Phrase ph = new Phrase();
for (int i = 0; i < elems.size(); i++) {
Element elem = (Element) elems.get(i);
ph.add(elem);
}
cell = new PdfPCell(ph);
} catch (IOException e) {
e.printStackTrace();
Phrase ph = new Phrase(stringValue, fnt);
cell = new PdfPCell(ph);
}
} else {
Phrase ph = new Phrase(stringValue, fnt);
cell = new PdfPCell(ph);
}
}
cell.setArabicOptions(arabicOptions);
cell.setRunDirection(textDirection);
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
// needed for a cell without padding
cell.setUseDescender(true);
// needed if there is a row in which all cells are empty
cell.setMinimumHeight(MINIMUM_HEIGHT);
if (bandElement != null) {
cell.setRotation(bandElement.getTextRotation());
}
if (colSpan > 1) {
cell.setColspan(colSpan);
}
if (rowSpan > 1) {
cell.setRowspan(rowSpan);
}
if (style != null) {
updateFont(style, fnt);
if (style.containsKey(StyleFormatConstants.BACKGROUND_COLOR)) {
Color val = (Color) style.get(StyleFormatConstants.BACKGROUND_COLOR);
cell.setBackgroundColor(new BaseColor(val));
}
if (style.containsKey(StyleFormatConstants.HORIZONTAL_ALIGN_KEY)) {
if (StyleFormatConstants.HORIZONTAL_ALIGN_LEFT.equals(style.get(StyleFormatConstants.HORIZONTAL_ALIGN_KEY))) {
cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
}
if (StyleFormatConstants.HORIZONTAL_ALIGN_RIGHT.equals(style.get(StyleFormatConstants.HORIZONTAL_ALIGN_KEY))) {
cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
}
if (StyleFormatConstants.HORIZONTAL_ALIGN_CENTER.equals(style.get(StyleFormatConstants.HORIZONTAL_ALIGN_KEY))) {
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
}
}
if (style.containsKey(StyleFormatConstants.VERTICAL_ALIGN_KEY)) {
if (StyleFormatConstants.VERTICAL_ALIGN_TOP.equals(style.get(StyleFormatConstants.VERTICAL_ALIGN_KEY))) {
cell.setVerticalAlignment(Element.ALIGN_TOP);
}
if (StyleFormatConstants.VERTICAL_ALIGN_MIDDLE.equals(style.get(StyleFormatConstants.VERTICAL_ALIGN_KEY))) {
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
}
if (StyleFormatConstants.VERTICAL_ALIGN_BOTTOM.equals(style.get(StyleFormatConstants.VERTICAL_ALIGN_KEY))) {
cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
}
}
if (style.containsKey(StyleFormatConstants.PADDING_LEFT)) {
Float val = (Float) style.get(StyleFormatConstants.PADDING_LEFT);
cell.setPaddingLeft(val);
}
if (style.containsKey(StyleFormatConstants.PADDING_RIGHT)) {
Float val = (Float) style.get(StyleFormatConstants.PADDING_RIGHT);
cell.setPaddingRight(val);
}
if (style.containsKey(StyleFormatConstants.PADDING_TOP)) {
Float val = (Float) style.get(StyleFormatConstants.PADDING_TOP);
cell.setPaddingTop(val);
}
if (style.containsKey(StyleFormatConstants.PADDING_BOTTOM)) {
Float val = (Float) style.get(StyleFormatConstants.PADDING_BOTTOM);
cell.setPaddingBottom(val);
}
cell.setBorderWidth(0);
if (style.containsKey(StyleFormatConstants.BORDER_LEFT)) {
Float val = (Float) style.get(StyleFormatConstants.BORDER_LEFT);
cell.setBorderWidthLeft(val / 2);
Color color = (Color) style.get(StyleFormatConstants.BORDER_LEFT_COLOR);
cell.setBorderColorLeft(new BaseColor(color));
}
if (style.containsKey(StyleFormatConstants.BORDER_RIGHT)) {
Float val = (Float) style.get(StyleFormatConstants.BORDER_RIGHT);
cell.setBorderWidthRight(val / 2);
Color color = (Color) style.get(StyleFormatConstants.BORDER_RIGHT_COLOR);
cell.setBorderColorRight(new BaseColor(color));
}
if (style.containsKey(StyleFormatConstants.BORDER_TOP)) {
Float val = (Float) style.get(StyleFormatConstants.BORDER_TOP);
cell.setBorderWidthTop(val / 2);
Color color = (Color) style.get(StyleFormatConstants.BORDER_TOP_COLOR);
cell.setBorderColorTop(new BaseColor(color));
}
if (style.containsKey(StyleFormatConstants.BORDER_BOTTOM)) {
Float val = (Float) style.get(StyleFormatConstants.BORDER_BOTTOM);
cell.setBorderWidthBottom(val / 2);
Color color = (Color) style.get(StyleFormatConstants.BORDER_BOTTOM_COLOR);
cell.setBorderColorBottom(new BaseColor(color));
}
// for subreports we use default no wrap
if (cell.getTable() == null) {
cell.setNoWrap(true);
if (bandElement != null) {
if (bandElement.isWrapText()) {
cell.setNoWrap(false);
cell.setLeading(0, (float) bandElement.getPercentLineSpacing() / 100);
}
}
}
// to see a background image all cells must not have any background!
if (bean.getReportLayout().getBackgroundImage() != null) {
cell.setBackgroundColor(null);
}
}
return cell;
}Example 50
| Project: realtrack-android-master File: ParticipationSummaryActivity.java View source code |
/**
* Creates files to email.
*
* @param dHolder
*/
public void sendDataTaskDoInBackgroundCallback() {
DataHolder dHolder = dataHolder;
String[] allInits = updateInitiativeNames();
String[] allCspps = updateCsppNames();
FileOutputStream dataFos = null;
FileOutputStream participationFos = null;
FileOutputStream signinFos = null;
Document signinDocument = null;
try {
dataFos = new FileOutputStream(nonAlignedDataOutputFile);
participationFos = new FileOutputStream(cacheParticipationOutputFile);
signinFos = new FileOutputStream(signInReportsOutputFile);
signinDocument = new Document(PageSize.A4);
PdfWriter.getInstance(signinDocument, signinFos);
signinDocument.open();
signinDocument.addTitle("RealTrack Sign-In Report");
Paragraph reportHeader = new Paragraph("RealTrack Sign-In Report", TITLE_FONT);
reportHeader.add(new Paragraph("Report generated on: " + (new SimpleDateFormat("MM/dd/yyyy hh:mm aaa").format(new Date()))));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.contains(getString(R.string.name)))
reportHeader.add(new Paragraph("PCV Name: " + prefs.getString(getString(R.string.name), "")));
signinDocument.add(reportHeader);
LineSeparator ls = new LineSeparator();
signinDocument.add(new Chunk(ls));
} catch (Exception e) {
}
String dataCSVContent = "Project Title" + "," + "Project Start Date" + "," + "Project End Date" + "," + "Project Notes" + "," + "Activity Title" + "," + "Activity Start Date" + "," + "Activity End Date" + "," + "Activity Cohort" + "," + "Activity Notes" + "," + "Activity Organizations" + "," + "Activity Community 1" + "," + "Activity CSPP" + "," + "Activity Initiatives" + "," + "Participation Date" + "," + "Participation Time" + "," + "Participation Men 0-9" + "," + "Participation Men 10-17" + "," + "Participation Men 18-24" + "," + "Participation Men over 25" + "," + "Participation Women 0-9" + "," + "Participation Women 10-17" + "," + "Participation Women 18-24" + "," + "Participation Women over 25" + "," + "Service Providers Men 0-9" + "," + "Service Providers Men 10-17" + "," + "Service Providers Men 18-24" + "," + "Service Providers Men over 25" + "," + "Service Providers Women 0-9" + "," + "Service Providers Women 10-17" + "," + "Service Providers Women 18-24" + "," + "Service Providers Women over 25" + "," + "Participation Event Details" + "\n";
String participationCSVContent = "Project Title" + "," + "Activity Title" + "," + "Cohort Name" + "," + "Participation Date" + "," + "Participation Time" + "," + "Participant Name" + "," + "Participant Phone Number" + "," + "Participant Village" + "," + "Participant Age" + "," + "Participant Gender" + "," + "Participation Event Details" + "\n";
try {
dataFos.write(dataCSVContent.getBytes());
participationFos.write(participationCSVContent.getBytes());
} catch (IOException e) {
}
for (ProjectHolder pHolder : dHolder.pHolder_data) {
Project p = pHolder.p;
for (ActivityHolder aHolder : pHolder.activityHolderList) {
Activities a = aHolder.a;
for (ParticipationHolder paHolder : aHolder.participationHolderList) {
Participation participation = paHolder.pa;
Date d = new Date(participation.getDate());
String[] csppList = a.getCspp().split("\\|");
String cspp = "";
for (int i = 0; i < csppList.length; i++) {
if (csppList[i].equals("1"))
cspp += allCspps[i] + "|";
}
// remove the last
cspp = (cspp.length() > 1) ? cspp.substring(0, cspp.length() - 1) : "";
// superfluous
// pipe character
String[] initiativesList = a.getInitiatives().split("\\|");
String inits = "";
for (int i = 0; i < initiativesList.length; i++) {
if (initiativesList[i].equals("1"))
inits += allInits[i] + "|";
}
// remove the
inits = (inits.length() > 1) ? inits.substring(0, inits.length() - 1) : "";
// last
// superfluous
// pipe
// character
int currentComms = findNumberOfCommunities(a.getComms());
if (currentComms > maxComms)
maxComms = currentComms;
dataCSVContent = ESCAPE_COMMAS + p.getTitle() + ESCAPE_COMMAS + "," + dateParser.format(p.getStartDate()) + "," + dateParser.format(p.getEndDate()) + "," + ESCAPE_COMMAS + p.getNotes() + ESCAPE_COMMAS + "," + ESCAPE_COMMAS + a.getTitle() + ESCAPE_COMMAS + "," + dateParser.format(a.getStartDate()) + "," + dateParser.format(a.getEndDate()) + "," + ESCAPE_COMMAS + a.getCohort() + ESCAPE_COMMAS + "," + ESCAPE_COMMAS + a.getNotes() + ESCAPE_COMMAS + "," + ESCAPE_COMMAS + a.getOrgs() + ESCAPE_COMMAS + "," + COMMUNITY_DELIMITER + a.getComms() + COMMUNITY_DELIMITER + cspp + "," + inits + "," + dateParser.format(participation.getDate()) + "," + timeParser.format(participation.getDate()) + "," + participation.getMen09() + "," + participation.getMen1017() + "," + participation.getMen1824() + "," + participation.getMenOver25() + "," + participation.getWomen09() + "," + participation.getWomen1017() + "," + participation.getWomen1824() + "," + participation.getWomenOver25() + "," + participation.getSpMen09() + "," + participation.getSpMen1017() + "," + participation.getSpMen1824() + "," + participation.getSpMenOver25() + "," + participation.getSpWomen09() + "," + participation.getSpWomen1017() + "," + participation.getSpWomen1824() + "," + participation.getSpWomenOver25() + "," + ESCAPE_COMMAS + participation.getNotes() + ESCAPE_COMMAS + "\n";
try {
dataFos.write(dataCSVContent.getBytes());
} catch (IOException e) {
}
Paragraph projectParagraph = null;
PdfPTable table = null;
if (!paHolder.participantList.isEmpty()) {
projectParagraph = new Paragraph();
addNewLines(projectParagraph, 1);
projectParagraph.add(new Paragraph("Project Title: " + p.getTitle()));
projectParagraph.add(new Paragraph("Activity Title: " + a.getTitle()));
projectParagraph.add(new Paragraph("Reporting Cohort: " + a.getCohort()));
projectParagraph.add(new Paragraph("Sign-In Sheet for: " + dateParser.format(d) + " " + timeParser.format(d)));
projectParagraph.add(new Paragraph("Event details: " + participation.getNotes()));
projectParagraph.add(new Paragraph("Sign-in Sheet:"));
addNewLines(projectParagraph, 1);
table = new PdfPTable(new float[] { 2, 2, 2, 1, 1, 3 });
table.setWidthPercentage(100f);
PdfPCell c1 = new PdfPCell(new Phrase("Name"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Phone"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Village"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Age"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Gender"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Signature"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
table.setHeaderRows(1);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);
}
for (Participant participant : paHolder.participantList) {
participationCSVContent = ESCAPE_COMMAS + p.getTitle() + ESCAPE_COMMAS + "," + ESCAPE_COMMAS + a.getTitle() + ESCAPE_COMMAS + "," + ESCAPE_COMMAS + a.getCohort() + ESCAPE_COMMAS + "," + dateParser.format(participation.getDate()) + "," + timeParser.format(participation.getDate()) + "," + ESCAPE_COMMAS + participant.getName() + ESCAPE_COMMAS + "," + ESCAPE_COMMAS + participant.getPhoneNumber() + ESCAPE_COMMAS + "," + ESCAPE_COMMAS + participant.getVillage() + ESCAPE_COMMAS + "," + participant.getAge() + "," + (participant.getGender() == Participant.MALE ? getString(R.string.male) : getString(R.string.female)) + "," + ESCAPE_COMMAS + participation.getNotes() + ESCAPE_COMMAS + "\n";
table.addCell(participant.getName());
table.addCell(participant.getPhoneNumber());
table.addCell(participant.getVillage());
table.addCell(Integer.toString(participant.getAge()));
table.addCell(participant.getGender() == Participant.MALE ? getString(R.string.male) : getString(R.string.female));
try {
Image signatureImage = Image.getInstance(participant.getSignaturePath());
PdfPCell imageCell = new PdfPCell(signatureImage);
imageCell.setHorizontalAlignment(Element.ALIGN_CENTER);
imageCell.setVerticalAlignment(Element.ALIGN_CENTER);
imageCell.setFixedHeight(50);
table.addCell(imageCell);
} catch (BadElementException e1) {
table.addCell("Signature not found");
} catch (MalformedURLException e1) {
table.addCell("Signature not found");
} catch (IOException e1) {
table.addCell("Signature not found");
}
try {
participationFos.write(participationCSVContent.getBytes());
} catch (IOException e) {
}
}
if (projectParagraph != null) {
projectParagraph.add(table);
try {
signinDocument.add(projectParagraph);
signinDocument.newPage();
} catch (DocumentException e) {
}
}
}
}
}
try {
dataFos.close();
participationFos.close();
signinDocument.close();
} catch (IOException e) {
}
// required if the user enters multiple communities separated by commas
normalizeCSVColumns();
}Example 51
| Project: Socio-technical-Security-Requirements-master File: ReportContentFactory.java View source code |
private void buildSectionStakeholders(Section section) {
String sectionIntro = "This section describes the stakeholders identified in the " + getProjectName() + " project. Stakeholders are represented by roles and agents.";
section.add(createParagraph(sectionIntro));
List<Actor> selActor = getStakeholderActors();
if (selActor.size() != 0) {
StringBuilder sb = new StringBuilder();
sb.append("In particular, ");
List<Role> roles = new ArrayList<Role>();
for (Actor a : selActor) {
if (a instanceof Role)
roles.add((Role) a);
}
List<String> rolesNames = new ArrayList<String>();
for (Role r : roles) {
rolesNames.add("%i" + r.getName() + "%");
}
if (roles.size() == 0) {
} else if (roles.size() == 1) {
sb.append("identified role is: " + rolesNames.get(0) + socialDiagRef());
} else {
sb.append("identified roles are: " + separateListOfString(rolesNames) + socialDiagRef());
}
List<Agent> agents = new ArrayList<Agent>();
for (Actor a : selActor) {
if (a instanceof Agent)
agents.add((Agent) a);
}
List<String> agentsNames = new ArrayList<String>();
for (Agent a : agents) {
agentsNames.add("%i" + a.getName() + "%");
}
if (roles.size() > 0 && agents.size() > 0) {
sb.append(", while ");
} else if (agents.size() == 0) {
sb.append(".");
}
if (agents.size() == 0) {
} else if (agents.size() == 1) {
if (roles.size() > 0)
sb.append(" ");
sb.append("identified agent is: " + agentsNames.get(0) + socialDiagRef() + ".");
} else {
if (roles.size() > 0)
sb.append(" ");
sb.append("identified agents are: " + separateListOfString(agentsNames) + socialDiagRef() + ". ");
}
// sb = new StringBuilder();
if (roles.size() > 0) {
sb.append(" " + ftc.getTable(FigureConstant.ROLE_TABLE));
if (agents.size() > 0)
sb.append(" and " + ftc.getTable(FigureConstant.AGENT_TABLE));
} else {
sb.append(" " + ftc.getTable(FigureConstant.AGENT_TABLE));
}
sb.append(" summarise the stakeholders.");
section.add(createParagraph(sb.toString()));
if (roles.size() > 0) {
List<String[]> headers = new ArrayList<String[]>();
headers.add(new String[] { "Role" });
headers.add(new String[] { "Description" });
headers.add(new String[] { "Mission" });
headers.add(new String[] { "Purpose" });
PdfPTable table = createTable(headers);
for (Role r : roles) {
table.addCell(getContentCell(r.getName()));
table.addCell(getContentCell(r.getDescription()));
table.addCell(getContentCell(r.getMission()));
table.addCell(getContentCell(r.getPurpose()));
}
addTableCaption(table, ftc.getTable(FigureConstant.ROLE_TABLE) + " - Roles in the " + getProjectName() + " project.");
section.add(table);
table.setComplete(true);
section.add(getDefaultParagraph());
}
if (agents.size() > 0) {
List<String[]> headers = new ArrayList<String[]>();
headers.add(new String[] { "Agent" });
headers.add(new String[] { "Description" });
headers.add(new String[] { "Abilities" });
headers.add(new String[] { "Important", "Features" });
headers.add(new String[] { "Certifications", "Accreditations" });
headers.add(new String[] { "Type Of", "Organisation" });
PdfPTable table = createTable(headers);
for (Agent a : agents) {
table.addCell(getContentCell(a.getName()));
table.addCell(getContentCell(a.getDescription()));
table.addCell(getContentCell(a.getAbilities()));
table.addCell(getContentCell(a.getOtherImportantFeatures()));
table.addCell(getContentCell(a.getPossessedCertificationsAndAccreditations()));
table.addCell(getContentCell(a.getTypeOfOrganisation()));
}
addTableCaption(table, ftc.getTable(FigureConstant.AGENT_TABLE) + " - Agents in the " + getProjectName() + " project");
section.add(table);
table.setComplete(true);
section.add(getDefaultParagraph());
}
sb = new StringBuilder();
List<Play> plays = new ArrayList<Play>();
for (Actor a : getStakeholderActors()) {
if (a instanceof Agent) {
for (Play p : ((Agent) a).getPlayedRoles()) {
if (p.getTarget() != null)
plays.add(p);
}
}
}
if (plays.size() > 0) {
section.add(createParagraph("Agents and roles are related by means of %i play % relations, as reported on " + ftc.getTable(FigureConstant.PLAY_TABLE)));
List<String[]> headers = new ArrayList<String[]>();
headers.add(new String[] { "Agent" });
headers.add(new String[] { "Role" });
PdfPTable table = createTable(headers);
for (Play p : plays) {
table.addCell(getContentCell(p.getSource().getName()));
table.addCell(getContentCell(p.getTarget().getName()));
}
addTableCaption(table, ftc.getTable(FigureConstant.PLAY_TABLE) + " - Agent/Role relations in the " + getProjectName() + " project");
section.add(table);
table.setComplete(true);
} else {
section.add(createParagraph("In the " + getProjectName() + " project there are no plays relationships taking place for the given agents/roles."));
}
}
section.setComplete(true);
section.setTriggerNewPage(true);
}Example 52
| Project: spin-suite-master File: ReportPrintData.java View source code |
/**
* Create a PDF File
* @author <a href="mailto:yamelsenih@gmail.com">Yamel Senih</a> 02/04/2014, 22:52:09
* @param outFile
* @throws FileNotFoundException
* @throws DocumentException
* @return void
*/
private void createPDF(File outFile) throws FileNotFoundException, DocumentException {
Document document = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outFile));
PDFHeaderAndFooter event = new PDFHeaderAndFooter();
writer.setPageEvent(event);
document.open();
//
document.addAuthor(ctx.getResources().getString(R.string.app_name));
document.addCreationDate();
//
Paragraph title = new Paragraph(m_reportQuery.getInfoReport().getName());
// Set Font
title.getFont().setStyle(Font.BOLD);
// Set Alignment
title.setAlignment(Paragraph.ALIGN_CENTER);
// Add Title
document.add(title);
// Add New Line
document.add(Chunk.NEWLINE);
// Parameters
ProcessInfoParameter[] param = m_pi.getParameter();
// Get Parameter
if (param != null) {
//
boolean isFirst = true;
// Iterate
for (ProcessInfoParameter para : param) {
// Get SQL Name
String name = para.getInfo();
StringBuffer textParameter = new StringBuffer();
if (para.getParameter() == null && para.getParameter_To() == null)
continue;
else {
// Add Parameters Title
if (isFirst) {
Paragraph titleParam = new Paragraph(ctx.getResources().getString(R.string.msg_ReportParameters));
// Set Font
titleParam.getFont().setStyle(Font.BOLDITALIC);
// Add to Document
document.add(titleParam);
isFirst = false;
}
// Add Parameters Name
if (para.getParameter() != null && // From and To is filled
para.getParameter_To() != null) {
//
textParameter.append(name).append(" => ").append(para.getDisplayValue()).append(" <= ").append(para.getDisplayValue_To());
} else if (// Only From
para.getParameter() != null) {
//
textParameter.append(name).append(" = ").append(para.getDisplayValue());
} else if (// Only To
para.getParameter_To() != // Only To
null) {
//
textParameter.append(name).append(" <= ").append(para.getDisplayValue_To());
}
}
// Add to Document
Paragraph viewParam = new Paragraph(textParameter.toString());
document.add(viewParam);
}
}
document.add(Chunk.NEWLINE);
//
InfoReportField[] columns = m_reportQuery.getColumns();
// Add Table
PdfPTable table = new PdfPTable(columns.length);
table.setSpacingBefore(4);
// Add Header
PdfPCell headerCell = new PdfPCell(new Phrase(m_reportQuery.getInfoReport().getName()));
headerCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
headerCell.setColspan(columns.length);
// Add to Table
table.addCell(headerCell);
// Add Header
// Decimal and Date Format
DecimalFormat[] cDecimalFormat = new DecimalFormat[columns.length];
SimpleDateFormat[] cDateFormat = new SimpleDateFormat[columns.length];
for (int i = 0; i < columns.length; i++) {
InfoReportField column = columns[i];
// Only Numeric
if (DisplayType.isNumeric(column.DisplayType))
cDecimalFormat[i] = DisplayType.getNumberFormat(ctx, column.DisplayType, column.FormatPattern);
else // Only Date
if (DisplayType.isDate(column.DisplayType))
cDateFormat[i] = DisplayType.getDateFormat(ctx, column.DisplayType, column.FormatPattern);
//
Phrase phrase = new Phrase(column.PrintName);
PdfPCell cell = new PdfPCell(phrase);
if (column.FieldAlignmentType.equals(InfoReportField.FIELD_ALIGNMENT_TYPE_TRAILING_RIGHT))
cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
else if (column.FieldAlignmentType.equals(InfoReportField.FIELD_ALIGNMENT_TYPE_CENTER))
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
else
cell.setHorizontalAlignment(PdfPCell.ALIGN_UNDEFINED);
//
table.addCell(cell);
}
// Add Detail
for (int row = 0; row < m_data.size(); row++) {
// Get Row
RowPrintData rPrintData = m_data.get(row);
// Iterate
for (int col = 0; col < columns.length; col++) {
InfoReportField column = columns[col];
ColumnPrintData cPrintData = rPrintData.get(col);
Phrase phrase = null;
PdfPCell cell = new PdfPCell();
//
String value = cPrintData.getValue();
if (DisplayType.isNumeric(column.DisplayType)) {
// Number
// Format
DecimalFormat decimalFormat = cDecimalFormat[col];
// Format
if (decimalFormat != null)
value = decimalFormat.format(DisplayType.getNumber(value));
// Set Value
cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
} else if (// Is Date
DisplayType.isDate(column.DisplayType)) {
SimpleDateFormat dateFormat = cDateFormat[col];
if (dateFormat != null) {
long date = Long.getLong(value, 0);
value = dateFormat.format(new Date(date));
}
}
// Set Value
phrase = new Phrase(value);
//
if (column.FieldAlignmentType.equals(InfoReportField.FIELD_ALIGNMENT_TYPE_TRAILING_RIGHT))
cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
else if (column.FieldAlignmentType.equals(InfoReportField.FIELD_ALIGNMENT_TYPE_CENTER))
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
else
cell.setHorizontalAlignment(PdfPCell.ALIGN_UNDEFINED);
// Set Font
if (rPrintData.isFunctionRow()) {
// Set Function Value
if (cPrintData.getFunctionValue() != null && cPrintData.getFunctionValue().length() > 0)
phrase = new Phrase(cPrintData.getFunctionValue());
// Set Font
phrase.getFont().setStyle(Font.BOLDITALIC);
}
// Add to Table
cell.setPhrase(phrase);
table.addCell(cell);
}
}
// Add Table to Document
document.add(table);
// New Line
document.add(Chunk.NEWLINE);
// Add Footer
StringBuffer footerText = new StringBuffer(Env.getContext(ctx, "#SUser"));
footerText.append("(");
footerText.append(Env.getContext(ctx, "#AD_Role_Name"));
footerText.append("@");
footerText.append(Env.getContext(ctx, "#AD_Client_Name"));
footerText.append(".");
footerText.append(Env.getContext(ctx, "#AD_Org_Name"));
footerText.append("{").append(Build.MANUFACTURER).append(".").append(Build.MODEL).append("}) ");
// Date
SimpleDateFormat pattern = DisplayType.getDateFormat(ctx, DisplayType.DATE_TIME);
footerText.append(" ").append(ctx.getResources().getString(R.string.Date)).append(" = ");
footerText.append(pattern.format(new Date()));
//
Paragraph footer = new Paragraph(footerText.toString());
footer.setAlignment(Paragraph.ALIGN_CENTER);
// Set Font
footer.getFont().setSize(8);
// Add Footer
document.add(footer);
// Close Document
document.close();
}Example 53
| Project: Offene-Pflege.de-master File: PrescriptionTools.java View source code |
@Override
protected Object doInBackground() throws Exception {
String header = SYSTools.xx("nursingrecords.prescription.dailyplan.header1") + " " + DateFormat.getDateInstance().format(new Date()) + " (" + station.getName() + ")";
final PDF pdf = new PDF(null, header, 10);
pdf.getDocument().add(new Header(OPDE.getAppInfo().getSignature(), header));
Paragraph h1 = new Paragraph(new Phrase(header, PDF.plain(PDF.sizeH1())));
h1.setAlignment(Element.ALIGN_CENTER);
pdf.getDocument().add(h1);
// pdf.getDocument().add(Chunk.NEWLINE);
Paragraph p = new Paragraph(SYSTools.xx("nursingrecords.prescription.dailyplan.warning"));
p.setAlignment(Element.ALIGN_CENTER);
pdf.getDocument().add(p);
pdf.getDocument().add(Chunk.NEWLINE);
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
int progress = -1;
OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, data.size()));
String resID = "";
PdfPTable table = null;
for (Object obj : data) {
progress++;
OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, data.size()));
Object[] objects = (Object[]) obj;
Prescription prescription = em.find(Prescription.class, ((BigInteger) objects[0]).longValue());
PrescriptionSchedule schedule = em.find(PrescriptionSchedule.class, ((BigInteger) objects[1]).longValue());
BigInteger bestid = (BigInteger) objects[2];
BigInteger formid = (BigInteger) objects[4];
// Alle Formen, die nicht abzählbar sind, werden grau hinterlegt. Also Tropfen, Spritzen etc.
boolean gray = false;
if (formid != null) {
DosageForm form = em.find(DosageForm.class, formid.longValue());
gray = form.getDailyPlan() > 0;
}
/***
* _ _
* | |__ ___ __ _ __| |
* | '_ \ / _ \/ _` |/ _` |
* | | | | __/ (_| | (_| |
* |_| |_|\___|\__,_|\__,_|
*
*/
// If the resident changes in the list. We need to restart a new table.
boolean residentChanges = !resID.equalsIgnoreCase(prescription.getResident().getRID());
if (residentChanges) {
// the table has to be closed every time the resident changes. But not the first time... obviously
if (table != null) {
pdf.getDocument().add(table);
pdf.getDocument().add(Chunk.NEWLINE);
}
table = new PdfPTable(new float[] { 6, 1, 1, 1, 1, 1, 1, 6 });
table.setTotalWidth(Utilities.millimetersToPoints(180));
table.setLockedWidth(true);
PdfPCell cell = new PdfPCell(new Phrase(ResidentTools.getLabelText(prescription.getResident()), whiteFont));
cell.setBackgroundColor(BaseColor.BLACK);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_TOP);
cell.setColspan(8);
table.addCell(cell);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
// table.getDefaultCell().setBackgroundColor(null);
table.addCell(PDF.cell("nursingrecords.prescription.dailyplan.table.col1", PDF.bold(), Element.ALIGN_CENTER, Element.ALIGN_MIDDLE));
table.addCell(PDF.cell("misc.msg.earlyinthemorning.short", PDF.bold(), Element.ALIGN_CENTER, Element.ALIGN_MIDDLE));
table.addCell(PDF.cell("misc.msg.morning.short", PDF.bold(), Element.ALIGN_CENTER, Element.ALIGN_MIDDLE));
table.addCell(PDF.cell("misc.msg.noon.short", PDF.bold(), Element.ALIGN_CENTER, Element.ALIGN_MIDDLE));
table.addCell(PDF.cell("misc.msg.afternoon.short", PDF.bold(), Element.ALIGN_CENTER, Element.ALIGN_MIDDLE));
table.addCell(PDF.cell("misc.msg.evening.short", PDF.bold(), Element.ALIGN_CENTER, Element.ALIGN_MIDDLE));
table.addCell(PDF.cell("misc.msg.lateatnight.short", PDF.bold(), Element.ALIGN_CENTER, Element.ALIGN_MIDDLE));
table.addCell(PDF.cell("misc.msg.comment", PDF.bold(), Element.ALIGN_CENTER, Element.ALIGN_MIDDLE));
table.setHeaderRows(2);
resID = prescription.getResident().getRID();
}
/***
* _ _
* ___ ___ _ __ | |_ ___ _ __ | |_
* / __/ _ \| '_ \| __/ _ \ '_ \| __|
* | (_| (_) | | | | || __/ | | | |_
* \___\___/|_| |_|\__\___|_| |_|\__|
*
*/
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_LEFT);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_TOP);
if (gray) {
table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
}
Phrase col1 = getShortDescriptionAsPhrase(prescription);
if (bestid != null) {
MedStock stock = em.find(MedStock.class, bestid.longValue());
col1.add(Chunk.NEWLINE);
col1.add(PDF.chunk(SYSTools.xx("nursingrecords.prescription.dailyplan.stockInUse") + " " + SYSTools.xx("misc.msg.number") + " " + stock.getID(), PDF.italic()));
String warning = "";
warning += (stock.expiresIn(7) ? "!!" : "");
warning += (stock.expiresIn(0) ? "!!!!" : "");
// variable expiry ?
if (stock.getTradeForm().getDaysToExpireAfterOpened() != null) {
col1.add(Chunk.NEWLINE);
col1.add(PDF.chunk(warning + " " + SYSTools.xx("misc.msg.expiresAfterOpened") + ": " + df.format(new DateTime(stock.getOpened()).plusDays(stock.getTradeForm().getDaysToExpireAfterOpened()).toDate())));
}
if (stock.getExpires() != null) {
DateFormat sdf = df;
// if expiry is at the end of a month then it has a different format
if (new LocalDate(stock.getExpires()).equals(new LocalDate(stock.getExpires()).dayOfMonth().withMaximumValue())) {
sdf = new SimpleDateFormat("MM/yy");
}
col1.add(Chunk.NEWLINE);
col1.add(PDF.chunk(SYSTools.xx("misc.msg.expires") + ": " + sdf.format(stock.getExpires())));
}
}
table.addCell(col1);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
if (schedule.usesTime()) {
PdfPCell cellTime = new PdfPCell();
cellTime.setHorizontalAlignment(Element.ALIGN_CENTER);
cellTime.setVerticalAlignment(Element.ALIGN_MIDDLE);
cellTime.setColspan(6);
Chunk timeChunk = PDF.chunk(DateFormat.getTimeInstance(DateFormat.SHORT).format(schedule.getUhrzeit()) + " " + SYSTools.xx("misc.msg.Time.short"), PDF.bold());
timeChunk.setUnderline(0.4f, -1f);
Phrase contentTime = new Phrase();
contentTime.setFont(PDF.plain());
// this is only as a workaround until i figure out to align cells with a colspan.
Chunk tab1 = new Chunk(new VerticalPositionMark(), 40, false);
contentTime.add(tab1);
contentTime.add(timeChunk);
contentTime.add(" ");
contentTime.add(PDF.getAsPhrase(schedule.getUhrzeitDosis()));
contentTime.add(schedule.getPrescription().hasMed() ? " " + SYSConst.UNITS[schedule.getPrescription().getTradeForm().getDosageForm().getUsageUnit()] : "x");
contentTime.add(Chunk.NEWLINE);
contentTime.add(" ");
cellTime.addElement(contentTime);
table.addCell(cellTime);
} else {
table.addCell(PDF.getAsPhrase(schedule.getNachtMo()));
table.addCell(PDF.getAsPhrase(schedule.getMorgens()));
table.addCell(PDF.getAsPhrase(schedule.getMittags()));
table.addCell(PDF.getAsPhrase(schedule.getNachmittags()));
table.addCell(PDF.getAsPhrase(schedule.getAbends()));
table.addCell(PDF.getAsPhrase(schedule.getNachtAb()));
}
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_JUSTIFIED);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_TOP);
table.addCell(PrescriptionScheduleTools.getRemarkAsPhrase(schedule));
table.getDefaultCell().setBackgroundColor(null);
}
pdf.getDocument().add(table);
pdf.getDocument().close();
return pdf;
}Example 54
| Project: tnoodle-master File: ScrambleRequest.java View source code |
private static void addScrambles(PdfWriter docWriter, Document doc, ScrambleRequest scrambleRequest, String globalTitle) throws DocumentException, IOException {
if (scrambleRequest.fmc) {
Rectangle pageSize = doc.getPageSize();
for (int i = 0; i < scrambleRequest.scrambles.length; i++) {
String scramble = scrambleRequest.scrambles[i];
PdfContentByte cb = docWriter.getDirectContent();
float LINE_THICKNESS = 0.5f;
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
int bottom = 30;
int left = 35;
int right = (int) (pageSize.getWidth() - left);
int top = (int) (pageSize.getHeight() - bottom);
int height = top - bottom;
int width = right - left;
int solutionBorderTop = bottom + (int) (height * .5);
int scrambleBorderTop = solutionBorderTop + 40;
int competitorInfoBottom = top - (int) (height * .15);
int gradeBottom = competitorInfoBottom - 50;
int competitorInfoLeft = right - (int) (width * .45);
int rulesRight = competitorInfoLeft;
int padding = 5;
// Outer border
cb.setLineWidth(2f);
cb.moveTo(left, top);
cb.lineTo(left, bottom);
cb.lineTo(right, bottom);
cb.lineTo(right, top);
// Solution border
cb.moveTo(left, solutionBorderTop);
cb.lineTo(right, solutionBorderTop);
// Rules bottom border
cb.moveTo(left, scrambleBorderTop);
cb.lineTo(rulesRight, scrambleBorderTop);
// Rules right border
cb.lineTo(rulesRight, gradeBottom);
// Grade bottom border
cb.moveTo(competitorInfoLeft, gradeBottom);
cb.lineTo(right, gradeBottom);
// Competitor info bottom border
cb.moveTo(competitorInfoLeft, competitorInfoBottom);
cb.lineTo(right, competitorInfoBottom);
// Competitor info left border
cb.moveTo(competitorInfoLeft, gradeBottom);
cb.lineTo(competitorInfoLeft, top);
// Solution lines
int availableSolutionWidth = right - left;
int availableSolutionHeight = scrambleBorderTop - bottom;
int lineWidth = 25;
//int linesX = (availableSolutionWidth/lineWidth + 1)/2;
int linesX = 10;
int linesY = (int) Math.ceil(1.0 * WCA_MAX_MOVES_FMC / linesX);
cb.setLineWidth(LINE_THICKNESS);
cb.stroke();
// int allocatedX = (2*linesX-1)*lineWidth;
int excessX = availableSolutionWidth - linesX * lineWidth;
int moveCount = 0;
solutionLines: for (int y = 0; y < linesY; y++) {
for (int x = 0; x < linesX; x++) {
if (moveCount >= WCA_MAX_MOVES_FMC) {
break solutionLines;
}
int xPos = left + x * lineWidth + (x + 1) * excessX / (linesX + 1);
int yPos = solutionBorderTop - (y + 1) * availableSolutionHeight / (linesY + 1);
cb.moveTo(xPos, yPos);
cb.lineTo(xPos + lineWidth, yPos);
moveCount++;
}
}
float UNDERLINE_THICKNESS = 0.2f;
cb.setLineWidth(UNDERLINE_THICKNESS);
cb.stroke();
cb.beginText();
int availableScrambleSpace = right - left - 2 * padding;
int scrambleFontSize = 20;
String scrambleStr = "Scramble: " + scramble;
float scrambleWidth;
do {
scrambleFontSize--;
scrambleWidth = bf.getWidthPoint(scrambleStr, scrambleFontSize);
} while (scrambleWidth > availableScrambleSpace);
cb.setFontAndSize(bf, scrambleFontSize);
int scrambleY = 3 + solutionBorderTop + (scrambleBorderTop - solutionBorderTop - scrambleFontSize) / 2;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, scrambleStr, left + padding, scrambleY, 0);
cb.endText();
int availableScrambleWidth = right - rulesRight;
int availableScrambleHeight = gradeBottom - scrambleBorderTop;
Dimension dim = scrambleRequest.scrambler.getPreferredSize(availableScrambleWidth - 2, availableScrambleHeight - 2);
PdfTemplate tp = cb.createTemplate(dim.width, dim.height);
Graphics2D g2 = new PdfGraphics2D(tp, dim.width, dim.height, new DefaultFontMapper());
try {
Svg svg = scrambleRequest.scrambler.drawScramble(scramble, scrambleRequest.colorScheme);
drawSvgToGraphics2D(svg, g2, dim);
} catch (InvalidScrambleException e) {
l.log(Level.INFO, "", e);
} finally {
g2.dispose();
}
cb.addImage(Image.getInstance(tp), dim.width, 0, 0, dim.height, rulesRight + (availableScrambleWidth - dim.width) / 2, scrambleBorderTop + (availableScrambleHeight - dim.height) / 2);
ColumnText ct = new ColumnText(cb);
int fontSize = 15;
int marginBottom = 10;
int offsetTop = 27;
boolean showScrambleCount = scrambleRequest.scrambles.length > 1;
if (showScrambleCount) {
offsetTop -= fontSize + 2;
}
cb.beginText();
cb.setFontAndSize(bf, fontSize);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, globalTitle, competitorInfoLeft + (right - competitorInfoLeft) / 2, top - offsetTop, 0);
offsetTop += fontSize + 2;
cb.endText();
cb.beginText();
cb.setFontAndSize(bf, fontSize);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, scrambleRequest.title, competitorInfoLeft + (right - competitorInfoLeft) / 2, top - offsetTop, 0);
cb.endText();
if (showScrambleCount) {
cb.beginText();
offsetTop += fontSize + 2;
cb.setFontAndSize(bf, fontSize);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Scramble " + (i + 1) + " of " + scrambleRequest.scrambles.length, competitorInfoLeft + (right - competitorInfoLeft) / 2, top - offsetTop, 0);
cb.endText();
}
offsetTop += fontSize + marginBottom;
cb.beginText();
fontSize = 15;
cb.setFontAndSize(bf, fontSize);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Competitor: __________________", competitorInfoLeft + padding, top - offsetTop, 0);
offsetTop += fontSize + marginBottom;
cb.endText();
cb.beginText();
fontSize = 15;
cb.setFontAndSize(bf, fontSize);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "WCA ID:", competitorInfoLeft + padding, top - offsetTop, 0);
cb.setFontAndSize(bf, 19);
int wcaIdLength = 63;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "_ _ _ _ _ _ _ _ _ _", competitorInfoLeft + padding + wcaIdLength, top - offsetTop, 0);
offsetTop += fontSize + (int) (marginBottom * 1.8);
cb.endText();
cb.beginText();
fontSize = 11;
cb.setFontAndSize(bf, fontSize);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "DO NOT FILL IF YOU ARE THE COMPETITOR", competitorInfoLeft + (right - competitorInfoLeft) / 2, top - offsetTop, 0);
offsetTop += fontSize + marginBottom;
cb.endText();
cb.beginText();
fontSize = 11;
cb.setFontAndSize(bf, fontSize);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Graded by: _______________ Result: ______", competitorInfoLeft + (right - competitorInfoLeft) / 2, top - offsetTop, 0);
offsetTop += fontSize + marginBottom;
cb.endText();
cb.beginText();
cb.setFontAndSize(bf, 25f);
// kill me now
int MAGIC_NUMBER = 40;
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Fewest Moves", left + (competitorInfoLeft - left) / 2, top - MAGIC_NUMBER, 0);
cb.endText();
com.itextpdf.text.List rules = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
rules.add("Notate your solution by writing one move per bar.");
rules.add("To delete moves, clearly erase/blacken them.");
rules.add("Face moves F, B, R, L, U, and D are clockwise.");
rules.add("Rotations x, y, and z follow R, U, and F.");
rules.add("' inverts a move; 2 doubles a move. (e.g.: U', U2)");
rules.add("w makes a face move into two layers. (e.g.: Uw)");
rules.add("A [lowercase] move is a cube rotation. (e.g.: [u])");
ct.addElement(rules);
int rulesTop = competitorInfoBottom + 55;
ct.setSimpleColumn(left + padding, scrambleBorderTop, competitorInfoLeft - padding, rulesTop, 0, Element.ALIGN_LEFT);
ct.go();
rules = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
rules.add("You have 1 hour to find a solution.");
rules.add("Your solution length will be counted in OBTM.");
int maxMoves = WCA_MAX_MOVES_FMC;
rules.add("Your solution must be at most " + maxMoves + " moves, including rotations.");
rules.add("Your solution must not be directly derived from any part of the scrambling algorithm.");
ct.addElement(rules);
// kill me now
MAGIC_NUMBER = 150;
ct.setSimpleColumn(left + padding, scrambleBorderTop, rulesRight - padding, rulesTop - MAGIC_NUMBER, 0, Element.ALIGN_LEFT);
ct.go();
doc.newPage();
}
} else {
Rectangle pageSize = doc.getPageSize();
float sideMargins = 100 + doc.leftMargin() + doc.rightMargin();
float availableWidth = pageSize.getWidth() - sideMargins;
float vertMargins = doc.topMargin() + doc.bottomMargin();
float availableHeight = pageSize.getHeight() - vertMargins;
if (scrambleRequest.extraScrambles.length > 0) {
// Yeee magic numbers. This should make space for the headerTable.
availableHeight -= 20;
}
int scramblesPerPage = Math.min(MAX_SCRAMBLES_PER_PAGE, scrambleRequest.getAllScrambles().size());
int maxScrambleImageHeight = (int) (availableHeight / scramblesPerPage - 2 * SCRAMBLE_IMAGE_PADDING);
// We don't let scramble images take up more than half the page
int maxScrambleImageWidth = (int) (availableWidth / 2);
if (scrambleRequest.scrambler.getShortName().equals("minx")) {
// TODO - If we allow the megaminx image to be too wide, the
// megaminx scrambles get really tiny. This tweak allocates
// a more optimal amount of space to the scrambles. This is possible
// because the scrambles are so uniformly sized.
maxScrambleImageWidth = 190;
}
Dimension scrambleImageSize = scrambleRequest.scrambler.getPreferredSize(maxScrambleImageWidth, maxScrambleImageHeight);
// First do a dry run just to see if any scrambles require highlighting.
// Then do the real run, and force highlighting on every scramble
// if any scramble required it.
boolean forceHighlighting = false;
for (boolean dryRun : new boolean[] { true, false }) {
String scrambleNumberPrefix = "";
TableAndHighlighting tableAndHighlighting = createTable(docWriter, doc, sideMargins, scrambleImageSize, scrambleRequest.scrambles, scrambleRequest.scrambler, scrambleRequest.colorScheme, scrambleNumberPrefix, forceHighlighting);
if (dryRun) {
if (tableAndHighlighting.highlighting) {
forceHighlighting = true;
continue;
}
} else {
doc.add(tableAndHighlighting.table);
}
if (scrambleRequest.extraScrambles.length > 0) {
PdfPTable headerTable = new PdfPTable(1);
headerTable.setTotalWidth(new float[] { availableWidth });
headerTable.setLockedWidth(true);
PdfPCell extraScramblesHeader = new PdfPCell(new Paragraph("Extra scrambles"));
extraScramblesHeader.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
extraScramblesHeader.setPaddingBottom(3);
headerTable.addCell(extraScramblesHeader);
if (!dryRun) {
doc.add(headerTable);
}
scrambleNumberPrefix = "E";
TableAndHighlighting extraTableAndHighlighting = createTable(docWriter, doc, sideMargins, scrambleImageSize, scrambleRequest.extraScrambles, scrambleRequest.scrambler, scrambleRequest.colorScheme, scrambleNumberPrefix, forceHighlighting);
if (dryRun) {
if (tableAndHighlighting.highlighting) {
forceHighlighting = true;
continue;
}
} else {
doc.add(extraTableAndHighlighting.table);
}
}
}
}
doc.newPage();
}Example 55
| Project: loadgenerator-master File: MainController.java View source code |
@RequestMapping(value = "/createsummary", method = RequestMethod.POST)
@ResponseBody
public String createSummary(HttpSession session) throws Exception, SuspendExecution {
// System.out.println(session.getId());
Document document = new Document();
float fntSize, lineSpacing;
List<Output> outputlist = new ArrayList<Output>();
if (normaltest.getTest())
outputlist = normaltest.getOutputlist();
else if (randomtest.getTest())
outputlist = randomtest.getOutputlist();
else if (dbtest.getTest())
outputlist = dbtest.getOutputlist();
else if (wstest.getTest())
outputlist = wstest.getOutputlist();
fntSize = 16f;
lineSpacing = 10f;
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("webapps/LoadGen/resources/tmpFiles/" + session.getId() + "summary.pdf"));
document.open();
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
Paragraph heading = new Paragraph(new Phrase(lineSpacing, "Test Summary", FontFactory.getFont(FontFactory.COURIER, fntSize)));
heading.setAlignment(Element.ALIGN_CENTER);
document.add(heading);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
for (int i = 0; i < outputlist.size(); i++) {
Paragraph title = new Paragraph(outputlist.get(i).getRequest());
document.add(Chunk.NEWLINE);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
PdfPTable table = new // 2 columns.
PdfPTable(// 2 columns.
5);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
// Width 100%
table.setWidthPercentage(// Width 100%
90);
// Space before table
table.setSpacingBefore(10f);
// Space after table
table.setSpacingAfter(10f);
float[] columnWidths = { 1f, 1f, 1f, 1f, 1f };
table.setWidths(columnWidths);
PdfPCell cell1 = new PdfPCell(new Paragraph("Request Rate"));
cell1.setBorderColor(BaseColor.BLACK);
cell1.setPaddingLeft(10);
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell2 = new PdfPCell(new Paragraph("Duration"));
cell2.setBorderColor(BaseColor.BLACK);
cell2.setPaddingLeft(10);
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell3 = new PdfPCell(new Paragraph("Average Throughput"));
cell3.setBorderColor(BaseColor.BLACK);
cell3.setPaddingLeft(10);
cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell4 = new PdfPCell(new Paragraph("Average Response Time"));
cell4.setBorderColor(BaseColor.BLACK);
cell4.setPaddingLeft(10);
cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell5 = new PdfPCell(new Paragraph("Error Rate"));
cell5.setBorderColor(BaseColor.BLACK);
cell5.setPaddingLeft(10);
cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell6 = new PdfPCell(new Paragraph(outputlist.get(i).getInputload()));
cell6.setBorderColor(BaseColor.BLACK);
cell6.setPaddingLeft(10);
cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);
// System.out.println("durt"+ outputlist.get(i).getDuration());
PdfPCell cell7 = new PdfPCell(new Paragraph(outputlist.get(i).getDuration() + " sec"));
cell7.setBorderColor(BaseColor.BLACK);
cell7.setPaddingLeft(10);
cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell8 = new PdfPCell(new Paragraph(outputlist.get(i).getAvgThroughput()));
cell8.setBorderColor(BaseColor.BLACK);
cell8.setPaddingLeft(10);
cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell9 = new PdfPCell(new Paragraph(outputlist.get(i).getAvgResponsetime()));
cell9.setBorderColor(BaseColor.BLACK);
cell9.setPaddingLeft(10);
cell9.setHorizontalAlignment(Element.ALIGN_CENTER);
cell9.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell10 = new PdfPCell(new Paragraph(outputlist.get(i).getErrorrate()));
cell10.setBorderColor(BaseColor.BLACK);
cell10.setPaddingLeft(10);
cell10.setHorizontalAlignment(Element.ALIGN_CENTER);
cell10.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
table.addCell(cell5);
table.addCell(cell6);
table.addCell(cell7);
table.addCell(cell8);
table.addCell(cell9);
table.addCell(cell10);
document.add(table);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
DefaultCategoryDataset tptgraph = new DefaultCategoryDataset();
try (BufferedReader br = new BufferedReader(new FileReader("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "tpt.txt"))) {
// tptgraph.addValue(0, "Throughput" , 0" );
for (String line; (line = br.readLine()) != null; ) {
// process the line.
String values[] = line.split(" ", 2);
tptgraph.addValue(Integer.parseInt(values[1]), "Throughput", values[0]);
}
// line is not visible here.
}
JFreeChart lineChartObject = ChartFactory.createLineChart("Time Vs Throughput", "Time", "Throughput", tptgraph, PlotOrientation.VERTICAL, true, true, false);
int width = 640;
int height = 480;
File lineChart = new File("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "tpt.jpeg");
ChartUtilities.saveChartAsJPEG(lineChart, lineChartObject, width, height);
DefaultCategoryDataset respgraph = new DefaultCategoryDataset();
try (BufferedReader br = new BufferedReader(new FileReader("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "resp.txt"))) {
for (String line; (line = br.readLine()) != null; ) {
// process the line.
String values[] = line.split(" ", 2);
respgraph.addValue(Integer.parseInt(values[1]), "Response Time", values[0]);
}
// line is not visible here.
}
lineChartObject = ChartFactory.createLineChart("Time Vs Response Time", "Time", "Response Time", respgraph, PlotOrientation.VERTICAL, true, true, false);
lineChart = new File("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "resp.jpeg");
ChartUtilities.saveChartAsJPEG(lineChart, lineChartObject, width, height);
DefaultCategoryDataset errgraph = new DefaultCategoryDataset();
try (BufferedReader br = new BufferedReader(new FileReader("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "err.txt"))) {
for (String line; (line = br.readLine()) != null; ) {
// process the line.
String values[] = line.split(" ", 2);
errgraph.addValue(Integer.parseInt(values[1]), "Error Rate", values[0]);
}
// line is not visible here.
}
lineChartObject = ChartFactory.createLineChart("Time Vs Error Rate", "Time", "Error Rate", errgraph, PlotOrientation.VERTICAL, true, true, false);
lineChart = new File("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "err.jpeg");
ChartUtilities.saveChartAsJPEG(lineChart, lineChartObject, width, height);
table = new PdfPTable(3);
table.setWidthPercentage(100);
table.addCell(createImageCell("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "tpt.jpeg"));
table.addCell(createImageCell("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "resp.jpeg"));
table.addCell(createImageCell("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "err.jpeg"));
document.add(table);
}
document.addAuthor("Stanly Thomas");
document.addCreationDate();
document.addCreator("LoadGen.com");
document.addTitle("Test Summary");
document.addSubject("The summary of the load test");
document.close();
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
for (int i = 0; i < outputlist.size(); i++) {
File file = new File("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "tpt.jpeg");
deleteFolder(file);
file = new File("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "tpt.txt");
deleteFolder(file);
file = new File("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "resp.jpeg");
deleteFolder(file);
file = new File("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "resp.txt");
deleteFolder(file);
file = new File("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "err.txt");
deleteFolder(file);
file = new File("webapps/LoadGen/resources/tmpFiles/" + session.getId() + outputlist.get(i).getRequest() + "err.jpeg");
deleteFolder(file);
}
}
return "success";
}Example 56
| Project: wabacus-master File: AbsReportType.java View source code |
protected void showTitleOnPdf() throws Exception {
PdfPTable tableTitle = new PdfPTable(1);
tableTitle.setTotalWidth(pdfwidth);
//è®¾ç½®è¡¨æ ¼çš„å®½åº¦å›ºå®š
tableTitle.setLockedWidth(true);
int titlefontsize = 0;
if (this.pdfbean != null)
titlefontsize = this.pdfbean.getTitlefontsize();
if (titlefontsize <= 0)
titlefontsize = 10;
Font headFont = new Font(PdfAssistant.getInstance().getBfChinese(), titlefontsize, Font.BOLD);
PdfPCell cell = new PdfPCell(new Paragraph(rbean.getTitle(rrequest) + " " + rbean.getSubtitle(rrequest), headFont));
cell.setColspan(1);
cell.setBorder(0);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
tableTitle.addCell(cell);
document.add(tableTitle);
}Example 57
| Project: jextractor-master File: PdfIntegrationArchive.java View source code |
private PdfPTable createTable(String[] collumns) throws DocumentException { PdfPTable table = new PdfPTable(collumns.length); for (String collumn : collumns) { PdfPCell cell = new PdfPCell(new Phrase(collumn)); cell.setColspan(3); table.addCell(cell); } this.pdfTable = table; return table; }