Java Code Examples for com.lowagie.text.pdf.PdfWriter

The following examples show how to use com.lowagie.text.pdf.PdfWriter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: itext2   Author: albfernandez   File: SplitTableTest.java    License: GNU Lesser General Public License v3.0 8 votes vote down vote up
/**
 * Break a large table up into several smaller tables for memory management
 * purposes.
 * 
 */
@Test
public void main() throws Exception {
	// step1
	Document document = new Document(PageSize.A4, 10, 10, 10, 10);
	// step2
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("SplitTable.pdf"));
	// step3
	document.open();
	// step4

	PdfContentByte cb = writer.getDirectContent();
	PdfPTable table = new PdfPTable(10);
	for (int k = 1; k <= 100; ++k) {
		table.addCell("The number " + k);
	}
	table.setTotalWidth(800);
	table.writeSelectedRows(0, 5, 0, -1, 50, 650, cb);
	document.newPage();
	table.writeSelectedRows(5, -1, 0, -1, 50, 650, cb);
	document.close();

	// step5
	document.close();
}
 
Example #2
Source Project: itext2   Author: albfernandez   File: NegativeLeadingTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Demonstrates what happens if you choose a negative leading.
 * 
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document();
	// step 2:
	// we create a writer that listens to the document
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("NegativeLeading.pdf"));

	// step 3: we open the document
	document.open();
	// step 4:
	document.add(new Phrase(16, "\n\n\n"));
	document.add(new Phrase(
			-16,
			"Hello, this is a very long phrase to show you the somewhat odd effect of a negative leading. You can write from bottom to top. This is not fully supported. It's something between a feature and a bug."));

	// step 5: we close the document
	document.close();
}
 
Example #3
private void insertTable_TextRow( PdfWriter writer, PdfPTable mainTable, String text, Font font )
{
    boolean hasBorder = false;

    // Add Organization ID/Period textfield
    // Create A table to add for each group AT HERE
    PdfPTable table = new PdfPTable( 1 );
    table.setHorizontalAlignment( Element.ALIGN_LEFT );

    addCell_Text( table, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), text, Element.ALIGN_LEFT, font );

    // Add to the main table
    PdfPCell cell_withInnerTable = new PdfPCell( table );

    cell_withInnerTable.setBorder( Rectangle.NO_BORDER );

    mainTable.addCell( cell_withInnerTable );
}
 
Example #4
Source Project: itext2   Author: albfernandez   File: ArabicTextTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Draws arabic text using java.awt.Graphics2D.
    */
@Test
public void main() throws Exception {
   	// step 1
       Document document = new Document(PageSize.A4, 50, 50, 50, 50);
       try {
       	// step 2
           PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "arabictext.pdf"));
           // step 3
           document.open();
           // step 4
           String text1 = "This text has \u0634\u0627\u062f\u062c\u0645\u0647\u0648\u0631 123,456 \u0645\u0646 (Arabic)";
           java.awt.Font font = new java.awt.Font("arial", 0, 18);
           PdfContentByte cb = writer.getDirectContent();
           java.awt.Graphics2D g2 = cb.createGraphicsShapes(PageSize.A4.getWidth(), PageSize.A4.getHeight());
           g2.setFont(font);
           g2.drawString(text1, 100, 100);
           g2.dispose();
           cb.sanityCheck();
           // step 5
           document.close();
       }
       catch (Exception de) {
           de.printStackTrace();
       }
   }
 
Example #5
Source Project: itext2   Author: albfernandez   File: PageNumbersWatermarkTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
    * Generates a document with a header containing Page x of y and with a Watermark on every page.
    */
@Test
public void main() throws Exception {
       	// 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, PdfTestBase.getOutputStream( "pageNumbersWatermark.pdf"));
           // step 3: initialisations + opening the document
           writer.setPageEvent(new PageNumbersWatermarkTest());
           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();
       
   }
 
Example #6
Source Project: itext2   Author: albfernandez   File: DifferentFontsTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Using FontSelector.
 */
@Test
public void main() throws Exception {
	// step 1
	Document document = new Document();
	// step 2
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("differentfonts.pdf"));
	// step 3
	document.open();
	// step 4
	Paragraph p = new Paragraph();
	p.add(new Chunk("This text is in Times Roman. This is ZapfDingbats: ", new Font(Font.TIMES_ROMAN, 12)));
	p.add(new Chunk("abcdefghijklmnopqrstuvwxyz", new Font(Font.ZAPFDINGBATS, 12)));
	p.add(new Chunk(". This is font Symbol: ", new Font(Font.TIMES_ROMAN, 12)));
	p.add(new Chunk("abcdefghijklmnopqrstuvwxyz", new Font(Font.SYMBOL, 12)));
	document.add(new Paragraph(p));
	// step 5
	document.close();

}
 
Example #7
Source Project: kfs   Author: kuali   File: PurchaseOrderQuoteRequestsPdf.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Generates the purchase order quote request list pdf document based on the data in the given input parameters
 * by creating a pdf writer using the given byteArrayOutputStream then calls the createPOQuoteRequestsListPdf to 
 * write the pdf document into the writer.
 * 
 * @param po                     The PurchaseOrderDocument to be used to generate the pdf.
 * @param byteArrayOutputStream  The ByteArrayOutputStream to print the pdf to.
 * @param institutionName        The purchasing institution name.
 * @return                       Collection of errors which are made of the messages from DocumentException.
 */
public Collection generatePOQuoteRequestsListPdf(PurchaseOrderDocument po, ByteArrayOutputStream byteArrayOutputStream, String institutionName) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("generatePOQuoteRequestsListPDF() started for po number " + po.getPurapDocumentIdentifier());
    }

    Collection errors = new ArrayList();

    try {
        Document doc = this.getDocument();
        PdfWriter writer = PdfWriter.getInstance(doc, byteArrayOutputStream);
        this.createPOQuoteRequestsListPdf(po, doc, writer, institutionName);
    }
    catch (DocumentException de) {
        LOG.error(de.getMessage(), de);
        errors.add(de.getMessage());
    }
    return errors;
}
 
Example #8
Source Project: kfs   Author: kuali   File: PurchaseOrderQuoteRequestsPdf.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Overrides the method in PdfPageEventHelper from itext to compose the footer and show the
 * footer.
 *
 * @param writer    The PdfWriter for this document.
 * @param document  The document.
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
    LOG.debug("onEndPage() started.");
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // compose the footer
    String text = "Page " + writer.getPageNumber() + " of ";
    float textSize = helv.getWidthPoint(text, 12);
    float textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    // show the footer
    float adjust = helv.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);
    cb.saveState();
}
 
Example #9
Source Project: itext2   Author: albfernandez   File: JavaScriptActionTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a document with a javascript action.
 * 
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document();

	// step 2:
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("JavaScriptAction.pdf"));
	// step 3: we add Javascript as Metadata and we open the document
	document.open();
	// step 4: we add some content
	Paragraph p = new Paragraph(new Chunk("Click to say Hello").setAction(PdfAction.javaScript(
			"app.alert('Hello');\r", writer)));
	document.add(p);

	// step 5: we close the document
	document.close();

}
 
Example #10
Source Project: gcs   Author: richardwilkes   File: FieldPositioningEvents.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * @see com.lowagie.text.pdf.PdfPageEvent#onGenericTag(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document, com.lowagie.text.Rectangle, java.lang.String)
 */
@Override
public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
	rect.setBottom(rect.getBottom() - 3);
	PdfFormField field = (PdfFormField) genericChunkFields.get(text);
	if (field == null) {
		TextField tf = new TextField(writer, new Rectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding)), text);
		tf.setFontSize(14);
		try {
			field = tf.getTextField();
		} catch (Exception e) {
			throw new ExceptionConverter(e);
		}
	} else {
		field.put(PdfName.RECT, new PdfRectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding)));
	}
	if (parent == null) {
		writer.addAnnotation(field);
	} else {
		parent.addKid(field);
	}
}
 
Example #11
Source Project: itext2   Author: albfernandez   File: EndPageTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
	try {
		Rectangle page = document.getPageSize();
		PdfPTable head = new PdfPTable(3);
		for (int k = 1; k <= 6; ++k)
			head.addCell("head " + k);
		head.setTotalWidth(page.getWidth() - document.leftMargin()
				- document.rightMargin());
		head.writeSelectedRows(
				0,
				-1,
				document.leftMargin(),
				page.getHeight() - document.topMargin()
						+ head.getTotalHeight(), writer.getDirectContent());
		PdfPTable foot = new PdfPTable(3);
		for (int k = 1; k <= 6; ++k)
			foot.addCell("foot " + k);
		foot.setTotalWidth(page.getWidth() - document.leftMargin()
				- document.rightMargin());
		foot.writeSelectedRows(0, -1, document.leftMargin(),
				document.bottomMargin(), writer.getDirectContent());
	} catch (Exception e) {
		throw new ExceptionConverter(e);
	}
}
 
Example #12
Source Project: kfs   Author: kuali   File: PurapPdf.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Overrides the method in PdfPageEventHelper from itext to write the headerTable, compose the footer and show the
 * footer.
 *
 * @param writer    The PdfWriter for this document.
 * @param document  The document.
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {
    LOG.debug("onEndPage() started.");
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // write the headerTable
    headerTable.setTotalWidth(document.right() - document.left());
    headerTable.writeSelectedRows(0, -1, document.left(), document.getPageSize().height() - 10, cb);
    // compose the footer
    String text = "Page " + writer.getPageNumber() + " of ";
    float textSize = helv.getWidthPoint(text, 12);
    float textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    // show the footer
    float adjust = helv.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);
    cb.saveState();
}
 
Example #13
Source Project: kfs   Author: kuali   File: CashReceiptCoverSheetServiceImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Method responsible for producing Check Detail section of the cover sheet. Not all Cash Receipt documents have checks.
 *
 * @param crDoc The CashReceipt document the cover sheet is being created for.
 * @param writer The output writer used to write the check data to the PDF file.
 * @param reader The input reader used to read data from the PDF file.
 */
protected void populateCheckDetail(CashReceiptDocument crDoc, PdfWriter writer, PdfReader reader) throws Exception {
    PdfContentByte content;
    ModifiableInteger pageNumber;
    int checkCount = 0;
    int maxCheckCount = MAX_CHECKS_FIRST_PAGE;

    pageNumber = new ModifiableInteger(0);
    content = startNewPage(writer, reader, pageNumber);

    for (Check current : crDoc.getChecks()) {
        writeCheckNumber(content, current);
        writeCheckDate(content, current);
        writeCheckDescription(content, current);
        writeCheckAmount(content, current);
        setCurrentRenderingYPosition(getCurrentRenderingYPosition() - CHECK_FIELD_HEIGHT);

        checkCount++;

        if (checkCount > maxCheckCount) {
            checkCount = 0;
            maxCheckCount = MAX_CHECKS_NORMAL;
            content = startNewPage(writer, reader, pageNumber);
        }
    }
}
 
Example #14
Source Project: itext2   Author: albfernandez   File: FieldPositioningEvents.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @see com.lowagie.text.pdf.PdfPageEvent#onGenericTag(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, com.lowagie.text.Rectangle, java.lang.String)
 */
public void onGenericTag(PdfWriter writer, Document document,
		Rectangle rect, String text) {
	rect.setBottom(rect.getBottom() - 3);
	PdfFormField field = (PdfFormField) genericChunkFields.get(text);
	if (field == null) {
		TextField tf = new TextField(writer, new Rectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding)), text);
		tf.setFontSize(14);
		try {
			field = tf.getTextField();
		} catch (Exception e) {
			throw new ExceptionConverter(e);
		}
	}
	else {
		field.put(PdfName.RECT,  new PdfRectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding)));
	}
	if (parent == null)
		writer.addAnnotation(field);
	else
		parent.addKid(field);
}
 
Example #15
private void insertTable_DataSet( PdfPTable mainTable, PdfWriter writer, DataSet dataSet )
    throws IOException, DocumentException
{
    Rectangle rectangle = new Rectangle( TEXTBOXWIDTH, PdfDataEntryFormUtil.CONTENT_HEIGHT_DEFAULT );

    if ( dataSet.getSections().size() > 0 )
    {
        for ( Section section : dataSet.getSections() )
        {
            insertTable_DataSetSections( mainTable, writer, rectangle, section.getDataElements(), section.getDisplayName() );
        }
    }
    else
    {
        insertTable_DataSetSections( mainTable, writer, rectangle, dataSet.getDataElements(), "" );
    }
}
 
Example #16
Source Project: itext2   Author: albfernandez   File: HelloSystemOutTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates a PDF file with the text 'Hello World'
 * 
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document();
	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to System.out (and a txt file)
	PdfWriter w = PdfWriter.getInstance(document, System.out);
	w.setCloseStream(false); // System.out should not be closed
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("HelloWorld.txt"));

	// step 3: we open the document
	document.open();
	// step 4: we add a paragraph to the document
	document.add(new Paragraph("Hello World"));

	// step 5: we close the document
	document.close();
}
 
Example #17
Source Project: itext2   Author: albfernandez   File: EventsTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Converts a play in XML into PDF.
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document(PageSize.A4, 80, 50, 30, 65);

	// step 2:
	// we create a writer that listens to the document
	// and directs a XML-stream to a file
	PdfWriter writer = PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("RomeoJuliet.pdf"));

	// create add the event handler
	MyPageEvents events = new EventsTest().getPageEvents();
	writer.setPageEvent(events);

	// step 3: we create a parser and set the document handler
	SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

	// step 4: we parse the document
	parser.parse(PdfTestBase.RESOURCES_DIR + "playRomeoJuliet.xml",
			new EventsTest().getXmlHandler(document));

	document.newPage();
	Speaker speaker;
	for (Iterator i = events.getSpeakers().iterator(); i.hasNext();) {
		speaker = (Speaker) i.next();
		document.add(new Paragraph(speaker.getName() + ": "
				+ speaker.getOccurrence() + " speech blocks"));
	}
	document.close();

}
 
Example #18
Source Project: kfs   Author: kuali   File: Coversheet.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.kuali.kfs.module.tem.pdf.PdfStream#print(java.io.OutputStream)
 * @throws Exception
 */
@Override
public void print(final OutputStream stream) throws Exception {
    final Font titleFont  = FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD);
    final Font headerFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
    final Font normalFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);

    final Document doc = new Document();
    final PdfWriter writer = PdfWriter.getInstance(doc, stream);
    doc.open();
    if(getDocumentNumber()!=null){
        Image image=Image.getInstance(new BarcodeHelper().generateBarcodeImage(getDocumentNumber()),null);
        doc.add(image);
    }

    final Paragraph title = new Paragraph("TEM Coversheet", titleFont);
    doc.add(title);

    final Paragraph faxNumber = new Paragraph("Fax this page to " + SpringContext.getBean(ParameterService.class).getParameterValueAsString(TravelReimbursementDocument.class, FAX_NUMBER), normalFont);
    doc.add(faxNumber);

    final Paragraph header = new Paragraph("", headerFont);
    header.setAlignment(ALIGN_RIGHT);
    header.add("Document Number: " + getDocumentNumber());
    doc.add(header);
    doc.add(getInstructionsParagraph());
    doc.add(getMailtoParagraph());
    doc.add(Chunk.NEWLINE);
    doc.add(getTripInfo());
    doc.add(Chunk.NEWLINE);
    doc.add(getPersonalInfo());
    doc.add(Chunk.NEWLINE);
    doc.add(getExpenses());

    drawAlignmentMarks(writer.getDirectContent());

    doc.close();
    writer.close();
}
 
Example #19
Source Project: itext2   Author: albfernandez   File: OptionalContentTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates the use of layers.
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {
	// step 1: creation of a document-object
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	// step 2: creation of the writer
	PdfWriter writer = PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("optionalcontent.pdf"));
	writer.setPdfVersion(PdfWriter.VERSION_1_5);
	writer.setViewerPreferences(PdfWriter.PageModeUseOC);
	// step 3: opening the document
	document.open();
	// step 4: content
	PdfContentByte cb = writer.getDirectContent();
	Phrase explanation = new Phrase(
			"Automatic layers, form fields, images, templates and actions",
			new Font(Font.HELVETICA, 18, Font.BOLD, Color.red));
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50,
			650, 0);
	PdfLayer l1 = new PdfLayer("Layer 1", writer);
	PdfLayer l2 = new PdfLayer("Layer 2", writer);
	PdfLayer l3 = new PdfLayer("Layer 3", writer);
	PdfLayer l4 = new PdfLayer("Form and XObject Layer", writer);
	PdfLayerMembership m1 = new PdfLayerMembership(writer);
	m1.addMember(l2);
	m1.addMember(l3);
	Phrase p1 = new Phrase("Text in layer 1");
	Phrase p2 = new Phrase("Text in layer 2 or layer 3");
	Phrase p3 = new Phrase("Text in layer 3");
	cb.beginLayer(l1);
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0f);
	cb.endLayer();
	cb.beginLayer(m1);
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0);
	cb.endLayer();
	cb.beginLayer(l3);
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0);
	cb.endLayer();
	TextField ff = new TextField(writer, new Rectangle(200, 600, 300, 620),
			"field1");
	ff.setBorderColor(Color.blue);
	ff.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
	ff.setBorderWidth(TextField.BORDER_WIDTH_THIN);
	ff.setText("I'm a form field");
	PdfFormField form = ff.getTextField();
	form.setLayer(l4);
	writer.addAnnotation(form);
	Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR
			+ "pngnow.png");
	img.setLayer(l4);
	img.setAbsolutePosition(200, 550);
	cb.addImage(img);
	PdfTemplate tp = cb.createTemplate(100, 20);
	Phrase pt = new Phrase("I'm a template", new Font(Font.HELVETICA, 12,
			Font.NORMAL, Color.magenta));
	ColumnText.showTextAligned(tp, Element.ALIGN_LEFT, pt, 0, 0, 0);
	tp.setLayer(l4);
	tp.setBoundingBox(new Rectangle(0, -10, 100, 20));
	cb.addTemplate(tp, 200, 500);
	ArrayList<Object> state = new ArrayList<Object>();
	state.add("toggle");
	state.add(l1);
	state.add(l2);
	state.add(l3);
	state.add(l4);
	PdfAction action = PdfAction.setOCGstate(state, true);
	Chunk ck = new Chunk("Click here to toggle the layers", new Font(
			Font.HELVETICA, 18, Font.NORMAL, Color.yellow)).setBackground(
			Color.blue).setAction(action);
	ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase(ck),
			250, 400, 0);
	cb.sanityCheck();

	// step 5: closing the document
	document.close();
}
 
Example #20
Source Project: itext2   Author: albfernandez   File: CellEventsTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * General example using cell events.
 * 
 */
@Test
public void main() throws Exception {
	// step1
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	// step2
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("CellEvents.pdf"));
	// step3
	document.open();
	// step4
	CellEventsTest event = new CellEventsTest();
	Image im = Image.getInstance(PdfTestBase.RESOURCES_DIR + "otsoe.jpg");
	im.setRotationDegrees(30);
	PdfPTable table = new PdfPTable(4);
	table.addCell("text 1");
	PdfPCell cell = new PdfPCell(im, true);
	cell.setCellEvent(event);
	table.addCell(cell);
	table.addCell("text 3");
	im.setRotationDegrees(0);
	table.addCell(im);
	table.setTotalWidth(300);
	PdfContentByte cb = writer.getDirectContent();
	table.writeSelectedRows(0, -1, 50, 600, cb);
	table.setHeaderRows(3);
	document.add(table);

	// step5
	document.close();
}
 
Example #21
Source Project: itext2   Author: albfernandez   File: LargeCellTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates the features of the old Table class.
 */
@Test
public void main() throws Exception {
	// step 1: creation of a document-object
	Document document = new Document(PageSize.A6);
	// step 2: creation of the writer-object
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("largecell.pdf"));
	// step 3: we open the document
	document.open();
	// step 4: we create a table and add it to the document
	Table table = new Table(3);
	table.setCellsFitPage(true);
	String text = "long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long text";
	table.addCell("text");
	table.addCell("text");
	table.addCell("text");
	table.addCell(text);
	table.addCell(text + text);
	table.addCell(text);
	table.addCell("text");
	table.addCell("text");
	table.addCell("text");
	document.add(table);

	// step 5: we close the document
	document.close();
}
 
Example #22
Source Project: itext2   Author: albfernandez   File: MultiColumnR2LTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * An example using MultiColumnText with irregular columns.
 */
@Test
public void main() throws Exception {
	Document document = new Document();
	OutputStream out = PdfTestBase.getOutputStream("multicolumnR2L.pdf");
	PdfWriter.getInstance(document, out);
	document.open();

	MultiColumnText mct = new MultiColumnText();
	mct.setColumnsRightToLeft(true);

	// set up 3 even columns with 10pt space between
	mct.addRegularColumns(document.left(), document.right(), 10f, 3);

	// Write some iText poems
	for (int i = 0; i < 30; i++) {
		mct.addElement(new Paragraph(String.valueOf(i + 1)));
		mct.addElement(newPara(randomWord(noun), Element.ALIGN_CENTER, Font.BOLDITALIC));
		for (int j = 0; j < 4; j++) {
			mct.addElement(newPara(poemLine(), Element.ALIGN_LEFT, Font.NORMAL));
		}
		mct.addElement(newPara(randomWord(adverb), Element.ALIGN_LEFT, Font.NORMAL));
		mct.addElement(newPara("\n\n", Element.ALIGN_LEFT, Font.NORMAL));
	}

	document.add(mct);
	document.close();

}
 
Example #23
Source Project: itext2   Author: albfernandez   File: VerticalTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Writing vertical text.
 */
@Test
public void main() throws Exception {
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	texts[3] = convertCid(texts[0]);
	texts[4] = convertCid(texts[1]);
	texts[5] = convertCid(texts[2]);
	PdfWriter writer = PdfWriter.getInstance(document,PdfTestBase.getOutputStream("vertical.pdf"));
	int idx = 0;
	document.open();
	PdfContentByte cb = writer.getDirectContent();
	for (int j = 0; j < 2; ++j) {
		BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j],	false);
		cb.setRGBColorStroke(255, 0, 0);
		cb.setLineWidth(0);
		float x = 400;
		float y = 700;
		float height = 400;
		float leading = 30;
		int maxLines = 6;
		for (int k = 0; k < maxLines; ++k) {
			cb.moveTo(x - k * leading, y);
			cb.lineTo(x - k * leading, y - height);
		}
		cb.rectangle(x, y, -leading * (maxLines - 1), -height);
		cb.stroke();
		VerticalText vt = new VerticalText(cb);
		vt.setVerticalLayout(x, y, height, maxLines, leading);
		vt.addText(new Chunk(texts[idx++], new Font(bf, 20)));
		vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue)));
		vt.go();
		vt.setAlignment(Element.ALIGN_RIGHT);
		vt.addText(new Chunk(texts[idx++],	new Font(bf, 20, 0, Color.orange)));
		vt.go();
		document.newPage();
	}
	document.close();

}
 
Example #24
Source Project: itext2   Author: albfernandez   File: ReadEncryptedTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Reads an encrypted PDF document.
 * 
 */
@Test
public void main() throws Exception {
	BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.OUTPUT_DIR + "info_encrypted.txt"));
	PdfReader r = new PdfReader(PdfTestBase.RESOURCES_DIR + "HelloEncrypted.pdf", "Hello".getBytes());
	out.write(r.getInfo().toString());
	out.write("\r\n");
	int permissions = r.getPermissions();
	out.write("Printing allowed: " + ((PdfWriter.ALLOW_PRINTING & permissions) > 0));
	out.write("\r\n");
	out.write("Modifying contents allowed: " + ((PdfWriter.ALLOW_MODIFY_CONTENTS & permissions) > 0));
	out.write("\r\n");
	out.write("Copying allowed: " + ((PdfWriter.ALLOW_COPY & permissions) > 0));
	out.write("\r\n");
	out.write("Modifying annotations allowed: " + ((PdfWriter.ALLOW_MODIFY_ANNOTATIONS & permissions) > 0));
	out.write("\r\n");
	out.write("Fill in allowed: " + ((PdfWriter.ALLOW_FILL_IN & permissions) > 0));
	out.write("\r\n");
	out.write("Screen Readers allowed: " + ((PdfWriter.ALLOW_SCREENREADERS & permissions) > 0));
	out.write("\r\n");
	out.write("Assembly allowed: " + ((PdfWriter.ALLOW_ASSEMBLY & permissions) > 0));
	out.write("\r\n");
	out.write("Degraded printing allowed: " + ((PdfWriter.ALLOW_DEGRADED_PRINTING & permissions) > 0));
	out.write("\r\n");
	out.flush();
	out.close();
}
 
Example #25
Source Project: itext2   Author: albfernandez   File: CustomPageSizeTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a PDF document with a certain pagesize
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Rectangle pageSize = new Rectangle(216, 720);
	pageSize.setBackgroundColor(new java.awt.Color(0xFF, 0xFF, 0xDE));
	Document document = new Document(pageSize);

	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file

	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("CustomPageSize.pdf"));

	// step 3: we open the document
	document.open();

	// step 4: we add some paragraphs to the document
	document.add(new Paragraph("The size of this page is 216x720 points."));
	document.add(new Paragraph("216pt / 72 points per inch = 3 inch"));
	document.add(new Paragraph("720pt / 72 points per inch = 10 inch"));
	document.add(new Paragraph("The size of this page is 3x10 inch."));
	document.add(new Paragraph("3 inch x 2.54 = 7.62 cm"));
	document.add(new Paragraph("10 inch x 2.54 = 25.4 cm"));
	document.add(new Paragraph("The size of this page is 7.62x25.4 cm."));
	document.add(new Paragraph("The backgroundcolor of the Rectangle used for this PageSize, is #FFFFDE."));
	document.add(new Paragraph("That's why the background of this document is yellowish..."));

	// step 5: we close the document
	document.close();
}
 
Example #26
private void insertTable_OrgAndPeriod( PdfPTable mainTable, PdfWriter writer, List<Period> periods )
    throws IOException, DocumentException
{
    boolean hasBorder = false;
    float width = 220.0f;

    // Input TextBox size
    Rectangle rectangle = new Rectangle( width, PdfDataEntryFormUtil.CONTENT_HEIGHT_DEFAULT );

    // Add Organization ID/Period textfield
    // Create A table to add for each group AT HERE
    PdfPTable table = new PdfPTable( 2 ); // Code 1
    table.setWidths( new int[]{ 1, 3 } );
    table.setHorizontalAlignment( Element.ALIGN_LEFT );


    addCell_Text( table, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), "Organization unit identifier", Element.ALIGN_RIGHT );
    addCell_WithTextField( table, rectangle, writer, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), PdfDataEntryFormUtil.LABELCODE_ORGID,
        PdfFieldCell.TYPE_TEXT_ORGUNIT );

    String[] periodsTitle = getPeriodTitles( periods, format );
    String[] periodsValue = getPeriodValues( periods );

    addCell_Text( table, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), "Period", Element.ALIGN_RIGHT );
    addCell_WithDropDownListField( table, rectangle, writer, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), PdfDataEntryFormUtil.LABELCODE_PERIODID, periodsTitle, periodsValue );

    // Add to the main table
    PdfPCell cell_withInnerTable = new PdfPCell( table );
    // cell_withInnerTable.setPadding(0);
    cell_withInnerTable.setBorder( Rectangle.NO_BORDER );

    cell_withInnerTable.setHorizontalAlignment( Element.ALIGN_LEFT );

    mainTable.addCell( cell_withInnerTable );
}
 
Example #27
/**
 * @see org.kuali.kfs.module.bc.document.service.BudgetConstructionReportsServiceHelper#generatePdf(java.util.List,
 *      java.io.ByteArrayOutputStream)
 */
@NonTransactional
public void generatePdf(List<String> errorMessages, ByteArrayOutputStream baos) throws DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();

    for (String error : errorMessages) {
        document.add(new Paragraph(error));
    }

    document.close();
}
 
Example #28
Source Project: dhis2-core   Author: dhis2   File: PdfFieldCell.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public PdfFieldCell( PdfFormField formField, float width, float height, int type, PdfWriter writer )
{
    this.formField = formField;
    this.width = width;
    this.height = height;
    this.writer = writer;
    this.type = type;
}
 
Example #29
Source Project: birt   Author: eclipse   File: PDFPageDevice.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * constructor for test
 *
 * @param output
 */
public PDFPageDevice( OutputStream output )
{
	doc = new Document( );
	try
	{
		writer = PdfWriter.getInstance( doc, new BufferedOutputStream(
				output ) );
	}
	catch ( DocumentException de )
	{
		logger.log( Level.SEVERE, de.getMessage( ), de );
	}
}
 
Example #30
Source Project: itext2   Author: albfernandez   File: JFreeChartTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
  * Converts a JFreeChart to PDF syntax.
  * @param filename	the name of the PDF file
  * @param chart		the JFreeChart
  * @param width		the width of the resulting PDF
  * @param height	the height of the resulting PDF
  */
 public static void convertToPdf(JFreeChart chart, int width, int height, String filename) {
 	// step 1
 	Document document = new Document(new Rectangle(width, height));
 	try {
 		// step 2
 		PdfWriter writer;
writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream(filename));
// step 3
 		document.open();
 		// step 4
 		PdfContentByte cb = writer.getDirectContent();
 		PdfTemplate tp = cb.createTemplate(width, height);
 		Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
 		Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
 		chart.draw(g2d, r2d);
 		g2d.dispose();
 		tp.sanityCheck();
 		cb.addTemplate(tp, 0, 0);
 		cb.sanityCheck();
 	}
 	catch(DocumentException de) {
 		de.printStackTrace();
 	}
 	catch (FileNotFoundException e) {
 		e.printStackTrace();
 	}
 	// step 5
 	document.close();
 }