Java Code Examples for com.itextpdf.text.Element

The following are top voted examples for showing how to use com.itextpdf.text.Element. 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: pdf-renderer   File: CellFactory.java   Source Code and License 13 votes vote down vote up
public PdfPCell getFillCell(){
	PdfPCell fillCell = new PdfPCell();
	fillCell.setBorderWidth( 0f );
	fillCell.setLeft(0);
	fillCell.setTop(0);
	fillCell.setRight( 0 );
	fillCell.setBottom( 0 );
	fillCell.setUseAscender( true );
	fillCell.setIndent(0);
	fillCell.setHorizontalAlignment( Element.ALIGN_LEFT );
	fillCell.setVerticalAlignment( Element.ALIGN_BOTTOM );
	fillCell.setPaddingLeft( 0f);
	fillCell.setPaddingBottom(0f);
	fillCell.setPaddingRight(0f );
	fillCell.setPaddingTop( 0f );
	fillCell.setBorder( 0 );
	renderEmptyCell(fillCell);
	
	return fillCell;
}
 
Example 2
Project: NICON   File: ExporOnlyViagemPdf.java   Source Code and License 11 votes vote down vote up
private PdfPTable cellRodape(String value, boolean l,boolean r,int align)
{
    Font fontCorpoTableO= FontFactory.getFont(Fontes.FONT, BaseFont.WINANSI, BaseFont.EMBEDDED ,7.5f);
    PdfPTable pTable = new PdfPTable(1);
    pTable.setWidthPercentage(100f);
    PdfPCell cellValue = new PdfPCell(new Phrase(value,fontCorpoTableO));
    if(l){cellValue.setBorderWidthLeft(0);}
    if(r){cellValue.setBorderWidthRight(0);}
   switch (align) 
   {
       case Element.ALIGN_RIGHT:cellValue.setHorizontalAlignment(Element.ALIGN_RIGHT);break;
       case Element.ALIGN_LEFT:cellValue.setHorizontalAlignment(Element.ALIGN_LEFT);break;
       case Element.ALIGN_CENTER:cellValue.setHorizontalAlignment(Element.ALIGN_CENTER);break;
       default:break;
   }
    pTable.addCell(cellValue);
    return pTable;
}
 
Example 3
Project: testarea-itext5   File: StampColoredText.java   Source Code and License 11 votes vote down vote up
/**
 * The OP's code transformed into Java changed with the work-around.
 */
void stampTextChanged(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.setColorFill(new BaseColor(255,200,200));
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example 4
Project: tellervo   File: ProSheet.java   Source Code and License 10 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 5
Project: rolp   File: LebPageHelper.java   Source Code and License 10 votes vote down vote up
@Override
public void onEndPage(PdfWriter writer, Document document) {
	PdfPTable table = new PdfPTable(2);
	table.setTotalWidth(527);
	table.setWidthPercentage(100);
	table.setLockedWidth(true);
	table.getDefaultCell().setFixedHeight(105f);
	table.getDefaultCell().setBorderWidth(0);
	table.addCell("");			
	table.addCell(csmLogoImage);
	table.writeSelectedRows(0, -1, 100, 840, writer.getDirectContent());
	ColumnText.showTextAligned(writer.getDirectContent(),
                   Element.ALIGN_LEFT, 
                   new Phrase(lebData.getSchuelername() + " " + lebData.getSchuljahr() + " " + lebData.getSchulhalbjahr().getId() + " Seite " + document.getPageNumber(), fusszeilenFont),
                   100, 75, 0);
}
 
Example 6
Project: MountainQuest-PL   File: CoverPageGenerator.java   Source Code and License 9 votes vote down vote up
@Override
public PdfPTable generatePage() throws Exception {
    Image image = Image.getInstance(imageFile.toURL());
    float heightToWidthRatio = (210f / 297f);
    Image imageCropped = ImageUtils.cropImageToMeetRatio(pdfWriter, image, heightToWidthRatio);

    PdfPCell cell = new PdfPCell(imageCropped, true);
    cell.setBorder(0);
    cell.setPadding(COVER_MARGIN);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setExtraParagraphSpace(0);
    cell.setRightIndent(0);

    PdfPTable table = new PdfPTable(1);
    ;
    table.setWidthPercentage(100f);
    table.setWidths(new int[]{1});
    table.setExtendLastRow(true);
    table.addCell(cell);

    return table;
}
 
Example 7
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 8
Project: bdf2   File: AbstractPdfReportBuilder.java   Source Code and License 8 votes vote down vote up
private void createGridColumnHeader(PdfPTable table, Collection<ColumnHeader> topHeaders, int maxHeaderLevel) throws Exception {
	for (int i = 1; i < 50; i++) {
		List<ColumnHeader> result = new ArrayList<ColumnHeader>();
		generateGridHeadersByLevel(topHeaders, i, result);
		for (ColumnHeader header : result) {
			PdfPCell cell = new PdfPCell(createParagraph(header));
			if (header.getBgColor() != null) {
				int[] colors = header.getBgColor();
				cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2]));
			}
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setHorizontalAlignment(header.getAlign());
			cell.setColspan(header.getColspan());
			if (header.getColumnHeaders().size() == 0) {
				int rowspan = maxHeaderLevel - (header.getLevel() - 1);
				if (rowspan > 0) {
					cell.setRowspan(rowspan);
				}
			}
			table.addCell(cell);
		}
	}
}
 
Example 9
Project: testarea-itext5   File: UseColumnText.java   Source Code and License 8 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32162759/columntext-showtextaligned-vs-columntext-setsimplecolumn-top-alignment">
 * ColumnText.ShowTextAligned vs ColumnText.SetSimpleColumn Top Alignment
 * </a>
 * <p>
 * Indeed, the coordinates do not line up. The y coordinate of 
 * {@link ColumnText#showTextAligned(PdfContentByte, int, Phrase, float, float, float)}
 * denotes the baseline while {@link ColumnText#setSimpleColumn(Rectangle)} surrounds
 * the text to come.
 * </p>
 */
@Test
public void testShowTextAlignedVsSimpleColumnTopAlignment() throws DocumentException, IOException
{
    Document document = new Document(PageSize.A4);

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "ColumnTextTopAligned.pdf")));
    document.open();

    Font fontQouteItems = new Font(BaseFont.createFont(), 12);
    PdfContentByte canvas = writer.getDirectContent();

    // Item Number
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("36222-0", fontQouteItems), 60, 450, 0);

    // Estimated Qty
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("47", fontQouteItems), 143, 450, 0);

    // Item Description
    ColumnText ct = new ColumnText(canvas); // Uses a simple column box to provide proper text wrapping
    ct.setSimpleColumn(new Rectangle(193, 070, 390, 450));
    ct.setText(new Phrase("In-Situ : Poly Cable - 100'\nPoly vented rugged black gable 100ft\nThis is an additional description. It can wrap an extra line if it needs to so this text is long.", fontQouteItems));
    ct.go();

    document.close();
}
 
Example 10
Project: gutenberg   File: TableRowNodeProcessor.java   Source Code and License 8 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void process(int level, Node node, InvocationContext context) {
    TreeNavigation nav = context.treeNavigation();
    boolean isHeaderRow = nav.ancestorTreeMatches(TableRowNode.class, TableHeaderNode.class);

    List<Element> elements = context.collectChildren(level, node);

    TableInfos tableInfos = context.peekTable();
    PdfPTable table = tableInfos.getTable();
    int col = 0;
    for (Element element : elements) {
        PdfPCell cell = (PdfPCell) element;
        cell.setHorizontalAlignment(tableInfos.columnAlignment(col));
        table.addCell(cell);

        col += cell.getColspan();
    }
    table.completeRow();

    if (isHeaderRow) {
        int headerRows = table.getHeaderRows();
        table.setHeaderRows(headerRows + 1);
    }

}
 
Example 11
Project: bioinformatics   File: PdfReportUtil.java   Source Code and License 8 votes vote down vote up
private static PdfPCell getPhotoCell(BufferedImage bufferedImage, float scalePercent, boolean isHorizontallyCentered) throws BadElementException, IOException {
	Image jpeg = Image.getInstance(bufferedImage, null);
	jpeg.scalePercent(scalePercent);
	jpeg.setAlignment(Image.MIDDLE);
	PdfPCell photoCell = new PdfPCell(jpeg);
	photoCell.setBorder(0);
	if (isHorizontallyCentered) {
		photoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	} else {
		photoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
	}

	photoCell.setVerticalAlignment(Element.ALIGN_TOP);
	int height = (int) Math.ceil(bufferedImage.getHeight() * scalePercent / 100);
	photoCell.setFixedHeight(height);
	return photoCell;
}
 
Example 12
Project: NICON   File: ExportMapaProducao__.java   Source Code and License 7 votes vote down vote up
private Phrase funcaoTitulo(int i) {
    String txt;
    Font fontcabecatable =  FontFactory.getFont(Fontes.FONTB, BaseFont.WINANSI, BaseFont.EMBEDDED ,10f );
    switch (i)
    {
        case 0:txt="Nr. Factura";break;
        case 1:txt="Nome do Segurado"; break;
        case 2:txt="Prémio";break;
        case 3:txt="Imposto 6%";break;
        case 4:txt="Imposto 5%";break;
        case 5:txt="FGA 2.6%";break;
        default:txt="TOTAL";break;
    }
    
    a=com.itextpdf.text.Element.ALIGN_CENTER;
    Phrase rt = new Phrase(txt,fontcabecatable);
    return rt; 
}
 
Example 13
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 14
Project: bdf2   File: AbstractPdfReportBuilder.java   Source Code and License 7 votes vote down vote up
private void createGridTableDatas(PdfPTable table, Collection<ReportData> datas) {
	for (ReportData data : datas) {
		PdfPCell cell = new PdfPCell(createParagraph(data.getTextChunk()));
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		int level = this.calculateIndentationCount(data.getTextChunk().getText());
		if (data.getBgColor() != null) {
			int[] colors = data.getBgColor();
			cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2]));
		}
		if (level == 0) {
			cell.setHorizontalAlignment(data.getAlign());
		} else {
			cell.setIndent(20 * level);
		}
		table.addCell(cell);
	}
}
 
Example 15
Project: NICON   File: ExporOnlyViagemPdf.java   Source Code and License 7 votes vote down vote up
private PdfPTable cellRodape(String value, boolean l,boolean r,int align)
{
    Font fontCorpoTableO= FontFactory.getFont(Fontes.FONT, BaseFont.WINANSI, BaseFont.EMBEDDED ,7.5f);
    PdfPTable pTable = new PdfPTable(1);
    pTable.setWidthPercentage(100f);
    PdfPCell cellValue = new PdfPCell(new Phrase(value,fontCorpoTableO));
    if(l){cellValue.setBorderWidthLeft(0);}
    if(r){cellValue.setBorderWidthRight(0);}
   switch (align) 
   {
       case Element.ALIGN_RIGHT:cellValue.setHorizontalAlignment(Element.ALIGN_RIGHT);break;
       case Element.ALIGN_LEFT:cellValue.setHorizontalAlignment(Element.ALIGN_LEFT);break;
       case Element.ALIGN_CENTER:cellValue.setHorizontalAlignment(Element.ALIGN_CENTER);break;
       default:break;
   }
    pTable.addCell(cellValue);
    return pTable;
}
 
Example 16
Project: rolp   File: PdfFormatHelper.java   Source Code and License 7 votes vote down vote up
public static PdfPTable buildFooterDatumLine(String datumString, Font footerFont) throws DocumentException {
	PdfPCell labelCell = new PdfPCell(new Phrase("Datum", footerFont));
	labelCell.setBorder(Rectangle.BOTTOM);
	labelCell.setBorderWidth(1f);

	PdfPCell nameCell = new PdfPCell(new Phrase(datumString, footerFont));
	nameCell.setBorder(Rectangle.BOTTOM);
	nameCell.setBorderWidth(1f);
	
	PdfPTable table = new PdfPTable(2);
	table.setHorizontalAlignment(Element.ALIGN_LEFT);
	table.setWidthPercentage(100f);
	table.addCell(labelCell);
	table.addCell(nameCell);
	table.setWidths(new float[] {0.3f, 0.7f});
	return table;
}
 
Example 17
Project: IMSQTI2PDF   File: HeaderFooter.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unused")
private void headerText(PdfWriter writer, Rectangle rect)
{
    float center = (rect.getLeft() + rect.getRight()) / 2;

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Header Text"), center, rect.getTop(), 0);

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("01.01.1970"), center, rect.getTop() - 16,
            0);
}
 
Example 18
Project: NICON   File: ExporOnlyViagemPdf.java   Source Code and License 6 votes vote down vote up
private void dataTableTitile(Document documento, String data) throws IOException, BadElementException, DocumentException {
    
   try {
       pTableEmpresaPricipal = new PdfPTable(new float[]{15f, 85f});
       pTableEmpresaInforImpres1 = new PdfPTable(1);
       pTableEmpresaInforImpres5 = new PdfPTable(1);
       
       PdfPCell pCellNomeEmpresa = new PdfPCell(new Phrase(Empresa.NOME, fontCabecalhoNG));
       pCellNomeEmpresa.setBorder(0);
       PdfPCell pCellNomeEndereco = new PdfPCell(new Phrase(Empresa.ENDERECO, fontCabecalhoN));
       pCellNomeEndereco.setBorder(0);
       PdfPCell pCellCaixaPostal = new PdfPCell(new Phrase(Empresa.CAIXAPOSTAL, fontCabecalhoN));
       pCellCaixaPostal.setBorder(0);
       PdfPCell pCellTeleFax = new PdfPCell(new Phrase(Empresa.TELEFAX + " " + ConfigDoc.Empresa.EMAIL, fontCabecalhoN));
       pCellTeleFax.setBorder(0);
       PdfPCell pCellSociedade = new PdfPCell(new Phrase(Empresa.SOCIEDADE, fontCabecalhoN));
       pCellSociedade.setBorder(0);
       Image imageEmpresa = Image.getInstance("logo.png");
       imageEmpresa.scaleToFit(120f, 85f);
       pTableEmpresaInforImpres1.addCell(pCellNomeEmpresa);
       pTableEmpresaInforImpres1.addCell(pCellNomeEndereco);
       pTableEmpresaInforImpres1.addCell(pCellCaixaPostal);
       pTableEmpresaInforImpres1.addCell(pCellTeleFax);
       pTableEmpresaInforImpres1.addCell(pCellSociedade);
       PdfPCell cellTabela3 = new PdfPCell(pTableEmpresaInforImpres1);
       cellTabela3.setBorder(0);
       pTableEmpresaInforImpres5.addCell(cellTabela3);
       PdfPCell cellTabela5 = new PdfPCell(pTableEmpresaInforImpres5);
       cellTabela5.setBorder(0);
       PdfPCell cellTabela6 = new PdfPCell(imageEmpresa);
       cellTabela6.setBorder(0);
       pTableEmpresaPricipal.setWidthPercentage(95);
       pTableEmpresaPricipal.addCell(cellTabela6);
       pTableEmpresaPricipal.addCell(cellTabela5);
       PdfPTable pTableTitulo = new PdfPTable(1);
       pTableTitulo.setHorizontalAlignment(Element.ALIGN_CENTER);
       pTableTitulo.setWidthPercentage(100);
       
       SimpleDateFormat sdfEsp = new SimpleDateFormat("MMMM, yyyy", Locale.ENGLISH);
       SimpleDateFormat sdf = new SimpleDateFormat("MM-yyyy");
       PdfPCell cellTitulo = new PdfPCell(new Phrase("TOTAL PREMIUM COLLECTED ON TRAVEL INSURANCE AND TAXES FOR "+sdfEsp.format(sdf.parse(data)).toUpperCase(), fontCorpoNG));
       cellTitulo.setBorder(0);
       cellTitulo.setPaddingBottom(10f);
       pTableTitulo.addCell(cellTitulo);
       
       pTableEmpresaPricipal.setHorizontalAlignment(Element.ALIGN_CENTER);
       
       documento.add(pTableEmpresaPricipal);
       documento.add(pTableNull);
       documento.add(pTableTitulo);
   } catch (ParseException ex) {
       Logger.getLogger(ExporOnlyViagemPdf.class.getName()).log(Level.SEVERE, null, ex);
   }
}
 
Example 19
Project: DWSurvey   File: Demo5URL2PDF.java   Source Code and License 6 votes vote down vote up
/**
 * 根据URL提前blog的基本信息,返回结果>>:[主题 ,分类,日期,内容]等.
 * 
 * @param blogURL
 * @return
 * @throws Exception
 */
public static String[] extractBlogInfo(String blogURL) throws Exception {
	String[] info = new String[4];
	org.jsoup.nodes.Document doc = Jsoup.connect(blogURL).get();
	org.jsoup.nodes.Element e_title = doc.select("h2.title").first();
	info[0] = e_title.text();

	org.jsoup.nodes.Element e_category = doc.select("a[rel=category tag]")
			.first();
	info[1] = e_category.attr("href").replace("http://www.micmiu.com/", "");

	org.jsoup.nodes.Element e_date = doc.select("span.post-info-date")
			.first();

	String dateStr = e_date.text().split("日期")[1].trim();
	info[2] = dateStr;
	org.jsoup.nodes.Element entry = doc.select("div.entry").first();
	info[3] = formatContentTag(entry);

	return info;
}
 
Example 20
Project: DWSurvey   File: Demo4URL2PDF.java   Source Code and License 6 votes vote down vote up
/**
 * 根据URL提前blog的基本信息,返回结果>>:[主题 ,分类,日期,内容]等.
 * 
 * @param blogURL
 * @return
 * @throws Exception
 */
public static String[] extractBlogInfo(String blogURL) throws Exception {
	String[] info = new String[4];
	org.jsoup.nodes.Document doc = Jsoup.connect(blogURL).get();
	org.jsoup.nodes.Element e_title = doc.select("h2.title").first();
	info[0] = e_title.text();

	org.jsoup.nodes.Element e_category = doc.select("a[rel=category tag]")
			.first();
	info[1] = e_category.attr("href").replace("http://www.micmiu.com/", "");

	org.jsoup.nodes.Element e_date = doc.select("span.post-info-date")
			.first();

	String dateStr = e_date.text().split("日期")[1].trim();
	info[2] = dateStr;
	org.jsoup.nodes.Element entry = doc.select("div.entry").first();
	info[3] = formatContentTag(entry);

	return info;
}
 
Example 21
Project: NICON   File: ExportMapaProducao__.java   Source Code and License 6 votes vote down vote up
private Phrase funcaoTitulo(int i) {
    String txt;
    Font fontcabecatable =  FontFactory.getFont(Fontes.FONTB, BaseFont.WINANSI, BaseFont.EMBEDDED ,10f );
    switch (i)
    {
        case 0:txt="Nr. Factura";break;
        case 1:txt="Nome do Segurado"; break;
        case 2:txt="Prémio";break;
        case 3:txt="Imposto 6%";break;
        case 4:txt="Imposto 5%";break;
        case 5:txt="FGA 2.6%";break;
        default:txt="TOTAL";break;
    }
    
    a=com.itextpdf.text.Element.ALIGN_CENTER;
    Phrase rt = new Phrase(txt,fontcabecatable);
    return rt; 
}
 
Example 22
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 23
Project: testarea-itext5   File: StampColoredText.java   Source Code and License 6 votes vote down vote up
/**
 * The OP's original code transformed into Java
 */
void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setColorFill(new BaseColor(255,200,200));
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example 24
Project: MountainQuest-PL   File: TableOfContentsPageGenerator.java   Source Code and License 6 votes vote down vote up
private void generateSectionTitle(PdfPTable table, Data data) throws IOException, DocumentException {
    if (!this.currentSection.equals(data.mountains)) {
        currentSection = data.mountains;
        currentBackgroundColor = backgroundColorGenerator.generate(data);

        PdfPCell cellSeparator = new PdfPCell(PhraseUtil.phrase(" "));
        cellSeparator.setBorder(0);
        cellSeparator.setPadding(10);
        cellSeparator.setColspan(4);
        table.addCell(cellSeparator);

        PdfPCell cell = new PdfPCell(PhraseUtil.phrase(currentSection, 14, Font.BOLD));
        cell.setBorder(0);
        cell.setPadding(10);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setColspan(4);
        cell.setBackgroundColor(currentBackgroundColor);
        table.addCell(cell);
    }
}
 
Example 25
Project: MountainQuest-PL   File: EmptyPageGenerator.java   Source Code and License 6 votes vote down vote up
private PdfPTable tableWithPageNumber() throws DocumentException, IOException {

        PdfPTable innerTable = new PdfPTable(1);
        innerTable.setWidths(new int[]{1});
        innerTable.setWidthPercentage(100);
        innerTable.setPaddingTop(0);
        innerTable.addCell(new PageNumberCellGenerator(pageNumber, BackgroundColorGenerator.DEFAULT_BACKGROUND_COLOR)
                .generateTile());

        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(0);
        cell.setPadding(0);
        cell.addElement(innerTable);

        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100f);
        table.setWidths(new int[]{1});
        table.setExtendLastRow(true);
        table.addCell(cell);
        return table;
    }
 
Example 26
Project: MountainQuest-PL   File: DataPageGenerator.java   Source Code and License 6 votes vote down vote up
private PdfPCell generateFooter() throws IOException, DocumentException, URISyntaxException {

        PdfPCell cell = new PdfPCell();
        cell.setColspan(12);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(0);
        cell.setPadding(0);

        PdfPTable innerTable = new PdfPTable(2);
        innerTable.getDefaultCell().setBorder(0);
        innerTable.setWidths(new int[]{1, 1});
        innerTable.setWidthPercentage(100);
        innerTable.addCell(generateStamp());
        innerTable.addCell(new PageNumberCellGenerator(pageNumber, backgroundColor).generateTile());

        cell.addElement(innerTable);
        return cell;
    }
 
Example 27
Project: tellervo   File: ProSheet.java   Source Code and License 6 votes vote down vote up
public ProSheet(TridasObject o, TridasDerivedSeries master, ArrayListModel<org.tellervo.desktop.sample.Element> elements){
	
	// Find all series for an object 
   	SearchParameters sampparam = new SearchParameters(SearchReturnObject.OBJECT);
   	sampparam.addSearchConstraint(SearchParameterName.OBJECTID, SearchOperator.EQUALS, o.getIdentifier().getValue().toString());
   	
   	
   	// we want a series returned here    	
	EntitySearchResource<TridasObject> searchResource = new EntitySearchResource<TridasObject>(sampparam);
	searchResource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT, TellervoRequestFormat.COMPREHENSIVE);
	TellervoResourceAccessDialog dialog = new TellervoResourceAccessDialog(searchResource);
	searchResource.query();	
	dialog.setVisible(true);

	List<TridasObject> objlist = searchResource.getAssociatedResult();

	if(objlist.size()>0)
	{
		this.o = (TridasObjectEx) objlist.get(0);
	}
	this.elements = elements;
}
 
Example 28
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;
}
 
Example 29
Project: tellervo   File: PageNumbersWatermark.java   Source Code and License 6 votes vote down vote up
/**
 * Generates a document with a header containing Page x of y and with a Watermark on every page.
 * @param args no arguments needed
 */
public static void main(String args[]) {
    try {
    	// step 1: creating the document
        Document doc = new Document(PageSize.A4, 50, 50, 100, 72);
        // step 2: creating the writer
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("pageNumbersWatermark.pdf"));
        // step 3: initialisations + opening the document
        writer.setPageEvent(new PageNumbersWatermark());
        doc.open();
        // step 4: adding content
        String text = "some padding text ";
        for (int k = 0; k < 10; ++k)
            text += text;
        Paragraph p = new Paragraph(text);
        p.setAlignment(Element.ALIGN_JUSTIFIED);
        doc.add(p);
        // step 5: closing the document
        doc.close();
    }
    catch ( Exception e ) {
        e.printStackTrace();
    }
}
 
Example 30
Project: tellervo   File: PageNumbersWatermark.java   Source Code and License 6 votes vote down vote up
/**
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
public void onStartPage(PdfWriter writer, Document document) {
    if (writer.getPageNumber() < 3) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.setColorFill(BaseColor.PINK);
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        cb.showTextAligned(Element.ALIGN_CENTER, "My Watermark Under " + writer.getPageNumber(), document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
}
 
Example 31
Project: weplantaforest   File: PdfHelper.java   Source Code and License 6 votes vote down vote up
public static void createCircleAndText(PdfContentByte cb, String text, float xCoord, float yCoord, float radius, Font textFont, int circleColorRed, int circleColorGreen, int circleColorBlue)
        throws DocumentException, IOException {
    cb.saveState();
    cb.setRGBColorFill(circleColorRed, circleColorGreen, circleColorBlue);
    cb.circle(xCoord, yCoord, radius);
    cb.fill();
    cb.stroke();
    cb.restoreState();

    PdfPTable table = new PdfPTable(1);
    float[] rows = { 595f };
    table.setTotalWidth(rows);
    table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.getDefaultCell().setFixedHeight(radius * 2);
    table.addCell(new Phrase(new Chunk(text, textFont)));
    table.writeSelectedRows(0, 1, 0, yCoord + radius, cb);
}
 
Example 32
Project: rolp   File: PdfStreamSource.java   Source Code and License 6 votes vote down vote up
private void addIndividuelleEinschaetzung(Chapter chapterLEB, PdfWriter writer) throws DocumentException, PdfFormatierungsException {
	if (!lebData.getIndividuelleEinschaetzung().isEmpty()) {
		sectionCount += 1;
		breakHurenkind(writer);
		breakSchusterjunge(writer);
		Paragraph paragraphIndividuelleEinschaetzung = new Paragraph();
		Section individuelleEinschaetzungsTextSection = chapterLEB.addSection(paragraphIndividuelleEinschaetzung);
		individuelleEinschaetzungsTextSection.setNumberDepth(0);
		Paragraph schuelereinschaetzungParapgraph = new Paragraph(lebData.getIndividuelleEinschaetzung().replace('\t', '\0'), standardTextFont);
		schuelereinschaetzungParapgraph.setAlignment(Element.ALIGN_JUSTIFIED);
		schuelereinschaetzungParapgraph.setLeading(FIXED_LEADING_TEXT, zeilenabstandsfaktor);
		individuelleEinschaetzungsTextSection.add(schuelereinschaetzungParapgraph);			
		document.add(individuelleEinschaetzungsTextSection);
		document.add(getKlassenlehrerunterschrift(chapterLEB));
		alertHurenkind(writer);
		insertDummyLineIfNecessary(writer);
	}
}
 
Example 33
Project: rolp   File: PdfStreamSource.java   Source Code and License 6 votes vote down vote up
private void addKlassenbrief(Chapter chapterLEB, PdfWriter writer) throws DocumentException, PdfFormatierungsException {
	if (!lebData.getKlassenbrief().isEmpty()) {
		sectionCount += 1;
		breakSchusterjunge(writer);
		Paragraph paragraphKlassenbrief = new Paragraph();
		Section klassenbriefSection = chapterLEB.addSection(paragraphKlassenbrief);
		klassenbriefSection.setNumberDepth(0);
		Paragraph klasseneinschaetzungParapgraph = new Paragraph(lebData.getKlassenbrief().replace('\t', '\0'), standardTextFont);
		klasseneinschaetzungParapgraph.setAlignment(Element.ALIGN_JUSTIFIED);
		klasseneinschaetzungParapgraph.setLeading(FIXED_LEADING_TEXT, zeilenabstandsfaktor);
		klasseneinschaetzungParapgraph.add(Chunk.NEWLINE);
		if (lebData.getIndividuelleEinschaetzung().isEmpty()) {
			klassenbriefSection.add(klasseneinschaetzungParapgraph);
			document.add(klassenbriefSection);
			document.add(getKlassenlehrerunterschrift(chapterLEB));
		} else {
			klasseneinschaetzungParapgraph.add(Chunk.NEWLINE);
			klassenbriefSection.add(klasseneinschaetzungParapgraph);
			document.add(klassenbriefSection);
		}
		alertLonelyHeader(writer);
		insertDummyLineIfNecessary(writer);
	}
}
 
Example 34
Project: rolp   File: PdfFormatHelper.java   Source Code and License 6 votes vote down vote up
public static PdfPTable buildFooterVersetzungsvermerkLine(String versetzungsvermerk, Font footerFont) throws DocumentException {
	PdfPCell labelCell = new PdfPCell(new Phrase("Versetzungsvermerk", footerFont));
	labelCell.setBorder(Rectangle.BOTTOM);
	labelCell.setBorderWidth(1f);

	PdfPCell nameCell = new PdfPCell(new Phrase(versetzungsvermerk, footerFont));
	nameCell.setBorder(Rectangle.BOTTOM);
	nameCell.setBorderWidth(1f);
	
	PdfPTable table = new PdfPTable(2);
	table.setHorizontalAlignment(Element.ALIGN_LEFT);
	table.setWidthPercentage(100f);
	table.addCell(labelCell);
	table.addCell(nameCell);
	table.setWidths(new float[] {0.3f, 0.7f});
	return table;
}
 
Example 35
Project: rolp   File: PdfFormatHelper.java   Source Code and License 6 votes vote down vote up
public static PdfPTable buildFooterDienstsiegelLine(Font footerFont) throws DocumentException {
	PdfPCell leftCell = new PdfPCell(new Phrase("", footerFont));
	leftCell.setBorder(Rectangle.NO_BORDER);
	leftCell.setBorderWidth(1f);
	
	PdfPCell centerCell = new PdfPCell(new Phrase("Dienstsiegel der Schule", footerFont));
	centerCell.setBorder(Rectangle.NO_BORDER);
	centerCell.setBorderWidth(1f);
	centerCell.setHorizontalAlignment(Element.ALIGN_CENTER);

	PdfPCell rightCell = new PdfPCell(new Phrase("", footerFont));
	rightCell.setBorder(Rectangle.NO_BORDER);
	rightCell.setBorderWidth(1f);
	
	PdfPTable table = new PdfPTable(3);
	table.setHorizontalAlignment(Element.ALIGN_MIDDLE);
	table.setWidthPercentage(100f);
	table.addCell(leftCell);
	table.addCell(centerCell);
	table.addCell(rightCell);
	table.setWidths(new float[] {0.3f, 0.3f, 0.3f});
	return table;
}
 
Example 36
Project: rolp   File: PdfFormatHelper.java   Source Code and License 6 votes vote down vote up
public static PdfPTable buildFooterUnterschriftenLine(Font footerFont) throws DocumentException {
	PdfPCell leftCell = new PdfPCell(new Phrase("Schulleiter(in)", footerFont));
	leftCell.setBorder(Rectangle.TOP);
	leftCell.setBorderWidth(1f);
	leftCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	
	PdfPCell centerCell = new PdfPCell(new Phrase("", footerFont));
	centerCell.setBorder(Rectangle.TOP);
	centerCell.setBorderWidth(1f);
	centerCell.setHorizontalAlignment(Element.ALIGN_CENTER);

	PdfPCell rightCell = new PdfPCell(new Phrase("Klassenleiter(in)", footerFont));
	rightCell.setBorder(Rectangle.TOP);
	rightCell.setBorderWidth(1f);
	rightCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	
	PdfPTable table = new PdfPTable(3);
	table.setWidthPercentage(100f);
	table.addCell(leftCell);
	table.addCell(centerCell);
	table.addCell(rightCell);
	table.setWidths(new float[] {0.3f, 0.3f, 0.3f});
	return table;
}
 
Example 37
Project: rolp   File: PdfFormatHelper.java   Source Code and License 6 votes vote down vote up
public static PdfPTable buildFooterHalbjahrDatumLine(String datumString, Font footerFont) throws DocumentException {
	PdfPCell leftCell = new PdfPCell(new Phrase(datumString, footerFont));
	leftCell.setBorder(Rectangle.NO_BORDER);
	leftCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	
	PdfPCell centerCell = new PdfPCell(new Phrase("", footerFont));
	centerCell.setBorder(Rectangle.NO_BORDER);
	centerCell.setHorizontalAlignment(Element.ALIGN_CENTER);

	PdfPCell rightCell = new PdfPCell(new Phrase("", footerFont));
	rightCell.setBorder(Rectangle.NO_BORDER);
	rightCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	
	PdfPTable table = new PdfPTable(3);
	table.setWidthPercentage(100f);
	table.addCell(leftCell);
	table.addCell(centerCell);
	table.addCell(rightCell);
	table.setWidths(new float[] {0.3f, 0.3f, 0.3f});
	return table;
}
 
Example 38
Project: rolp   File: PdfFormatHelper.java   Source Code and License 6 votes vote down vote up
public static PdfPTable buildFooterHalbjahrDatumKlassenleiterLine(Font footerFont) throws DocumentException {
	PdfPCell leftCell = new PdfPCell(new Phrase("Datum", footerFont));
	leftCell.setBorder(Rectangle.TOP);
	leftCell.setBorderWidth(1f);
	leftCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	
	PdfPCell centerCell = new PdfPCell(new Phrase("", footerFont));
	centerCell.setBorder(Rectangle.TOP);
	centerCell.setBorderWidth(1f);
	centerCell.setHorizontalAlignment(Element.ALIGN_CENTER);

	PdfPCell rightCell = new PdfPCell(new Phrase("Klassenleiter(in)", footerFont));
	rightCell.setBorder(Rectangle.TOP);
	rightCell.setBorderWidth(1f);
	rightCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	
	PdfPTable table = new PdfPTable(3);
	table.setWidthPercentage(100f);
	table.addCell(leftCell);
	table.addCell(centerCell);
	table.addCell(rightCell);
	table.setWidths(new float[] {0.3f, 0.3f, 0.3f});
	return table;
}
 
Example 39
Project: gutenberg   File: HeaderFooter.java   Source Code and License 6 votes vote down vote up
public void drawFooter(PdfContentByte canvas, PageInfos pageInfos) {
    if (pageInfos.getRawPageNumber() == 1 && !footerOnFirstPage)
        return;

    if (drawLine) {
        BaseColor lineColor = styles.getColorOrDefault(HEADER_LINE_COLOR);
        canvas.saveState();
        canvas.setColorStroke(lineColor);
        canvas.setLineWidth(1.2f);
        canvas.moveTo(rect.getLeft(), rect.getBottom() - 6);
        canvas.lineTo(rect.getRight(), rect.getBottom() - 6);
        canvas.stroke();
        canvas.restoreState();
    }

    float bottom = rect.getBottom() - 20;
    Phrase footer = footerText(pageInfos);
    if (footer != null) {
        showTextAligned(canvas, Element.ALIGN_LEFT, footer, rect.getLeft(), bottom, 0);
    }

    Font footerFont = styles.getFontOrDefault(FOOTER_FONT);

    Phrase page = new Phrase(pageInfos.getFormattedPageNumber(), footerFont);
    showTextAligned(canvas, Element.ALIGN_RIGHT, page, rect.getRight(), bottom, 0);
}
 
Example 40
Project: gutenberg   File: ParaNodeProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void process(int level, Node node, InvocationContext context) {
    List<Element> subs = context.collectChildren(level, node);
    Paragraph p = new Paragraph();
    for (Element sub : subs) {
        p.add(discardNewline(sub));
    }

    KeyValues kvs = context.iTextContext().keyValues();

    Float spacingBefore = kvs.<Float>getNullable(PARAGRAPH_SPACING_BEFORE).or(5f);
    Float spacingAfter = kvs.<Float>getNullable(PARAGRAPH_SPACING_AFTER).or(5f);
    p.setSpacingBefore(spacingBefore);
    p.setSpacingAfter(spacingAfter);

    applyAttributes(context, p);

    context.append(p);
}
 
Example 41
Project: gutenberg   File: VerbatimNodeProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void process(int level, Node node, InvocationContext context) {
    VerbatimNode vNode = (VerbatimNode) node;

    SourceCode code = convertToSourceCode(vNode);
    Attributes attributes = context.peekAttributes(level);
    applyAttributes(code, attributes);


    ITextContext iTextContext = context.iTextContext();
    List<Element> elements = iTextContext.emitButCollectElements(code);
    for (Element element : elements) {
        ITextUtils.applyAttributes(element, attributes);
        context.append(element);
    }
}
 
Example 42
Project: gutenberg   File: TableCellNodeProcessor.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void process(int level, Node node, InvocationContext context) {
    TreeNavigation nav = context.treeNavigation();
    boolean isHeaderCell = nav.ancestorTreeMatches(TableCellNode.class, TableRowNode.class, TableHeaderNode.class);

    CellStyler cellStyler = context.peekCellStyler();
    context.pushFont(cellStyler.cellFont());
    List<Element> elements = context.collectChildren(level, node);
    context.popFont();

    Phrase phrase = new Phrase();
    phrase.addAll(elements);

    int colspan = ((TableCellNode) node).getColSpan();

    PdfPCell cell = isHeaderCell ? headerCell(phrase) : new PdfPCell(phrase);
    cell.setColspan(colspan);
    cellStyler.applyStyle(cell);

    context.append(cell);
}
 
Example 43
Project: gutenberg   File: OrderedListNodeProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void process(int level, Node node, InvocationContext context) {
    List<Element> subs = context.collectChildren(level, node);

    com.itextpdf.text.List orderedList = new com.itextpdf.text.List(com.itextpdf.text.List.ORDERED);
    for (Element sub : subs) {
        if (!orderedList.add(sub)) {
            // wrap it
            ListItem listItem = new ListItem();
            listItem.add(sub);
            orderedList.add(listItem);
        }
    }

    KeyValues kvs = context.iTextContext().keyValues();

    Float spacingBefore = kvs.<Float>getNullable(ORDERED_LIST_SPACING_BEFORE).or(5f);
    Float spacingAfter = kvs.<Float>getNullable(ORDERED_LIST_SPACING_AFTER).or(5f);

    Paragraph p = new Paragraph();
    p.add(orderedList);
    p.setSpacingBefore(spacingBefore);
    p.setSpacingAfter(spacingAfter);

    context.append(p);
}
 
Example 44
Project: gutenberg   File: ExpLinkNodeProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void process(int level, Node node, InvocationContext context) {
    ExpLinkNode linkNode = (ExpLinkNode) node;
    String url = context.variableResolver().resolve(linkNode.url);

    Font anchorFont = new FontCopier(context.peekFont())
            .style(Font.UNDERLINE)
            .color(Colors.DARK_RED)
            .get();

    context.pushFont(anchorFont);
    List<Element> subs = context.collectChildren(level, node);
    context.popFont();

    Phrase p = new Phrase();
    p.addAll(subs);

    Anchor anchor = new Anchor(p);
    anchor.setReference(url);
    context.append(anchor);
}
 
Example 45
Project: gutenberg   File: HeaderNodeProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void process(int level, Node node, InvocationContext context) {
    HeaderNode hNode = (HeaderNode) node;
    int hLevel = hNode.getLevel();

    Sections sections = context.iTextContext().sections();

    Font font = sections.sectionTitlePrimaryFont(hLevel);
    context.pushFont(font);
    List<Element> subs = context.collectChildren(level, node);
    context.popFont();

    Paragraph p = new Paragraph();
    p.setFont(font);
    p.addAll(subs);

    Element element = sections.newSection(p, hLevel);
    context.append(element);
}
 
Example 46
Project: gutenberg   File: SourceCodeEmitter.java   Source Code and License 6 votes vote down vote up
@Override
public void emit(SourceCode sourceCode, ITextContext context) {
    String lang = sourceCode.lang();

    try {
        for (SourceCodeEmitterExtension extension : extensions) {
            if (extension.accepts(lang)) {
                extension.emit(sourceCode, context);
                return;
            }
        }
    } catch (WrappedRuntimeException wre) {
        log.warn("Failed to invoke extension, fallback on raw rendering", wre.getCause());
    }

    // still there? no extension or error, let's rely directly on pygments
    List<Element> elements = pygmentsAdapter.process(sourceCode);
    context.appendAll(elements);
}
 
Example 47
Project: Create-PDF-in-Java-   File: createPDF.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    try (PrintWriter out = response.getWriter()) {

        //special font sizes
        //user for this entire page
        Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD, new BaseColor(0, 0, 0));
        Font bodyFont = new Font(Font.FontFamily.TIMES_ROMAN, 10);

        //set document response type
        documentResponse(response);

        //generate new document. 
        Document doc = new Document();

        //add properties
        documentProperties(response, doc);

        //open document
        doc.open();

        //create title of report
        Paragraph title = new Paragraph("PDF in Java");

        //get the current date and time form the class
        CurrentDateTime date = new CurrentDateTime();
        
        //add header
        documentHeader(doc, date, title, response);

        //set number of columns and their widths, f is float
        float[] columnWidths = {2f, 3f, 3f, 3f};
        PdfPTable table = new PdfPTable(columnWidths);

        //set width and spacing of table, default width is 100f, f is float
        table.setWidthPercentage(90f);
        table.setSpacingBefore(10f);
        table.setSpacingBefore(10f);

        //set heading of table
        insertCell(table, "User Id", Element.ALIGN_CENTER, 1, titleFont);
        insertCell(table, "UserName", Element.ALIGN_CENTER, 1, titleFont);
        insertCell(table, "Address", Element.ALIGN_CENTER, 1, titleFont);
        insertCell(table, "Email", Element.ALIGN_CENTER, 1, titleFont);

        //add header row to the table, we can set more than one row
        table.setHeaderRows(1);

        //set body part of the table
        insertCell(table, "1", Element.ALIGN_CENTER, 1, bodyFont);
        insertCell(table, "budthapa", Element.ALIGN_CENTER, 1, bodyFont);
        insertCell(table, "Kathmandu", Element.ALIGN_CENTER, 1, bodyFont);
        insertCell(table, "[email protected]", Element.ALIGN_CENTER, 1, bodyFont);
        
        //add document footer
        //this footer adds above table in the paragraph
        documentFooter(doc, table);

        //close the document
        doc.close();
    } catch (Exception e) {
        //exception here
    }
}
 
Example 48
Project: cucumber-contrib   File: HeaderProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public List<Element> end(WorkerContext ctx, Tag tag, List<Element> currentContent) {
    List<Element> elements = super.end(ctx, tag, currentContent);

    Paragraph paragraph = createParagraph();
    paragraph.addAll(elements);
    String content = paragraph.getContent();

    if (level == 1) {
        final Chapter chapter = configuration.createTitledChapter(content);
        return new ArrayList<Element>(1) {{
            add(chapter);
        }};
    }
    return elements;
}
 
Example 49
Project: cucumber-contrib   File: GralProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public List<Element> end(WorkerContext ctx, Tag tag, List<Element> currentContent) {
    Map<String, String> attributes = tag.getAttributes();

    String src = attributes.get(HTML.Attribute.SRC);
    if (src == null || src.trim().isEmpty()) {
        return new ArrayList<Element>(1);
    }

    src = src.trim();

    InputStream stream = null;
    try {
        URL url = new URL(src);
        stream = url.openStream();
        String raw = IOUtils.toString(stream);

        log.debug("About to render GRAL image");
        return renderGral(raw);
    } catch (Exception e) {
        log.debug("Unable to retrieve image from url {}, fallback on standard behavior", src);
        return new ArrayList<Element>(1);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}
 
Example 50
Project: cucumber-contrib   File: GralProcessor.java   Source Code and License 6 votes vote down vote up
private List<Element> renderGral(String raw) throws BadElementException, IOException {
    ChartDescriptor descriptor = new ChartDescriptorParser().parse(raw);

    PdfContentByte cb = writer.get().getDirectContent();
    float width = (float) descriptor.getWidth();
    float height = (float) descriptor.getHeight();

    PdfTemplate template = cb.createTemplate(width, height);
    Graphics2D g2 = new PdfGraphics2D(template, width, height);

    GralRenderer renderer = new GralRenderer();
    renderer.render(g2, descriptor);

    ArrayList<Element> elements = new ArrayList<Element>(1);
    elements.add(new ImgTemplate(template));
    return elements;
}
 
Example 51
Project: cucumber-contrib   File: MarkdownEmitterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void markdown_with_paragraph__new_lines_are_not_kept() throws IOException {
    String markdownText = "" +
            "Once upon a time \n" +
            "in a kingdom far, \n" +
            "far away, \n" +
            "the king and queen\n" +
            "";

    // html
    StringReader stringReader = markdownEmitter.formatHtmlAsReader(markdownText);
    String html = IOUtils.toString(stringReader);
    assertThat(html).isEqualTo("<p>Once upon a time in a kingdom far, far away, the king and queen</p>");

    // pdf elements
    List<Element> elements = markdownEmitter.markdownToElements(markdownText);
    assertThat(elements).isNotEmpty();

}
 
Example 52
Project: cucumber-contrib   File: MarkdownEmitterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void markdown_with_codeBlock() throws IOException {
    String markdownText = "\n" +
            "    var s = 1; \n" +
            "    s = s + 2; \n";

    // html
    StringReader stringReader = markdownEmitter.formatHtmlAsReader(markdownText);
    String html = IOUtils.toString(stringReader);
    assertThat(html).isEqualTo("<pre><code>var s = 1; \n" +
            "s = s + 2; \n" +
            "</code></pre>");

    // pdf elements
    List<Element> elements = markdownEmitter.markdownToElements(markdownText);
    assertThat(elements).isNotEmpty();

}
 
Example 53
Project: cucumber-contrib   File: MarkdownEmitterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void markdown_with_asciidiag() throws IOException {
    String markdownText = "" + //
            "# Title\n" + //
            "\n" + //
            "{% asciidiag %}\n" + //
            "/-------+     +-------+\n" + //
            "|  REQ  |<--->|  REP  |\n" + //
            "+-------/     +-------+\n" + //
            "{% asciidiag %}"; //

    // html
    StringReader stringReader = markdownEmitter.formatHtmlAsReader(markdownText);
    String html = IOUtils.toString(stringReader);
    assertThat(html).matches(
            literal("<h1>Title</h1>\n" +
                    "<p>\n" +
                    " <img src=\"file:") +
                    "(.+)" +
                    literal(".png\" />\n" +
                            " </p>\n"));
    // pdf elements
    List<Element> elements = markdownEmitter.markdownToElements(markdownText);
    assertThat(elements).isNotEmpty();
}
 
Example 54
Project: iTextTutorial   File: T11_ColumnText.java   Source Code and License 6 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));
		document.open();

		// TODO: 1. get direct content
		PdfContentByte canvas = writer.getDirectContent();

		Font font = new Font(FontFamily.HELVETICA, 18, Font.BOLD, BaseColor.ORANGE);
		Phrase headerText = new Phrase("PSEG DP&C", font);
		int alignLeft = Element.ALIGN_LEFT;
		float right = document.getPageSize().getRight();
		float top = document.getPageSize().getTop();

		// TODO: 2. use ColumnText
		ColumnText.showTextAligned(canvas, alignLeft, headerText, right - 180, top - 36, 0);

		document.close();
	}
 
Example 55
Project: fll-sw   File: SubjectivePdfWriter.java   Source Code and License 6 votes vote down vote up
private void writeCommentsSection(final PdfPTable table,
                                  final Font baseFont,
                                  final int height) {
  PdfPCell commentLabel = null;
  PdfPCell emptySpace = null;

  Font font = new Font(baseFont);
  font.setStyle(Font.ITALIC);
  // This is the 'Comments' section at the bottom of every table for the judge
  // to write in
  commentLabel = createCell("Comments:", font, NO_BORDERS);
  commentLabel.setRotation(90);
  commentLabel.setRowspan(1);
  commentLabel.setBorderWidthLeft(0);
  commentLabel.setBorderWidthBottom(0);
  commentLabel.setHorizontalAlignment(Element.ALIGN_CENTER);
  commentLabel.setVerticalAlignment(Element.ALIGN_CENTER);
  emptySpace = createCell(" ", font, TOP_ONLY);
  emptySpace.setMinimumHeight(18f);
  table.addCell(commentLabel);
  // Need to add the empty cells so the row is complete and is displayed in
  // the pdf
  for (int i1 = 0; i1 < 5; i1++) {
    table.addCell(emptySpace);
  }

  emptySpace = createCell(" ", font, NO_BORDERS);
  for (int i2 = 0; i2 < height; i2++) {
    for (int i3 = 0; i3 < 6; i3++) {
      table.addCell(emptySpace);
    }
  }
}
 
Example 56
Project: IMSQTI2PDF   File: HeaderFooter.java   Source Code and License 5 votes vote down vote up
private void pageNumberFooter(PdfWriter writer, Rectangle rect)
{
    Chunk c = new Chunk(String.format(LocaleStrings.getString("page"), writer.getPageNumber(), _maximumPageNumber));
    c.setFont(new Font(FontFamily.HELVETICA, 10));
    Phrase pagephrase = new Phrase(c);

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, pagephrase, rect.getRight() - 60,
            rect.getBottom() - 30, 0);
}
 
Example 57
Project: NICON   File: ExportMapaProducao__.java   Source Code and License 5 votes vote down vote up
public void priencherTable(Producao pro, Font fontCorpoTable, PdfPTable pTableDate, Document documento, float border) throws DocumentException {
    newDado(pro.PREMIO + " " + pro.MOEDA, fontCorpoTable, pTableDate, documento, Element.ALIGN_RIGHT,border);
    newDado(pro.IMPOSTOCONSUMO + " " + pro.MOEDA, fontCorpoTable, pTableDate, documento, Element.ALIGN_RIGHT,border);
    newDado(pro.IMPOSTOSELO + " " + pro.MOEDA, fontCorpoTable, pTableDate, documento, Element.ALIGN_RIGHT,border);
    newDado(pro.FGA + " " + pro.MOEDA, fontCorpoTable, pTableDate, documento, Element.ALIGN_RIGHT,border);
    newDado(pro.VALORTOTAL + " " + pro.MOEDA, fontCorpoTable, pTableDate, documento, Element.ALIGN_RIGHT,border);
}
 
Example 58
Project: DWSurvey   File: Demo5URL2PDF.java   Source Code and License 5 votes vote down vote up
/**
 * 格式化 img标签
 * 
 * @param entry
 * @return
 */
private static String formatContentTag(org.jsoup.nodes.Element entry) {
	try {
		entry.select("div").remove();
		// 把 <a href="*.jpg" ><img src="*.jpg"/></a> 替换为 <img
		// src="*.jpg"/>
		for (org.jsoup.nodes.Element imgEle : entry
				.select("a[href~=(?i)\\.(png|jpe?g)]")) {
			imgEle.replaceWith(imgEle.select("img").first());
		}
		return entry.html();
	} catch (Exception e) {
		return "";
	}
}
 
Example 59
Project: DWSurvey   File: Demo4URL2PDF.java   Source Code and License 5 votes vote down vote up
/**
 * 格式化 img标签
 * 
 * @param entry
 * @return
 */
private static String formatContentTag(org.jsoup.nodes.Element entry) {
	try {
		entry.select("div").remove();
		// 把 <a href="*.jpg" ><img src="*.jpg"/></a> 替换为 <img
		// src="*.jpg"/>
		for (org.jsoup.nodes.Element imgEle : entry
				.select("a[href~=(?i)\\.(png|jpe?g)]")) {
			imgEle.replaceWith(imgEle.select("img").first());
		}
		return entry.html();
	} catch (Exception e) {
		return "";
	}
}
 
Example 60
Project: bdf2   File: AbstractPdfReportBuilder.java   Source Code and License 5 votes vote down vote up
protected Paragraph createReportTitle(ReportTitle reportTitle) {
	Paragraph paragraph = new Paragraph();
	paragraph.setAlignment(Element.ALIGN_CENTER);
	if (reportTitle != null && reportTitle.isShowTitle()) {
		TextChunk titleChunk = new TextChunk();
		titleChunk.setText(reportTitle.getTitle());
		titleChunk.setFontSize(reportTitle.getStyle().getFontSize());
		titleChunk.setFontColor(reportTitle.getStyle().getFontColor());
		paragraph.add(createChunk(titleChunk));
		paragraph.add(Chunk.NEWLINE);
		paragraph.add(Chunk.NEWLINE);
	}
	return paragraph;
}