com.lowagie.text.pdf.PdfWriter Java Examples

The following examples show how to use com.lowagie.text.pdf.PdfWriter. 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 File: SplitTableTest.java    From itext2 with 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 File: OptionalContentTest.java    From itext2 with GNU Lesser General Public License v3.0 7 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 #3
Source File: PurchaseOrderQuoteRequestsPdf.java    From kfs with 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 #4
Source File: PageNumbersWatermarkTest.java    From itext2 with 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 #5
Source File: CashReceiptCoverSheetServiceImpl.java    From kfs with 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 #6
Source File: PurchaseOrderQuoteRequestsPdf.java    From kfs with 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 #7
Source File: FieldPositioningEvents.java    From itext2 with 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 #8
Source File: DefaultPdfDataEntryFormService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #9
Source File: DifferentFontsTest.java    From itext2 with 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 #10
Source File: JavaScriptActionTest.java    From itext2 with 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 #11
Source File: ArabicTextTest.java    From itext2 with 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 #12
Source File: FieldPositioningEvents.java    From gcs with 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 #13
Source File: HelloSystemOutTest.java    From itext2 with 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 #14
Source File: DefaultPdfDataEntryFormService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #15
Source File: EndPageTest.java    From itext2 with 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 #16
Source File: PurapPdf.java    From kfs with 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 #17
Source File: NegativeLeadingTest.java    From itext2 with 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 #18
Source File: PdfWorksheet.java    From unitime with Apache License 2.0 5 votes vote down vote up
private PdfWorksheet(OutputStream out, Collection<SubjectArea> subjectAreas, String courseNumber) throws IOException, DocumentException  {
    iUseCommitedAssignments = ApplicationProperty.WorksheetPdfUseCommittedAssignments.isTrue();
    iSubjectAreas = new TreeSet<SubjectArea>(new Comparator<SubjectArea>() {
		@Override
		public int compare(SubjectArea s1, SubjectArea s2) {
			return s1.getSubjectAreaAbbreviation().compareTo(s2.getSubjectAreaAbbreviation());
		}
	});
    iSubjectAreas.addAll(subjectAreas);
    iCourseNumber = courseNumber;
    if (iCourseNumber!=null && (iCourseNumber.trim().length()==0 || "*".equals(iCourseNumber.trim().length())))
        iCourseNumber = null;
    iDoc = new Document(PageSize.LETTER.rotate());

    iOut = out;
    PdfWriter.getInstance(iDoc, iOut);

    String session = null;
    String subjects = "";
    for (SubjectArea sa: iSubjectAreas) {
    	if (subjects.isEmpty()) subjects += ", ";
    	subjects += sa.getSubjectAreaAbbreviation();
    	if (session == null) session += sa.getSession().getLabel();
    }
    iDoc.addTitle(subjects + (iCourseNumber==null?"":" "+iCourseNumber) + " Worksheet");
    iDoc.addAuthor(ApplicationProperty.WorksheetPdfAuthor.value().replace("%", Constants.getVersion()));
    iDoc.addSubject(subjects + (session == null ? "" : " -- " + session));
    iDoc.addCreator("UniTime "+Constants.getVersion()+", www.unitime.org");
    if (!iSubjectAreas.isEmpty())
    	iCurrentSubjectArea = iSubjectAreas.first();

    iDoc.open();
    
    printHeader();
}
 
Example #19
Source File: AHrefTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates some Anchor functionality.
 * 
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document();
	// step 2:
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("AHref.pdf"));
	HtmlWriter.getInstance(document, PdfTestBase.getOutputStream("AHref.html"));

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

	// step 4:
	Paragraph paragraph = new Paragraph("Please visit my ");
	Anchor anchor1 = new Anchor("website (external reference)", FontFactory.getFont(FontFactory.HELVETICA, 12,
			Font.UNDERLINE, new Color(0, 0, 255)));
	anchor1.setReference("http://www.lowagie.com/iText/");
	anchor1.setName("top");
	paragraph.add(anchor1);
	paragraph.add(new Chunk(".\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"));
	document.add(paragraph);
	Anchor anchor2 = new Anchor("please jump to a local destination", FontFactory.getFont(FontFactory.HELVETICA,
			12, Font.NORMAL, new Color(0, 0, 255)));
	anchor2.setReference("#top");
	document.add(anchor2);

	// step 5: we close the document
	document.close();
}
 
Example #20
Source File: ImagesTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * General Images example
 */
@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 a file
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Images.pdf"));

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

	// step 4:
	document.add(new Paragraph("A picture of my dog: otsoe.jpg"));
	Image jpg = Image.getInstance(PdfTestBase.RESOURCES_DIR + "otsoe.jpg");
	document.add(jpg);
	document.add(new Paragraph("getacro.gif"));
	Image gif = Image.getInstance(PdfTestBase.RESOURCES_DIR + "getacro.gif");
	document.add(gif);
	document.add(new Paragraph("pngnow.png"));
	Image png = Image.getInstance(PdfTestBase.RESOURCES_DIR + "pngnow.png");
	document.add(png);
	document.add(new Paragraph("iText.bmp"));
	Image bmp = Image.getInstance(PdfTestBase.RESOURCES_DIR + "iText.bmp");
	document.add(bmp);
	document.add(new Paragraph("iText.wmf"));
	Image wmf = Image.getInstance(PdfTestBase.RESOURCES_DIR + "iText.wmf");
	document.add(wmf);
	document.add(new Paragraph("iText.tif"));
	Image tiff = Image.getInstance(PdfTestBase.RESOURCES_DIR + "iText.tif");
	document.add(tiff);

	// step 5: we close the document
	document.close();
}
 
Example #21
Source File: PdfExportHelper.java    From mdw with Apache License 2.0 5 votes vote down vote up
@Override
public void onParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) {
    if (active) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.rectangle(document.left(), paragraphPosition - offset, document.right() - document.left(),
                startPosition - paragraphPosition);
        cb.stroke();
    }
}
 
Example #22
Source File: PdfLogicalPageDrawable.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public PdfLogicalPageDrawable( final PdfWriter writer, final LFUMap<ResourceKey, com.lowagie.text.Image> imageCache,
    final char version ) {
  if ( writer == null ) {
    throw new NullPointerException();
  }
  if ( imageCache == null ) {
    throw new NullPointerException();
  }
  this.writer = writer;
  this.imageCache = imageCache;
  this.version = version;
}
 
Example #23
Source File: OddEvenTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Combines 2 tiff-files into 1 PDF (similar to tiffmesh).
 * 
 * @param args
 *            [0] the file with the odd pages [1] the file with the even
 *            pages [2] the resulting file
 */
public void main(String... args) throws Exception {
	if (args.length < 3) {
		System.err.println("OddEven needs 3 Arguments.");
		System.out
				.println("Usage: com.lowagie.examples.objects.images.tiff.OddEven odd_file.tif even_file.tif combined_file.pdf");
		return;
	}
	RandomAccessFileOrArray odd = new RandomAccessFileOrArray(args[0]);
	RandomAccessFileOrArray even = new RandomAccessFileOrArray(args[1]);
	Image img = TiffImage.getTiffImage(odd, 1);
	Document document = new Document(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
	PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(args[2]));
	document.open();
	PdfContentByte cb = writer.getDirectContent();
	int count = Math.max(TiffImage.getNumberOfPages(odd), TiffImage.getNumberOfPages(even));
	for (int c = 0; c < count; ++c) {

		Image imgOdd = TiffImage.getTiffImage(odd, c + 1);
		Image imgEven = TiffImage.getTiffImage(even, count - c);
		document.setPageSize(new Rectangle(imgOdd.getScaledWidth(), imgOdd.getScaledHeight()));
		document.newPage();
		imgOdd.setAbsolutePosition(0, 0);
		cb.addImage(imgOdd);
		document.setPageSize(new Rectangle(imgEven.getScaledWidth(), imgEven.getScaledHeight()));
		document.newPage();
		imgEven.setAbsolutePosition(0, 0);
		cb.addImage(imgEven);

	}
	odd.close();
	even.close();
	document.close();

}
 
Example #24
Source File: PdfAnnotationsImp.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static PdfAnnotation convertAnnotation(PdfWriter writer, Annotation annot, Rectangle defaultRect) throws IOException {
     switch(annot.annotationType()) {
        case Annotation.URL_NET:
            return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((URL) annot.attributes().get(Annotation.URL)));
        case Annotation.URL_AS_STRING:
            return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((String) annot.attributes().get(Annotation.FILE)));
        case Annotation.FILE_DEST:
            return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((String) annot.attributes().get(Annotation.FILE), (String) annot.attributes().get(Annotation.DESTINATION)));
        case Annotation.SCREEN:
            boolean sparams[] = (boolean[])annot.attributes().get(Annotation.PARAMETERS);
            String fname = (String) annot.attributes().get(Annotation.FILE);
            String mimetype = (String) annot.attributes().get(Annotation.MIMETYPE);
            PdfFileSpecification fs;
            if (sparams[0])
                fs = PdfFileSpecification.fileEmbedded(writer, fname, fname, null);
            else
                fs = PdfFileSpecification.fileExtern(writer, fname);
            PdfAnnotation ann = PdfAnnotation.createScreen(writer, new Rectangle(annot.llx(), annot.lly(), annot.urx(), annot.ury()),
                    fname, fs, mimetype, sparams[1]);
            return ann;
        case Annotation.FILE_PAGE:
            return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((String) annot.attributes().get(Annotation.FILE), ((Integer) annot.attributes().get(Annotation.PAGE)).intValue()));
        case Annotation.NAMED_DEST:
            return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction(((Integer) annot.attributes().get(Annotation.NAMED)).intValue()));
        case Annotation.LAUNCH:
            return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((String) annot.attributes().get(Annotation.APPLICATION),(String) annot.attributes().get(Annotation.PARAMETERS),(String) annot.attributes().get(Annotation.OPERATION),(String) annot.attributes().get(Annotation.DEFAULTDIR)));
        default:
     	   return new PdfAnnotation(writer, defaultRect.getLeft(), defaultRect.getBottom(), defaultRect.getRight(), defaultRect.getTop(), new PdfString(annot.title(), PdfObject.TEXT_UNICODE), new PdfString(annot.content(), PdfObject.TEXT_UNICODE));
    }
}
 
Example #25
Source File: PageNumbersWatermarkTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onCloseDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onCloseDocument(PdfWriter writer, Document document) {
   tpl.beginText();
   tpl.setFontAndSize(helv, 12);
   tpl.setTextMatrix(0, 0);
   tpl.showText(Integer.toString(writer.getPageNumber() - 1));
   tpl.endText();
   tpl.sanityCheck();
}
 
Example #26
Source File: JFreeChartTest.java    From itext2 with 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();
 }
 
Example #27
Source File: PdfPageEventForwarder.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Called when the document is closed.
 * <P>
 * Note that this method is called with the page number equal to the last page plus one.
 *
 * @param writer the <CODE>PdfWriter</CODE> for this document
 * @param document the document
 */
@Override
public void onCloseDocument(PdfWriter writer, Document document) {
	PdfPageEvent event;
	for (Iterator i = events.iterator(); i.hasNext();) {
		event = (PdfPageEvent) i.next();
		event.onCloseDocument(writer, document);
	}
}
 
Example #28
Source File: FontCacheUtils.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
static void createUnicodePDF( String format, Locale locale, String fileName )
		throws Exception
{
	FontMappingManager manager = FontMappingManagerFactory.getInstance( )
			.getFontMappingManager( format, locale );

	// step 1: creation of a document-object
	Document document = new Document( );
	PdfWriter writer = PdfWriter.getInstance( document,
			new FileOutputStream( fileName ) );
	document.open( );
	for ( int seg = 0; seg < 0xFF; seg++ )
	{
		PdfContentByte cb = writer.getDirectContent( );
		cb.beginText( );
		for ( int hi = 0; hi < 16; hi++ )
		{
			for ( int lo = 0; lo < 16; lo++ )
			{
				int x = 100 + hi * 32;
				int y = 100 + lo * 32;
				char ch = (char) ( seg * 0xFF + hi * 16 + lo );

				String fontFamily = manager.getDefaultPhysicalFont( ch );
				BaseFont bf = manager.createFont( fontFamily, Font.NORMAL );
				cb.setFontAndSize( bf, 16 );
				cb.setTextMatrix( x, y );
				cb.showText( new String( new char[]{ch} ) );
			}
		}
		cb.endText( );
	}
	document.close( );
}
 
Example #29
Source File: SkewTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * SetSkew.
 * 
 */
@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("Skew.pdf"));

	// step 3: we open the document
	document.open();
	// step 4:
	Paragraph p = new Paragraph("Skew test:");
	document.add(p);
	Chunk chunk = new Chunk("TESTING skew");
	chunk.setSkew(45f, 0f);
	document.add(chunk);
	document.add(Chunk.NEWLINE);
	chunk.setSkew(0f, 45f);
	document.add(chunk);
	document.add(Chunk.NEWLINE);
	chunk.setSkew(-45f, 0f);
	document.add(chunk);
	document.add(Chunk.NEWLINE);
	chunk.setSkew(0f, -45f);
	document.add(chunk);
	document.add(Chunk.NEWLINE);
	chunk.setSkew(15f, 30f);
	document.add(chunk);
	document.add(Chunk.NEWLINE);
	Chunk italic = new Chunk("This looks like Font.ITALIC");
	italic.setSkew(0f, 12f);
	document.add(italic);

	// step 5: we close the document
	document.close();
}
 
Example #30
Source File: PurchaseOrderPdf.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generates the pdf document based on the data in the given PurchaseOrderDocument, the pdf parameters,
 * environment, retransmit items, creates a pdf writer using the given byteArrayOutputStream then
 * write the pdf document into the writer.
 *
 * @param po                     The PurchaseOrderDocument to be used to generate the pdf.
 * @param pdfParameters          The PurchaseOrderPdfParameters to be used to generate the pdf.
 * @param byteArrayOutputStream  The ByteArrayOutputStream where the pdf document will be written to.
 * @param isRetransmit           The boolean to indicate whether this is for a retransmit purchase order document.
 * @param environment            The current environment used (e.g. DEV if it is a development environment).
 * @param retransmitItems        The items selected by the user to be retransmitted.
 */
public void generatePdf(PurchaseOrderDocument po, PurchaseOrderTransmitParameters pdfParameters, ByteArrayOutputStream byteArrayOutputStream, boolean isRetransmit, String environment, List<PurchaseOrderItem> retransmitItems) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("generatePdf() started for po number " + po.getPurapDocumentIdentifier());
    }

    this.isRetransmit = isRetransmit;
    String statusInquiryUrl = pdfParameters.getStatusInquiryUrl();
    String campusName = pdfParameters.getCampusParameter().getCampus().getName();
    String contractLanguage = pdfParameters.getContractLanguage();
    String logoImage = pdfParameters.getLogoImage();
    String directorSignatureImage = pdfParameters.getDirectorSignatureImage();
    String directorName = pdfParameters.getCampusParameter().getCampusPurchasingDirectorName();
    String directorTitle = pdfParameters.getCampusParameter().getCampusPurchasingDirectorTitle();
    String contractManagerSignatureImage = pdfParameters.getContractManagerSignatureImage();

    try {
        Document doc = this.getDocument(9, 9, 70, 36);
        PdfWriter writer = PdfWriter.getInstance(doc, byteArrayOutputStream);
        this.createPdf(po, doc, writer, statusInquiryUrl, campusName, contractLanguage, logoImage, directorSignatureImage, directorName, directorTitle, contractManagerSignatureImage, isRetransmit, environment, retransmitItems);
    }
    catch (DocumentException de) {
        LOG.error("generatePdf() DocumentException: " + de.getMessage(), de);
        throw new PurError("Document Exception when trying to save a Purchase Order PDF", de);
    }
    catch (IOException i) {
        LOG.error("generatePdf() IOException: " + i.getMessage(), i);
        throw new PurError("IO Exception when trying to save a Purchase Order PDF", i);
    }
    catch (Exception t) {
        LOG.error("generatePdf() EXCEPTION: " + t.getMessage(), t);
        throw new PurError("Exception when trying to save a Purchase Order PDF", t);
    }
}