Java Code Examples for com.itextpdf.text.Paragraph

The following are top voted examples for showing how to use com.itextpdf.text.Paragraph. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tellervo   File: ProSheet.java   Source Code and License 9 votes vote down vote up
private Paragraph getObjectDescription() 
{

	Paragraph p = new Paragraph();
	p.setLeading(0, 1.2f);
	p.setAlignment(Element.ALIGN_JUSTIFIED);
       p.setSpacingAfter(10);
       p.setSpacingBefore(50);
       
	if(o.getDescription()!=null){
		p.add(new Chunk(o.getDescription(), bodyFont));
	}
	else{
		p.add(new Chunk("No description recorded", bodyFont));
	}
	
	return p;
}
 
Example 2
Project: ureport   File: PageHeaderFooterEvent.java   Source Code and License 8 votes vote down vote up
private PdfPCell buildPdfPCell(HeaderFooter phf,String text,int type){
	PdfPCell cell=new PdfPCell();
	cell.setPadding(0);
	cell.setBorder(Rectangle.NO_BORDER);
	Font font=FontBuilder.getFont(phf.getFontFamily(), phf.getFontSize(), phf.isBold(), phf.isItalic(),phf.isUnderline());
	String fontColor=phf.getForecolor();
	if(StringUtils.isNotEmpty(fontColor)){
		String[] color=fontColor.split(",");
		font.setColor(Integer.valueOf(color[0]), Integer.valueOf(color[1]), Integer.valueOf(color[2]));			
	}
	Paragraph graph=new Paragraph(text,font);
	cell.setPhrase(graph);
	switch(type){
	case 1:
		cell.setHorizontalAlignment(Element.ALIGN_LEFT);
		break;
	case 2:
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		break;
	case 3:
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		break;
	}
	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	return cell;
}
 
Example 3
Project: FOXopen   File: InputField.java   Source Code and License 8 votes vote down vote up
/**
 * Serialise the input field div and content
 * @param pSerialisationContext
 * @param pSerialiser
 * @param pEvalNode
 */
public void serialise(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, EN pEvalNode) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, INPUT_FIELD_TAG, getInputFieldClasses(), Collections.emptyList());
  pSerialiser.pushElementAttributes(lElementAttributes);

  PdfPTable lTable = pSerialiser.getElementFactory().getTable(1);
  PdfPCell lCell = pSerialiser.getElementFactory().getCell();
  Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();

  pSerialiser.startContainer(ElementContainerFactory.getContainer(lCell, lCellParagraph));
  mInputFieldContent.addContent(pSerialisationContext, pSerialiser, pEvalNode);
  if (lCellParagraph.isEmpty()) {
    // If there is no cell content in all cells in a table row, the row will be 0 height - add a zero width space to
    // ensure that the input field div isn't collapsed like this (the height will be determined from the cell
    // paragraph font)
    lCellParagraph.add(ZERO_WIDTH_SPACE_CHARACTER);
  }
  pSerialiser.endContainer();

  lTable.addCell(lCell);
  pSerialiser.add(lTable);

  pSerialiser.popElementAttributes();
}
 
Example 4
Project: IMSQTI2PDF   File: PDFCreator.java   Source Code and License 7 votes vote down vote up
public void createPDF(String outputFile, ArrayList<Question> qlist, boolean showCorrectAnswer,
        PageCounter pagecounter, int maximumPageNumber, String inputFolder) throws DocumentException, IOException
{
    _inputFolder = inputFolder;
    Document document = new Document(PageSize.A4, 50, 50, 70, 50);
    PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile));

    pdfwriter.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    pdfwriter.setPageEvent(new HeaderFooter(maximumPageNumber));

    if (pagecounter != null)
    {
        pdfwriter.setPageEvent(pagecounter);
    }

    document.open();

    Paragraph p = new Paragraph();
    // p.setSpacingBefore(SPACING);
    p.setSpacingAfter(SPACING);
    p.setIndentationLeft(INDENTATION);

    writeQuestions(p, document, showCorrectAnswer, qlist);

    document.close();

}
 
Example 5
Project: bdf2   File: PdfReportPageNumber.java   Source Code and License 7 votes vote down vote up
/**
 * Adds a header to every page
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
 *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
	PdfPTable table = new PdfPTable(3);
	try {
		table.setWidths(new int[]{40,5,10});
		table.setTotalWidth(100);
		table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
		Font font=new Font(chineseFont,8);
		font.setColor(new BaseColor(55,55,55));
		Paragraph paragraph=new Paragraph("第   "+writer.getPageNumber()+" 页   共",font);
		paragraph.setAlignment(Element.ALIGN_RIGHT);
		table.addCell(paragraph);
		Image img=Image.getInstance(total);
		img.scaleAbsolute(28, 28);
		PdfPCell cell = new PdfPCell(img);
		cell.setBorder(Rectangle.NO_BORDER);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);
		PdfPCell c = new PdfPCell(new Paragraph("页",font));
		c.setHorizontalAlignment(Element.ALIGN_LEFT);
		c.setBorder(Rectangle.NO_BORDER);
		table.addCell(c);
		float center=(document.getPageSize().getWidth())/2-120/2;
		table.writeSelectedRows(0, -1,center,30, writer.getDirectContent());
	}
	catch(DocumentException de) {
		throw new ExceptionConverter(de);
	}
}
 
Example 6
Project: CPI   File: generarPDF.java   Source Code and License 7 votes vote down vote up
private static void addTitlePage(Document document,Resolucion res)
    throws DocumentException {
  Paragraph preface = new Paragraph();
  // We add one empty line
  addEmptyLine(preface, 1);
  // Lets write a big header
  preface.add(new Paragraph("Consejo Profesional de Informatica de Santiago del Estero", catFont));

  addEmptyLine(preface, 1);
  // Will create: Report generated by: _name, _date
  preface.add(new Paragraph( "Comision Directiva del Consejo, " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      smallBold));
  addEmptyLine(preface, 2);
  preface.add(new Paragraph("Resolucion N°"+res.getNumero_resolucion()+"",
      smallBold));

  addEmptyLine(preface, 3);

  preface.add(new Paragraph("Esta Resolucion de tipo "+res.getTipo()+" formulada para notificar al socio con legajo: "+res.getLegajo_socio()+" de su actual estado como socio del Consejo.\n"
          + res.getDescripcion_solicitud()+" "+res.getDescripcion_resolucion()+" en la fecha "+res.getFecha(),
      cuerpo));

  document.add(preface);
  // Start a new page
  document.newPage();
}
 
Example 7
Project: hotel   File: ResidenceService.java   Source Code and License 7 votes vote down vote up
private void createAccomodationTableHeaders(PdfPTable accomodationsTable) {
	PdfPCell numberHeader = new PdfPCell(new Paragraph("Lp."));
	PdfPCell roomNumberHeader = new PdfPCell(new Paragraph("Nr pokoju"));
	PdfPCell dateFromHeader = new PdfPCell(new Paragraph("Od"));
	PdfPCell dateToHeader = new PdfPCell(new Paragraph("Do"));
	PdfPCell placesHeader = new PdfPCell(new Paragraph("Miejsca"));
	PdfPCell roomTypeHeader = new PdfPCell(new Paragraph("Typ"));
	PdfPCell roomPriceHeader = new PdfPCell(new Paragraph("Cena"));
	accomodationsTable.addCell(numberHeader);
	accomodationsTable.addCell(roomNumberHeader);
	accomodationsTable.addCell(dateFromHeader);
	accomodationsTable.addCell(dateToHeader);
	accomodationsTable.addCell(placesHeader);
	accomodationsTable.addCell(roomTypeHeader);
	accomodationsTable.addCell(roomPriceHeader);
}
 
Example 8
Project: hotel   File: ResidenceService.java   Source Code and License 7 votes vote down vote up
private void createofferInstancesTableContent(List<OfferInstance> offerInstances, PdfPTable offerInstancesTable) {
	DecimalFormat decimalFormat = new DecimalFormat(PRICE_DECIMAL_FORMAT);

	int i = 1;
	for (OfferInstance offerInstance : offerInstances) {
		Offer offer = offerInstance.getOffer();

		PdfPCell numberCell = new PdfPCell(new Paragraph(String.valueOf(i++)));

		String offerName = offer.getName();
		PdfPCell roomNumberCell = new PdfPCell(new Paragraph(offerName));

		String offerPrice = decimalFormat.format(offer.getBaseValue()) + " PLN";
		PdfPCell roomPriceCell = new PdfPCell(new Paragraph(offerPrice));

		offerInstancesTable.addCell(numberCell);
		offerInstancesTable.addCell(roomNumberCell);
		offerInstancesTable.addCell(roomPriceCell);
	}

}
 
Example 9
Project: hotel   File: EmployeeService.java   Source Code and License 7 votes vote down vote up
private void createTableContent(List<CleaningSchedule> cleaningSchedules, PdfPTable cleaningScheduleTable) {
	int i = 1;
	for (CleaningSchedule cleaningSchedule : cleaningSchedules) {
		PdfPCell numberCell = new PdfPCell(new Paragraph(String.valueOf(i++)));
		String roomNumber = cleaningSchedule.getAccomodation().getAllocationEntity().getNumber();
		PdfPCell roomNumberCell = new PdfPCell(new Paragraph(roomNumber));
		String preferredTime = cleaningSchedule.getDesiredTime() == null ? "-" : cleaningSchedule.getDesiredTime().toString("HH:mm");
		PdfPCell preferredTimeCell = new PdfPCell(new Paragraph(preferredTime));
		String note = cleaningSchedule.getNote() == null ? "-" : cleaningSchedule.getNote();
		PdfPCell noteCell = new PdfPCell(new Paragraph(note));
		cleaningScheduleTable.addCell(numberCell);
		cleaningScheduleTable.addCell(roomNumberCell);
		cleaningScheduleTable.addCell(preferredTimeCell);
		cleaningScheduleTable.addCell(noteCell);
	}
}
 
Example 10
Project: ExcelToBarcode   File: MainController.java   Source Code and License 7 votes vote down vote up
/** Shows a blank document, in case of a problem in generating the PDF */
private byte[] showBlank() throws DocumentException {
    final Document document = new Document(PageSize.LETTER); // FIXME - get PageSize from label definition
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
    final PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    document.add(new Paragraph("No data have been uploaded.  The time is: " + new Date()));
    
    final Barcode128 code128 = new Barcode128();
    code128.setGenerateChecksum(true);
    code128.setCode(new Date().toString());
    
    document.add(code128.createImageWithBarcode(writer.getDirectContent(), null, null));
    document.close();
    return baos.toByteArray();
}
 
Example 11
Project: FOXopen   File: FormListWidgetBuilder.java   Source Code and License 7 votes vote down vote up
/**
 * Serialises a form row
 * @param pSerialisationContext
 * @param pSerialiser
 * @param pRowNode The form node
 */
private void addFormRow(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, EvaluatedNodeInfo pRowNode) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, LIST_ROW_TAG, getRowClasses(pRowNode), getRowStyles(pRowNode));
  pSerialiser.pushElementAttributes(lElementAttributes);

  PdfPCell lCell = pSerialiser.getElementFactory().getCell();
  Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();

  pSerialiser.startContainer(ElementContainerFactory.getContainer(lCell, lCellParagraph));
  pSerialiser.getWidgetBuilder(pRowNode.getWidgetBuilderType()).buildWidget(pSerialisationContext, pSerialiser, pRowNode);
  pSerialiser.endContainer();
  pSerialiser.add(lCell);

  pSerialiser.popElementAttributes();
}
 
Example 12
Project: FOXopen   File: ListWidgetBuilder.java   Source Code and License 7 votes vote down vote up
/**
 * Serialises a column header
 * @param pSerialiser
 * @param pHeaderNode The column header node
 */
private void addColumnHeader(PDFSerialiser pSerialiser, EvaluatedNodeInfo pHeaderNode) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, LIST_CELL_TAG, getHeaderClasses(pHeaderNode), getHeaderStyles(pHeaderNode));
  pSerialiser.pushElementAttributes(lElementAttributes);

  PdfPCell lHeaderCell = pSerialiser.getElementFactory().getCell();

  // Add the header prompt to the cell if one exists
  Optional.ofNullable(pHeaderNode.getSummaryPrompt()).ifPresent(pEvaluatedPrompt -> {
    Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();
    pSerialiser.startContainer(ElementContainerFactory.getContainer(lHeaderCell, lCellParagraph));
    pSerialiser.addParagraphText(pSerialiser.getSafeStringAttribute(pEvaluatedPrompt));
    pSerialiser.endContainer();
  });

  pSerialiser.add(lHeaderCell);
  pSerialiser.popElementAttributes();
}
 
Example 13
Project: FOXopen   File: ListWidgetBuilder.java   Source Code and License 7 votes vote down vote up
/**
 * Serialises a list body cell
 * @param pSerialisationContext
 * @param pSerialiser
 * @param pItemNode The item node of the cell if the row and column of the cell has content
 * @param pIsNestedList Whether or not the list if nested, a different class is applied to nested list cells
 */
private void addBodyCell(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, Optional<EvaluatedNodeInfo> pItemNode, boolean pIsNestedList) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, LIST_CELL_TAG, getCellClasses(pItemNode, pIsNestedList), getCellStyles(pItemNode));
  pSerialiser.pushElementAttributes(lElementAttributes);

  PdfPCell lCell = pSerialiser.getElementFactory().getCell();
  Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();

  if (pItemNode.isPresent() && pItemNode.get().getVisibility() != NodeVisibility.DENIED) {
    // Column was found for this row and it isn't denied visibility, add content
    pSerialiser.startContainer(ElementContainerFactory.getContainer(lCell, lCellParagraph));
    pSerialiser.getWidgetBuilder(pItemNode.get().getWidgetBuilderType()).buildWidget(pSerialisationContext, pSerialiser, pItemNode.get());
    pSerialiser.endContainer();
  }

  pSerialiser.add(lCell);
  pSerialiser.popElementAttributes();
}
 
Example 14
Project: iTextTutorial   File: T05_Image.java   Source Code and License 7 votes vote down vote up
public void createPdf(String filename) throws DocumentException, IOException {

		Document document = new Document(PageSize.LETTER);
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));

		// TODO: force iText to respect the order in which content is added
		writer.setStrictImageSequence(true);

		document.open();

		// step 4 - add content into document
		String[] imageNames = { "35_Cal_Crutchlow.jpg", "38_Bradley_Smith.jpg", "46_Valentino_Rossi.jpg",
				"99_Jorge_Lorenzo.jpg" };
		for (int i = 0; i < 4; i++) {

			Image image = Image.getInstance("resources/img/" + imageNames[i]);

			// TODO: scale image
			image.scaleToFit(500, 500); // scale size

			document.add(image);
			document.add(new Paragraph(imageNames[i]));
		}

		document.close();
	}
 
Example 15
Project: DWSurvey   File: ItextpdfTest.java   Source Code and License 6 votes vote down vote up
public static void writeSimplePdf() throws Exception{
			//1.新建document对象
			//第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
			Document document = new Document(PageSize.A4, 50, 50, 50, 50);
			//2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
			//创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
			PdfWriter writer = PdfWriter.getInstance(document, 	new FileOutputStream("D:\\Documents\\ITextTest.pdf"));
			//3.打开文档
			document.open();		
			//4.向文档中添加内容
			//通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落
			BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			Font fontChinese = new Font(bfChinese, 22, Font.BOLD, BaseColor.BLACK);
			
			document.add(new Paragraph("sdfsdfsd全是中文显示了没.fsdfsfs",fontChinese));
			document.add(new Paragraph("Some more text on the 	first page with different color and font type.",
					FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new BaseColor(255, 150, 200))));
			Paragraph pragraph=new Paragraph("你这里有中亠好", fontChinese);
			document.add(pragraph);
			
			//图像支持格式 GIF, Jpeg, PNG, wmf
			Image gif = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png");
			gif.setBorder(5);
			gif.scaleAbsolute(30,30);
			gif.setAlignment(Image.RIGHT|Image.TEXTWRAP);
			document.add(gif);
			Paragraph pragraph11=new Paragraph("你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好", fontChinese);
			document.add(pragraph11);
			
			Image gif15 = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png");
//			gif15.setBorder(50);
			gif15.setBorder(Image.BOX);
			gif15.setBorderColor(BaseColor.RED);
//			gif15.setBorderColorBottom(borderColorBottom)
			gif15.setBorderWidth(1);
			gif15.scalePercent(50);
			document.add(gif15);
			//5.关闭文档
			document.close();
		}
 
Example 16
Project: hotel   File: ResidenceService.java   Source Code and License 6 votes vote down vote up
private void addOfferInstances(List<OfferInstance> offerInstances, Document document, BaseFont bf)
		throws DocumentException {

	if(offerInstances.isEmpty()) {
		return;
	}

	document.add(new Paragraph("Wybrane oferty: ", new Font(bf, 12)));

	PdfPTable offerInstancesTable = new PdfPTable(3);
	offerInstancesTable.setWidthPercentage(100);
	offerInstancesTable.setSpacingBefore(18f);
	offerInstancesTable.setSpacingAfter(18f);
	createofferInstancesTableHeaders(offerInstancesTable);
	createofferInstancesTableContent(offerInstances, offerInstancesTable);
	document.add(offerInstancesTable);
}
 
Example 17
Project: coj-web   File: PDFExportProblem.java   Source Code and License 6 votes vote down vote up
public Document getPDF() throws Exception {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(FILE + problem.getPid() + ".pdf"));
    Image image = Image.getInstance(this.logo);
    document.open();
    document.add(image);
    document.addCreationDate();
    document.add(new Paragraph("Title: "+problem.getTitle()));
    document.add(new Paragraph("Code: "+problem.getPid()));
    document.add(new Paragraph(" "));
    document.add(addParagraph("Description",problem.getDescription(), true));
    document.add(addParagraph("Input",problem.getInput(), true));
    document.add(addParagraph("Output",problem.getOutput(), true));
    document.add(addParagraph("Input Example",problem.getInputex().replaceAll("<br/>", ""), true));
    document.add(addParagraph("Output Example",problem.getOutputex(), true));
    document.add(new Paragraph("Time(ms): "+problem.getTime()));
    document.add(new Paragraph("Memory(kb): "+problem.getMemory()));
    document.add(new Paragraph("Source(kb): "+problem.getFontsize()));
    document.addTitle("Challenger Online Judge");
    document.addAuthor("Chjudge");
    document.close();
    return document;
}
 
Example 18
Project: OpenSongTablet   File: ExportPreparer.java   Source Code and License 6 votes vote down vote up
private static void makePDF(Bitmap bmp, File file) {
    Document document = new Document();
    try {
        PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addAuthor(FullscreenActivity.mAuthor.toString());
        document.addTitle(FullscreenActivity.mTitle.toString());
        document.addCreator("OpenSongApp");
        if (bmp!=null && bmp.getWidth()>bmp.getHeight()) {
            document.setPageSize(PageSize.A4.rotate());
        } else {
            document.setPageSize(PageSize.A4);
        }
        document.addTitle(FullscreenActivity.mTitle.toString());
        document.open();//document.add(new Header("Song title",FullscreenActivity.mTitle.toString()));
        BaseFont urName = BaseFont.createFont("assets/fonts/Lato-Reg.ttf", "UTF-8",BaseFont.EMBEDDED);
        Font TitleFontName  = new Font(urName, 14);
        Font AuthorFontName = new Font(urName, 10);
        document.add(new Paragraph(FullscreenActivity.mTitle.toString(),TitleFontName));
        document.add(new Paragraph(FullscreenActivity.mAuthor.toString(),AuthorFontName));
        addImage(document,bmp);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 19
Project: FOXopen   File: MultiOptionSelectWidget.java   Source Code and License 6 votes vote down vote up
private PdfPCell createColumnItem(PDFSerialiser pSerialiser, EvaluatedNodeInfo pEvalNode,
                                  LayoutFieldValueMappingItemColumn pColumnItem, int pItemsPerRow, boolean pHideField) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, MULTI_OPTION_CELL_TAG,
                                             getColumnItemClasses(pEvalNode), getColumnItemStyles(pEvalNode));
  pSerialiser.pushElementAttributes(lElementAttributes);

  PdfPCell lFieldCell = pSerialiser.getElementFactory().getCell();
  Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();
  lFieldCell.setColspan(FOXGridUtils.calculateAdjustedColumnSpan(pColumnItem.getColSpan(), pItemsPerRow));

  pSerialiser.startContainer(ElementContainerFactory.getContainer(lFieldCell, lCellParagraph));
  addColumnItemContent(pSerialiser, pColumnItem, pHideField);
  pSerialiser.endContainer();

  pSerialiser.popElementAttributes();

  return lFieldCell;
}
 
Example 20
Project: FOXopen   File: FormWidget.java   Source Code and License 6 votes vote down vote up
/**
 * Serialises a table cell of the column item content with cell styles applied
 * @param pSerialisationContext
 * @param pSerialiser
 * @param pColumnItem The column item to create a cell for
 * @param pFormColumns The number of columns in the form, used to determine field column spans
 */
private void addColumnItem(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, LayoutWidgetItemColumn pColumnItem, int pFormColumns) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, FORM_CELL_TAG, getColumnItemCellClasses(pColumnItem), getColumnItemCellStyles(pColumnItem));
  pSerialiser.pushElementAttributes(lElementAttributes);

  PdfPCell lFormCell = pSerialiser.getElementFactory().getCell();
  Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();
  lFormCell.setColspan(FOXGridUtils.calculateAdjustedColumnSpan(pColumnItem.getColSpan(), pFormColumns));

  pSerialiser.startContainer(ElementContainerFactory.getContainer(lFormCell, lCellParagraph));
  addColumnItemContent(pSerialisationContext, pSerialiser, pColumnItem);
  pSerialiser.endContainer();

  pSerialiser.add(lFormCell);
  pSerialiser.popElementAttributes();
}
 
Example 21
Project: FOXopen   File: WidgetBuilderPDFSerialiser.java   Source Code and License 6 votes vote down vote up
@Override
public void buildPrompt(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, EN pEvalNode) {
  if (hasPrompt(pEvalNode)) {
    ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
    pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, PROMPT_TAG, getPromptClasses(pEvalNode), Collections.emptyList());
    pSerialiser.pushElementAttributes(lElementAttributes);

    Paragraph lParagraph = pSerialiser.getElementFactory().getParagraph();
    pSerialiser.startContainer(ElementContainerFactory.getContainer(lParagraph));
    renderXMLStringContent(pSerialisationContext, pSerialiser, pEvalNode.getPrompt().getString());
    pSerialiser.endContainer();
    pSerialiser.add(lParagraph);

    pSerialiser.popElementAttributes();
  }
}
 
Example 22
Project: FOXopen   File: HeaderFooterComponent.java   Source Code and License 6 votes vote down vote up
@Override
public void buildComponent(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, EPN pEvalNode) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, mTag,
                                             Collections.singletonList(pEvalNode.getClasses()),
                                             Collections.singletonList(pEvalNode.getStyles()));
  pSerialiser.pushElementAttributes(lElementAttributes);

  // Add header/footer content to a table
  PdfPTable lTable = pSerialiser.getElementFactory().getTable(1);
  PdfPCell lCell = pSerialiser.getElementFactory().getCell();
  Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();

  pSerialiser.startContainer(ElementContainerFactory.getContainer(lCell, lCellParagraph));
  processChildren(pSerialisationContext, pSerialiser, pEvalNode);
  pSerialiser.endContainer();

  lTable.addCell(lCell);

  // Consume the header/footer content (i.e. set the header or footer content via the serialiser)
  mHeaderFooterContentConsumer.accept(pSerialiser, new HeaderFooterContent(lTable));
  pSerialiser.popElementAttributes();
}
 
Example 23
Project: FOXopen   File: InfoBoxComponentBuilder.java   Source Code and License 6 votes vote down vote up
@Override
public void buildComponent(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, EvaluatedInfoBoxPresentationNode pEvalNode) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  List<String> lClasses = Arrays.asList(INFO_BOX_CLASS, INFO_BOX_TYPE_CLASS_PREFIX + pEvalNode.getInfoBoxType().toString().toLowerCase(), pEvalNode.getClasses());
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, INFO_BOX_TAG, lClasses, Collections.singletonList(pEvalNode.getStyles()));
  pSerialiser.pushElementAttributes(lElementAttributes);

  PdfPTable lInfoBoxTable = pSerialiser.getElementFactory().getTable(1);
  PdfPCell lInfoBoxCell = pSerialiser.getElementFactory().getCell();
  Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();

  pSerialiser.startContainer(ElementContainerFactory.getContainer(lInfoBoxCell, lCellParagraph));

  // Add a title if one exists
  if (pEvalNode.getEvaluatedTitleContainer() != null) {
    addTitle(pSerialisationContext, pSerialiser, pEvalNode);
  }

  // Process info box content
  processChildren(pSerialisationContext, pSerialiser, pEvalNode.getEvaluatedContentContainer());

  pSerialiser.endContainer();
  lInfoBoxTable.addCell(lInfoBoxCell);
  // A table spacer is required so any content before the info box is not overlapped
  pSerialiser.addTableSpacer();
  pSerialiser.add(lInfoBoxTable);

  pSerialiser.popElementAttributes();
}
 
Example 24
Project: FOXopen   File: HeadingComponentBuilder.java   Source Code and License 6 votes vote down vote up
@Override
public void buildComponent(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, EvaluatedHeadingPresentationNode pEvalNode) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, HEADING_TAG_PREFIX + pEvalNode.getLevel(),
                                             Collections.singletonList(pEvalNode.getClasses()),
                                             Collections.singletonList(pEvalNode.getStyles()));
  pSerialiser.pushElementAttributes(lElementAttributes);

  // Heading text is contained within a table so that it may be styled as a block-level element (i.e. the same as a
  // div with borders, background colours etc.)
  PdfPTable lTable = pSerialiser.getElementFactory().getTable(1);
  PdfPCell lCell = pSerialiser.getElementFactory().getCell();
  Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();

  pSerialiser.startContainer(ElementContainerFactory.getContainer(lCell, lCellParagraph));
  processChildren(pSerialisationContext, pSerialiser, pEvalNode);
  pSerialiser.endContainer();

  lTable.addCell(lCell);
  // A table spacer is required so any content before the heading is not overlapped
  pSerialiser.addTableSpacer();
  pSerialiser.add(lTable);

  pSerialiser.popElementAttributes();
}
 
Example 25
Project: FOXopen   File: GridCellComponentBuilder.java   Source Code and License 6 votes vote down vote up
@Override
public void buildComponent(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, EvaluatedGridCellPresentationNode pEvalNode) {
  ElementAttributes lElementAttributes = pSerialiser.getInheritedElementAttributes();
  pSerialiser.getCSSResolver().resolveStyles(lElementAttributes, GRID_CELL_TAG,
                                             Arrays.asList(GRID_CELL_CLASS, pEvalNode.getClasses()),
                                             Collections.singletonList(pEvalNode.getStyles()));
  pSerialiser.pushElementAttributes(lElementAttributes);

  PdfPCell lCell = pSerialiser.getElementFactory().getCell();
  Paragraph lCellParagraph = pSerialiser.getElementFactory().getParagraph();
  lCell.setColspan(pEvalNode.getColumnSpan());

  pSerialiser.startContainer(ElementContainerFactory.getContainer(lCell, lCellParagraph));
  processChildren(pSerialisationContext, pSerialiser, pEvalNode);
  pSerialiser.endContainer();
  pSerialiser.add(lCell);

  pSerialiser.popElementAttributes();
}
 
Example 26
Project: osdq-core   File: DataDictionaryPDF.java   Source Code and License 6 votes vote down vote up
private void addTitlePage(Document document) throws DocumentException {

	addEmptyLine(document, 5);
   
   Paragraph title = new Paragraph("Data Dictionary by Arrah technology");
   title.setAlignment(Element.ALIGN_CENTER);
   document.add(title);
   addEmptyLine(document, 1);
   
   Paragraph url = new Paragraph("http://sourceforge.net/projects/dataquality/");
   url.setAlignment(Element.ALIGN_CENTER);
   document.add(url);
   addEmptyLine(document, 3);
   
   Paragraph rtime = new Paragraph("Report generated on: " +  new Date());
   rtime.setAlignment(Element.ALIGN_CENTER);
   document.add(rtime);

   document.newPage();
 }
 
Example 27
Project: testarea-itext5   File: ColorParagraphBackground.java   Source Code and License 6 votes vote down vote up
@Test
public void testParagraphBackgroundEventListener() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "document-with-paragraph-backgrounds.pdf")));
    ParagraphBackground border = new ParagraphBackground();
    writer.setPageEvent(border);
    document.open();
    document.add(new Paragraph("Hello,"));
    document.add(new Paragraph("In this document, we'll add several paragraphs that will trigger page events. As long as the event isn't activated, nothing special happens, but let's make the event active and see what happens:"));
    border.setActive(true);
    document.add(new Paragraph("This paragraph now has a background. Isn't that fantastic? By changing the event, we can even draw a border, change the line width of the border and many other things. Now let's deactivate the event."));
    border.setActive(false);
    document.add(new Paragraph("This paragraph no longer has a background."));
    document.close();
}
 
Example 28
Project: testarea-itext5   File: ChangeMargins.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38057241/itextpdf-different-margin-on-specific-page">
 * itextpdf different margin on specific page
 * </a>
 * <p>
 * This test shows how to set different margins to separate pages.
 * </p> 
 */
@Test
public void testChangingMargins() throws IOException, DocumentException
{
    StringBuilder builder = new StringBuilder("test");
    for (int i = 0; i < 100; i++)
        builder.append(" test");
    String test = builder.toString();
    
    try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "ChangingMargins.pdf")))
    {
        Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
        PdfWriter.getInstance(pdfDocument, pdfStream);
        pdfDocument.open();

        for (int m = 0; m < pdfDocument.getPageSize().getWidth() / 2 && m < pdfDocument.getPageSize().getHeight() / 2; m += 100)
        {
            // pdfDocument.setMargins(m, m, 100, 100);
            pdfDocument.setMargins(m, m, m, m);
            pdfDocument.newPage();
            pdfDocument.add(new Paragraph(test));
        }

        pdfDocument.close();
    }
}
 
Example 29
Project: testarea-itext5   File: CreateAndAppendDoc.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/29001852/how-to-create-a-pdf-and-you-then-merge-another-pdf-to-the-same-document-using-it">
 * how to create a PDF and you then merge another pdf to the same document using itext
 * </a>
 * <p>
 * Testing the OP's method with <code>paginate</code> set to <code>false</code>
 * </p>
 */
@Test
public void testAppendPDFs() throws IOException, DocumentException
{
    try (
            InputStream testA4Stream = getClass().getResourceAsStream("testA4.pdf");
            InputStream fromStream = getClass().getResourceAsStream("from.pdf");
            InputStream prefaceStream = getClass().getResourceAsStream("preface.pdf");
            InputStream type3Stream = getClass().getResourceAsStream("Test_Type3_Problem.pdf");
            FileOutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "appendPdfs.pdf"));
        )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        document.add(new Paragraph("Some content to start with"));
        appendPDFs(Arrays.asList(testA4Stream, fromStream, prefaceStream, type3Stream), writer, document, null, false);
        document.close();
    }
}
 
Example 30
Project: testarea-itext5   File: CreateAndAppendDoc.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/29001852/how-to-create-a-pdf-and-you-then-merge-another-pdf-to-the-same-document-using-it">
 * how to create a PDF and you then merge another pdf to the same document using itext
 * </a>
 * <p>
 * Testing the OP's method with <code>paginate</code> set to <code>true</code>
 * </p>
 */
@Test
public void testAppendPDFsPaginate() throws IOException, DocumentException
{
    try (
            InputStream testA4Stream = getClass().getResourceAsStream("testA4.pdf");
            InputStream fromStream = getClass().getResourceAsStream("from.pdf");
            InputStream prefaceStream = getClass().getResourceAsStream("preface.pdf");
            InputStream type3Stream = getClass().getResourceAsStream("Test_Type3_Problem.pdf");
            FileOutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "appendPdfsPaginate.pdf"));
        )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        document.add(new Paragraph("Some content to start with"));
        appendPDFs(Arrays.asList(testA4Stream, fromStream, prefaceStream, type3Stream), writer, document, null, true);
        document.close();
    }
}
 
Example 31
Project: testarea-itext5   File: DenseMerging.java   Source Code and License 6 votes vote down vote up
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 0; i < paragraphCount; i++)
    {
        Paragraph paragraph = new Paragraph();
        paragraph.add(String.format(paragraphFormat, i));
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
 
Example 32
Project: testarea-itext5   File: VeryDenseMerging.java   Source Code and License 6 votes vote down vote up
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 0; i < paragraphCount; i++)
    {
        Paragraph paragraph = new Paragraph();
        paragraph.add(String.format(paragraphFormat, i));
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
 
Example 33
Project: testarea-itext5   File: ImportPageWithoutFreeSpace.java   Source Code and License 6 votes vote down vote up
/**
 * This method creates a PDF with a single styled paragraph.
 */
static byte[] createSimpleTextPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();

    Paragraph paragraph = new Paragraph();
    paragraph.add(new Phrase("Beware: ", new Font(FontFamily.HELVETICA, 12, Font.BOLDITALIC)));
    paragraph.add(new Phrase("The implementation of ", new Font(FontFamily.HELVETICA, 12, Font.ITALIC)));
    paragraph.add(new Phrase("MarginFinder", new Font(FontFamily.COURIER, 12, Font.ITALIC)));
    paragraph.add(new Phrase(" is far from optimal. It is not even correct as it includes all curve control points which is too much. Furthermore it ignores stuff like line width or wedge types. It actually merely is a proof-of-concept.", new Font(FontFamily.HELVETICA, 12, Font.ITALIC)));
    document.add(paragraph);

    document.close();

    return baos.toByteArray();
}
 
Example 34
Project: testarea-itext5   File: DynamicFooter.java   Source Code and License 6 votes vote down vote up
public PdfPTable generateFooter() {
    try {
        BaseFont baseFont = BaseFont.createFont(/*"resources/ARIAL.TTF"*/ "c:/Windows/Fonts/arial.ttf", BaseFont.IDENTITY_H, true);
        footerTable = new PdfPTable(1);
        footerTable.setTotalWidth(440);
        footerTable.setLockedWidth(true);

        Font pageNumberFont = new Font(baseFont, 9, Font.BOLD);
        Paragraph pageNumberP = new Paragraph(titleIndex+"-"+ pageNumber, pageNumberFont);
        PdfPCell pageNumberCell = new PdfPCell(pageNumberP);
        pageNumberCell.setBorder(0);
        pageNumberCell.setPaddingTop(20);
        footerTable.addCell(pageNumberCell);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return footerTable;
}
 
Example 35
Project: testarea-itext5   File: SimpleRedactionTest.java   Source Code and License 6 votes vote down vote up
static byte[] createSimpleTextPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 1; i < 20; i++)
    {
        Paragraph paragraph = new Paragraph();
        for (int j = 0; j < i; j++)
            paragraph.add("Hello World! ");
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
 
Example 36
Project: tellervo   File: SeriesReport.java   Source Code and License 6 votes vote down vote up
/**
 * Get an iText Paragraph for the Title 
 * 
 * @return Paragraph
 */
private Paragraph getTitlePDF()
{
	Paragraph p = new Paragraph();
	
	p.add(new Chunk(s.getDisplayTitle()+"\n", titleFont));

	// Add object name if this is a mSeries
	if(s.getSeries() instanceof TridasMeasurementSeries)
	{
		TridasObject tobj = s.getMeta(Metadata.OBJECT, TridasObject.class);
	
		p.add(new Chunk(tobj.getTitle(), subTitleFont));
	}		
	return p;		
}
 
Example 37
Project: tellervo   File: SeriesReport.java   Source Code and License 6 votes vote down vote up
/**
 * iText paragraph containing created and lastmodified timestamps
 * 
 * @return Paragraph
 */
private Paragraph getTimestampPDF()
{
	// Set up calendar
	Date createdTimestamp = s.getSeries().getCreatedTimestamp().getValue()
			.toGregorianCalendar().getTime();
	Date lastModifiedTimestamp = s.getSeries().getLastModifiedTimestamp()
			.getValue().toGregorianCalendar().getTime();
	DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
	
	Paragraph p = new Paragraph();


	p.add(new Chunk("Created: ", subSubSectionFont));
	p.add(new Chunk(df1.format(createdTimestamp), bodyFont));
	p.add(new Chunk("\nLast Modified: ", subSubSectionFont));
	p.add(new Chunk(df1.format(lastModifiedTimestamp), bodyFont));

	
	return p;
	
}
 
Example 38
Project: tellervo   File: SeriesReport.java   Source Code and License 6 votes vote down vote up
private Paragraph getSeriesComments() 
{


	Paragraph p = new Paragraph();
	
	if(s.getSeries().getComments()!=null){
		
		p.setLeading(0, 1.2f);
		p.add(new Chunk("Comments: \n", subSubSectionFont));
		p.add(new Chunk(s.getSeries().getComments(), bodyFont));
		return p;
	}
	else
	{
		return p;
	}
	
	
}
 
Example 39
Project: tellervo   File: SeriesReport.java   Source Code and License 6 votes vote down vote up
/**
 * iText paragraph of element and sample info
 * @return Paragraph
 */
private Paragraph getElementAndSampleInfo()
{
	Paragraph p = new Paragraph();
	
	TridasElement telem = s.getMeta(Metadata.ELEMENT, TridasElement.class);
	TridasSample tsamp = s.getMeta(Metadata.SAMPLE, TridasSample.class);
	
	p.add(new Chunk("Element and sample details:\n", subSubSectionFont));
	
	p.add(new Chunk("- Taxon:  ", bodyFont));
	p.add(new Chunk(telem.getTaxon().getNormal()+"\n", bodyFontItalic));
	p.add(new Chunk("- Element type: "+ telem.getType().getNormal()+"\n", bodyFont));
	p.add(new Chunk("- Sample type: "+ tsamp.getType().getNormal()+"\n", bodyFont));
	return p;
	
}
 
Example 40
Project: tellervo   File: ProSheet.java   Source Code and License 6 votes vote down vote up
private Paragraph getObjectComments() 
{

	Paragraph p = new Paragraph();
	p.setLeading(0, 1.2f);
	p.setAlignment(Element.ALIGN_JUSTIFIED);
       p.setSpacingAfter(10);
	
	if(o.getComments()!=null){
		p.add(new Chunk("Notes: ", commentFont));
		p.add(new Chunk(o.getComments(), commentFont));
	}

	
	return p;
}