Java Code Examples for com.lowagie.text.Document#add()

The following examples show how to use com.lowagie.text.Document#add() . 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: CustomerLoadServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void writeFileNameSectionTitle(Document pdfDoc, String filenameLine) {
    Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.BOLD);

    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(Element.ALIGN_LEFT);
    Chunk chunk = new Chunk(filenameLine, font);
    chunk.setBackground(Color.LIGHT_GRAY, 5, 5, 5, 5);
    paragraph.add(chunk);

    //  blank line
    paragraph.add(new Chunk("", font));

    try {
        pdfDoc.add(paragraph);
    }
    catch (DocumentException e) {
        LOG.error("iText DocumentException thrown when trying to write content.", e);
        throw new RuntimeException("iText DocumentException thrown when trying to write content.", e);
    }
}
 
Example 2
Source File: FontEncodingTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
    * Specifying an encoding.
    */
@Test
   public void main() throws Exception {
       
       
       // step 1: creation of a document-object
       Document document = new Document();
       
           
           // step 2: creation of the writer
           PdfWriter.getInstance(document, PdfTestBase.getOutputStream("fontencoding.pdf"));
           
           // step 3: we open the document
           document.open();
           
           // step 4: we add content to the document
           BaseFont helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
           Font font = new Font(helvetica, 12, Font.NORMAL);
           Chunk chunk = new Chunk("Sponsor this example and send me 1\u20ac. These are some special characters: \u0152\u0153\u0160\u0161\u0178\u017D\u0192\u02DC\u2020\u2021\u2030", font);
           document.add(chunk);
       
       // step 5: we close the document
       document.close();
   }
 
Example 3
Source File: LocalDestinationTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a document that jumps to a Local Destination upon opening.
 * 
 */
@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("LocalDestination.pdf"));
	// step 3: we open the document
	document.open();
	// step 4: we add some content
	document.add(new Paragraph("Page 1"));
	document.newPage();
	document.add(new Paragraph("This PDF file jumps directly to page 2 when opened"));
	PdfContentByte cb = writer.getDirectContent();
	cb.localDestination("page2", new PdfDestination(PdfDestination.XYZ, -1, 10000, 0));
	writer.setOpenAction("page2");

	// step 5: we close the document
	document.close();
}
 
Example 4
Source File: PdfVersionTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a PDF document and shows the PDF version.
 */
@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 writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("pdfversion.pdf"));
	writer.setPdfVersion(PdfWriter.VERSION_1_2);
	// step 3: we open the document
	document.open();

	// step 4:
	document.add(new Paragraph("This is a PDF-1.2 document"));

	// step 5: we close the document
	document.close();
}
 
Example 5
Source File: ChainedActionsTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a document with chained Actions.
 * 
 */
@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("ChainedActions.pdf"));
	// step 3: we add Javascript as Metadata and we open the document
	document.open();
	// step 4: we add some content
	PdfAction action = PdfAction.javaScript("app.alert('Welcome at my site');\r", writer);
	action.next(new PdfAction("http://www.lowagie.com/iText/"));
	Paragraph p = new Paragraph(new Chunk("Click to go to Bruno's site").setAction(action));
	document.add(p);

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

}
 
Example 6
Source File: HelloWorldTest.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 a file
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("HelloWorld.pdf"));

	// 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 7
Source File: FontSelectionTest.java    From itext2 with GNU Lesser General Public License v3.0 5 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("fontselection.pdf"));
	// step 3
	document.open();
	// step 4
	String text = "This text is the first verse of \u275dThe Iliad\u275e. It's not polytonic as it should be "
			+ "with \u2798 and \u279a entoation variants but that's all we have for now.\n\n"
			+ "\u2766\u00a0\u00a0\u039c\u03b7\u03bd\u03b9\u03bd \u03b1\u03b5\u03b9\u03b4\u03b5, \u03b8\u03b5\u03b1, \u03a0\u03b7\u03bb\u03b7\u03b9\u03b1\u03b4\u03b5\u03c9 \u0391\u03c7\u03b9\u03bb\u03b7\u03bf\u03c2";
	FontSelector sel = new FontSelector();
	sel.addFont(new Font(Font.TIMES_ROMAN, 12));
	sel.addFont(new Font(Font.ZAPFDINGBATS, 12));
	sel.addFont(new Font(Font.SYMBOL, 12));
	Phrase ph = sel.process(text);
	document.add(new Paragraph(ph));
	// step 5
	document.close();

}
 
Example 8
Source File: TablePdfTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testCreateTable() throws FileNotFoundException,
		DocumentException {
	// create document
	Document document = PdfTestBase.createPdf("testCreateTable.pdf");
	try {
		// new page with a table
		document.open();
		document.newPage();

		PdfPTable table = createPdfTable(2);

		for (int i = 0; i < 10; i++) {
			PdfPCell cell = new PdfPCell();
			cell.setRowspan(2);
			table.addCell(cell);

		}
		table.calculateHeights(true);
		document.add(table);
		document.newPage();

	} finally {
		// close document
		if (document != null)
			document.close();
	}

}
 
Example 9
Source File: SurveyPdf.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeAnswer(Document document,String questionText , String answerValue) throws Exception{
	Paragraph questionParagraph = new Paragraph();
	questionParagraph.setLeading(14, 0);
	questionParagraph.add(new Chunk(questionText.trim() + ": ",boldedFont)); 
    questionParagraph.add(new Chunk(answerValue == null ? "": answerValue.trim() ,normalFont));  
	document.add(questionParagraph);
}
 
Example 10
Source File: AccountSummaryController.java    From primefaces-blueprints with The Unlicense 5 votes vote down vote up
public void postProcessPDF(Object document) throws IOException, BadElementException, DocumentException {  
	 Document pdf = (Document) document; 
	 pdf.add( Chunk.NEWLINE );
	 Font fontbold = FontFactory.getFont("Times-Roman", 14, Font.BOLD);
	 pdf.add(new Paragraph("Disclaimer",fontbold));
	 pdf.add( Chunk.NEWLINE );
	 pdf.add(new Paragraph("The information contained in this website is for information purposes only, and does not constitute, nor is it intended to constitute, the provision of financial product advice."));
	 pdf.add(new Paragraph("This website is intended to track the investor account summary information,investments and transaction in a partcular period of time. "));
}
 
Example 11
Source File: TotalPageNumberTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates creating a header with page number and total number of pages
 * 
 * 
 */
@Test
public void main() throws Exception {
	Document document = new Document();
	RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("TotalPageNumber.rtf"));

	// Create a new Paragraph for the footer
	Paragraph par = new Paragraph("Page ");

	// Add the RtfPageNumber to the Paragraph
	par.add(new RtfPageNumber());

	// Add the RtfTotalPageNumber to the Paragraph
	par.add(" of ");
	par.add(new RtfTotalPageNumber());

	// Create an RtfHeaderFooter with the Paragraph and set it
	// as a header for the document
	RtfHeaderFooter header = new RtfHeaderFooter(par);
	document.setHeader(header);

	document.open();

	for (int i = 1; i <= 300; i++) {
		document.add(new Paragraph("Line " + i + "."));
	}

	document.close();

}
 
Example 12
Source File: NamedActionsTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a document with Named Actions.
 * 
 */
@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: we create a writer that listens to the document
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("NamedActions.pdf"));
	// step 3: we open the document
	document.open();
	// step 4: we add some content
	Paragraph p = new Paragraph(new Chunk("Click to print").setAction(new PdfAction(PdfAction.PRINTDIALOG)));
	PdfPTable table = new PdfPTable(4);
	table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
	table.addCell(new Phrase(new Chunk("First Page").setAction(new PdfAction(PdfAction.FIRSTPAGE))));
	table.addCell(new Phrase(new Chunk("Prev Page").setAction(new PdfAction(PdfAction.PREVPAGE))));
	table.addCell(new Phrase(new Chunk("Next Page").setAction(new PdfAction(PdfAction.NEXTPAGE))));
	table.addCell(new Phrase(new Chunk("Last Page").setAction(new PdfAction(PdfAction.LASTPAGE))));
	for (int k = 1; k <= 10; ++k) {
		document.add(new Paragraph("This is page " + k));
		document.add(Chunk.NEWLINE);
		document.add(table);
		document.add(p);
		document.newPage();
	}

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

}
 
Example 13
Source File: WidthHeightTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Width and height of a textstring
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {


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

	// step 2: creation of the writer-object
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("widthheight.pdf"));

	// step 3: we open the document
	document.open();
	File fontPath = new File (PdfTestBase.RESOURCES_DIR + "/liberation-fonts-ttf/LiberationSans-Regular.ttf");
	// step 4: we add content to the document
	BaseFont bfComic = BaseFont.createFont(fontPath.getAbsolutePath(), BaseFont.WINANSI, BaseFont.EMBEDDED);
	Font font = new Font(bfComic, 12);
	String text1 = "quick brown fox jumps";
	String text2 = " over ";
	String text3 = "the lazy dog";
	document.add(new Paragraph(text1, font));
	document.add(new Paragraph("width: " + bfComic.getWidthPoint(text1, 12)));
	document.add(new Paragraph("ascent: " + bfComic.getAscentPoint(text1, 12)));
	document.add(new Paragraph("descent: " + bfComic.getDescentPoint(text1, 12)));
	document.add(new Paragraph("height: "
			+ (bfComic.getAscentPoint(text1, 12) - bfComic.getDescentPoint(text1, 12))));
	document.add(new Paragraph(text2, font));
	document.add(new Paragraph("width: " + bfComic.getWidthPoint(text2, 12)));
	document.add(new Paragraph("ascent: " + bfComic.getAscentPoint(text2, 12)));
	document.add(new Paragraph("descent: " + bfComic.getDescentPoint(text2, 12)));
	document.add(new Paragraph("height: "
			+ (bfComic.getAscentPoint(text2, 12) - bfComic.getDescentPoint(text2, 12))));
	document.add(new Paragraph(text3, font));
	document.add(new Paragraph("width: " + bfComic.getWidthPoint(text3, 12)));
	document.add(new Paragraph("ascent: " + bfComic.getAscentPoint(text3, 12)));
	document.add(new Paragraph("descent: " + bfComic.getDescentPoint(text3, 12)));
	document.add(new Paragraph("height: "
			+ (bfComic.getAscentPoint(text3, 12) - bfComic.getDescentPoint(text3, 12))));
	document.add(new Paragraph(text1 + text2 + text3, font));
	document.add(new Paragraph("width: " + bfComic.getWidthPoint(text1 + text2 + text3, 12)));
	document.add(new Paragraph("ascent: " + bfComic.getAscentPoint(text1 + text2 + text3, 12)));
	document.add(new Paragraph("descent: " + bfComic.getDescentPoint(text1 + text2 + text3, 12)));
	document.add(new Paragraph("height: "
			+ (bfComic.getAscentPoint(text1 + text2 + text3, 12) - bfComic.getDescentPoint(text1 + text2 + text3,
					12))));

	// step 5: we close the document
	document.close();
}
 
Example 14
Source File: BulkReceivingPdf.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Generates the pdf document based on the data in the given BulkReceivingDocument
 * 
 * @param blkRecDoc   The BulkReceivingDocument to be used to generate the pdf.
 * @param byteStream  The ByteArrayOutputStream where the pdf document will be written to.
 */
public void generatePdf(BulkReceivingDocument blkRecDoc, 
                        ByteArrayOutputStream byteStream,
                        String logoImage,
                        String environment) {
    
    if (LOG.isDebugEnabled()) {
        LOG.debug("generatePdf() started for bulk receiving - " + blkRecDoc.getDocumentNumber());
    }

    Document document = null;
    
    try {
        
        document = this.getDocument(9, 9, 70, 36);
        PdfWriter writer = PdfWriter.getInstance(document, byteStream);

        //These have to be set because they are used by the onOpenDocument() and onStartPage() methods.
        this.logoImage = logoImage;
        this.blkRecDoc = blkRecDoc;
        this.environment = environment;
        
        // This turns on the page events that handle the header and page numbers.
        BulkReceivingPdf events = new BulkReceivingPdf().getPageEvents();
        writer.setPageEvent(this); 

        document.open();
        
        document.add(createVendorAndDeliveryDetailsTable());
        document.add(new Paragraph("\nAdditional Details\n  ", ver_8_bold));
        document.add(createAdditionalDetailsTable());
        
        document.close();
        
    }catch (Exception de) {
        throw new RuntimeException("Document Exception when trying to save a Bulk Receiving PDF", de);
    }finally{
        if (document != null && document.isOpen()){
            document.close();
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("generatePdf() completed for bulk receiving - " + blkRecDoc.getDocumentNumber());
    }
}
 
Example 15
Source File: ContractsGrantsInvoiceReportServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Generates the pdf file for printing the envelopes.
 *
 * @param list
 * @param outputStream
 * @throws DocumentException
 * @throws IOException
 */
protected void generateCombinedPdfForEnvelopes(Collection<ContractsGrantsInvoiceDocument> list, OutputStream outputStream) throws DocumentException, IOException {
    Document document = new Document(new Rectangle(ArConstants.InvoiceEnvelopePdf.LENGTH, ArConstants.InvoiceEnvelopePdf.WIDTH));
    PdfWriter.getInstance(document, outputStream);
    boolean pageAdded = false;

    for (ContractsGrantsInvoiceDocument invoice : list) {
        // add a document
        for (InvoiceAddressDetail invoiceAddressDetail : invoice.getInvoiceAddressDetails()) {
            if (ArConstants.InvoiceTransmissionMethod.MAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) {
                CustomerAddress address = invoiceAddressDetail.getCustomerAddress();

                Integer numberOfEnvelopesToPrint = address.getCustomerEnvelopesToPrintQuantity();
                if (ObjectUtils.isNull(numberOfEnvelopesToPrint)) {
                    numberOfEnvelopesToPrint = 1;
                }
                for (int i = 0; i < numberOfEnvelopesToPrint; i++) {
                    // if a page has not already been added then open the document.
                    if (!pageAdded) {
                        document.open();
                    }
                    pageAdded = true;
                    document.newPage();
                    // adding the sent From address
                    Organization org = invoice.getInvoiceGeneralDetail().getAward().getPrimaryAwardOrganization().getOrganization();
                    Paragraph sentBy = generateAddressParagraph(org.getOrganizationName(), org.getOrganizationLine1Address(), org.getOrganizationLine2Address(), org.getOrganizationCityName(), org.getOrganizationStateCode(), org.getOrganizationZipCode(), ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT);
                    sentBy.setIndentationLeft(ArConstants.InvoiceEnvelopePdf.INDENTATION_LEFT);
                    sentBy.setAlignment(Element.ALIGN_LEFT);

                    // adding the send To address
                    String string;
                    Paragraph sendTo = generateAddressParagraph(address.getCustomerAddressName(), address.getCustomerLine1StreetAddress(), address.getCustomerLine2StreetAddress(), address.getCustomerCityName(), address.getCustomerStateCode(), address.getCustomerZipCode(), ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT);
                    sendTo.setAlignment(Element.ALIGN_CENTER);
                    sendTo.add(new Paragraph(KFSConstants.BLANK_SPACE));

                    document.add(sentBy);
                    document.add(sendTo);
                }
            }
        }
    }
    if (pageAdded) {
        document.close();
    }
}
 
Example 16
Source File: ExampleEAN128Test.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Example Barcode EAN128.
 */
@Test
public void main() throws Exception {

	// step 1
	Document document = new Document();
	// step 2
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("ean128.pdf"));
	// step 3
	document.open();
	// step 4
	PdfContentByte cb = writer.getDirectContent();
	PdfPTable pageTot = new PdfPTable(1);
	pageTot.getDefaultCell().setPadding(0f);
	pageTot.getDefaultCell().setBorder(Rectangle.NO_BORDER);
	pageTot.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
	pageTot.setWidthPercentage(100f);
	// Data for the barcode : it is composed of 3 blocks whith AI 402, 90
	// and 421
	// The blocks whith the type 402 and 90 are of variable size so you must
	// put a FNC1
	// to delimitate the block
	String code402 = "24132399420058289" + Barcode128.FNC1;
	String code90 = "3700000050" + Barcode128.FNC1;
	String code421 = "422356";
	String data = code402 + code90 + code421;

	PdfPTable cell = new PdfPTable(1);
	cell.getDefaultCell().setBorder(Rectangle.NO_BORDER);
	cell.getDefaultCell().setPadding(0f);

	PdfPCell info = new PdfPCell(new Phrase("Barcode EAN 128"));
	info.setBorder(Rectangle.NO_BORDER);
	pageTot.addCell(info);

	Barcode128 shipBarCode = new Barcode128();
	shipBarCode.setX(0.75f);
	shipBarCode.setN(1.5f);
	shipBarCode.setChecksumText(true);
	shipBarCode.setGenerateChecksum(true);
	shipBarCode.setSize(10f);
	shipBarCode.setTextAlignment(Element.ALIGN_CENTER);
	shipBarCode.setBaseline(10f);
	shipBarCode.setCode(data);
	shipBarCode.setBarHeight(50f);

	Image imgShipBarCode = shipBarCode.createImageWithBarcode(cb, Color.black, Color.blue);
	PdfPCell shipment = new PdfPCell(new Phrase(new Chunk(imgShipBarCode, 0, 0)));
	shipment.setFixedHeight(shipBarCode.getBarcodeSize().getHeight() + 16f);
	shipment.setPaddingTop(5f);
	shipment.setPaddingBottom(10f);
	shipment.setBorder(Rectangle.BOX);
	shipment.setVerticalAlignment(Element.ALIGN_TOP);
	shipment.setHorizontalAlignment(Element.ALIGN_CENTER);
	cell.addCell(shipment);

	pageTot.addCell(cell);

	document.add(pageTot);

	// step 5
	document.close();
}
 
Example 17
Source File: RtfTOCandCellbordersTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Creates an RTF document with a TOC and Table with special Cellborders.
 * 
 * 
 */
@Test
public void main() throws Exception {
	Document document = new Document();
	RtfWriter2 writer2 = RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("toc.rtf"));

	writer2.setAutogenerateTOCEntries(true);

	document.open();

	Paragraph para = new Paragraph();
	para.add(new RtfTableOfContents("RIGHT CLICK AND HERE AND SELECT \"UPDATE FIELD\" TO UPDATE."));
	document.add(para);

	Paragraph par = new Paragraph("This is some sample content.");
	Chapter chap1 = new Chapter("Chapter 1", 1);
	chap1.add(par);
	Chapter chap2 = new Chapter("Chapter 2", 2);
	chap2.add(par);
	document.add(chap1);
	document.add(chap2);

	for (int i = 0; i < 300; i++) {
		if (i == 158) {
			document.add(new RtfTOCEntry("This is line 158."));
		}
		document.add(new Paragraph("Line " + i));
	}

	document.add(new RtfTOCEntry("Cell border demonstration"));

	Table table = new Table(3);

	RtfCell cellDotted = new RtfCell("Dotted border");
	cellDotted.setBorders(new RtfBorderGroup(Rectangle.BOX, RtfBorder.BORDER_DOTTED, 1, new Color(0, 0, 0)));
	RtfCell cellEmbossed = new RtfCell("Embossed border");
	cellEmbossed.setBorders(new RtfBorderGroup(Rectangle.BOX, RtfBorder.BORDER_EMBOSS, 1, new Color(0, 0, 0)));
	RtfCell cellNoBorder = new RtfCell("No border");
	cellNoBorder.setBorders(new RtfBorderGroup());

	table.addCell(cellDotted);
	table.addCell(cellEmbossed);
	table.addCell(cellNoBorder);

	document.add(table);
	document.close();
}
 
Example 18
Source File: ImageMasksTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
    * Applying masks to images.
 */
@Test
public void main() throws Exception {
       
       
       Document document = new Document(PageSize.A4, 50, 50, 50, 50);
       try {
           PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "maskedImages.pdf"));
           
           document.open();
           Paragraph p = new Paragraph("Some text behind a masked image.");
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           document.add(p);
           PdfContentByte cb = writer.getDirectContent();
           byte maskr[] = {(byte)0x3c, (byte)0x7e, (byte)0xe7, (byte)0xc3, (byte)0xc3, (byte)0xe7, (byte)0x7e, (byte)0x3c};
           Image mask = Image.getInstance(8, 8, 1, 1, maskr);
           mask.makeMask();
           mask.setInverted(true);
           Image image = Image.getInstance(PdfTestBase.RESOURCES_DIR +"otsoe.jpg");
           image.setImageMask(mask);
           image.setAbsolutePosition(60, 550);
           // explicit masking
           cb.addImage(image);
           // stencil masking
           cb.setRGBColorFill(255, 0, 0);
           cb.addImage(mask, mask.getScaledWidth() * 8, 0, 0, mask.getScaledHeight() * 8, 100, 450);
           cb.setRGBColorFill(0, 255, 0);
           cb.addImage(mask, mask.getScaledWidth() * 8, 0, 0, mask.getScaledHeight() * 8, 100, 400);
           cb.setRGBColorFill(0, 0, 255);
           cb.addImage(mask, mask.getScaledWidth() * 8, 0, 0, mask.getScaledHeight() * 8, 100, 350);
           document.close();
       }
       catch (Exception de) {
           de.printStackTrace();
       }
   }
 
Example 19
Source File: TemplateImagesTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
    * PdfTemplates can be wrapped in an Image.
    */
@Test
   public  void main() throws Exception {
       
           
       // step 1: creation of a document-object
       Rectangle rect = new Rectangle(PageSize.A4);
       rect.setBackgroundColor(new Color(238, 221, 88));
       Document document = new Document(rect, 50, 50, 50, 50);
	// step 2: we create a writer that listens to the document
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("templateImages.pdf"));
	// step 3: we open the document
	document.open();
	// step 4:
	PdfTemplate template = writer.getDirectContent().createTemplate(20, 20);
	BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
			BaseFont.NOT_EMBEDDED);
	String text = "Vertical";
	float size = 16;
	float width = bf.getWidthPoint(text, size);
	template.beginText();
	template.setRGBColorFillF(1, 1, 1);
	template.setFontAndSize(bf, size);
	template.setTextMatrix(0, 2);
	template.showText(text);
	template.endText();
	template.setWidth(width);
	template.setHeight(size + 2);
	template.sanityCheck();
	Image img = Image.getInstance(template);
	img.setRotationDegrees(90);
	Chunk ck = new Chunk(img, 0, 0);
	PdfPTable table = new PdfPTable(3);
	table.setWidthPercentage(100);
	table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
	table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
	PdfPCell cell = new PdfPCell(img);
	cell.setPadding(4);
	cell.setBackgroundColor(new Color(0, 0, 255));
	cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	table.addCell("I see a template on my right");
	table.addCell(cell);
	table.addCell("I see a template on my left");
	table.addCell(cell);
	table.addCell("I see a template everywhere");
	table.addCell(cell);
	table.addCell("I see a template on my right");
	table.addCell(cell);
	table.addCell("I see a template on my left");

	Paragraph p1 = new Paragraph("This is a template ");
	p1.add(ck);
	p1.add(" just here.");
	p1.setLeading(img.getScaledHeight() * 1.1f);
	document.add(p1);
	document.add(table);
	Paragraph p2 = new Paragraph("More templates ");
	p2.setLeading(img.getScaledHeight() * 1.1f);
	p2.setAlignment(Element.ALIGN_JUSTIFIED);
	img.scalePercent(70);
	for (int k = 0; k < 20; ++k)
		p2.add(ck);
	document.add(p2);
	// step 5: we close the document
	document.close();

   }
 
Example 20
Source File: RawDataTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Raw data.
 */
@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("rawdata.pdf"));

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

	// step 4: we add content (example by Paulo Soares)

	// creation a jpeg passed as an array of bytes to the Image
	RandomAccessFile rf = new RandomAccessFile(PdfTestBase.RESOURCES_DIR + "otsoe.jpg", "r");
	int size = (int) rf.length();
	byte imext[] = new byte[size];
	rf.readFully(imext);
	rf.close();
	Image img1 = Image.getInstance(imext);
	img1.setAbsolutePosition(50, 500);
	document.add(img1);

	// creation of an image of 100 x 100 pixels (x 3 bytes for the Red,
	// Green and Blue value)
	byte data[] = new byte[100 * 100 * 3];
	for (int k = 0; k < 100; ++k) {
		for (int j = 0; j < 300; j += 3) {
			data[k * 300 + j] = (byte) (255 * Math.sin(j * .5 * Math.PI / 300));
			data[k * 300 + j + 1] = (byte) (256 - j * 256 / 300);
			data[k * 300 + j + 2] = (byte) (255 * Math.cos(k * .5 * Math.PI / 100));
		}
	}
	Image img2 = Image.getInstance(100, 100, 3, 8, data);
	img2.setAbsolutePosition(200, 200);
	document.add(img2);

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