Java Code Examples for com.lowagie.text.pdf.PdfContentByte#addImage()

The following examples show how to use com.lowagie.text.pdf.PdfContentByte#addImage() . 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: 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 2
Source File: TransformImageTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
    * Add an image using different transformation matrices.
    */
@Test
public void main() throws Exception {
       Document.compress = false;
       // step 1: creation of a document-object
       Document document = new Document(PageSize.A4);
       
       try {
           // step 2: creation of the writer
           PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "transformimage.pdf"));
           
           // step 3: we open the document
           document.open();
           
           // step 4:
           PdfContentByte cb = writer.getDirectContent();
           Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR + "hitchcock.png");
           cb.addImage(img, 271, -50, -30, 550, 100, 100);
           cb.sanityCheck();
  
       }
       catch(DocumentException de) {
           System.err.println(de.getMessage());
       }
       catch(IOException ioe) {
           System.err.println(ioe.getMessage());
       }
       
       // step 5: we close the document
       document.close();
   }
 
Example 3
Source File: SoftMaskTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates the Transparency functionality.
 */
@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 a writer
	PdfWriter writer = PdfWriter.getInstance(document,PdfTestBase.getOutputStream("softmask.pdf"));
	// step 3: we open the document
	document.open();
	// step 4: content
	PdfContentByte cb = writer.getDirectContent();
	String text = "text ";
	text += text;
	text += text;
	text += text;
	text += text;
	text += text;
	text += text;
	text += text;
	text += text;
	document.add(new Paragraph(text));
	Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR	+ "otsoe.jpg");
	img.setAbsolutePosition(100, 550);
	byte gradient[] = new byte[256];
	for (int k = 0; k < 256; ++k) {
		gradient[k] = (byte) k;
	}
	Image smask = Image.getInstance(256, 1, 1, 8, gradient);
	smask.makeMask();
	img.setImageMask(smask);
	cb.addImage(img);
	cb.sanityCheck();
	// step 5: we close the document
	document.close();
}
 
Example 4
Source File: AwtImageTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Uses a java.awt.Image object to construct a com.lowagie.text.Image
 * object.
 */
@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("awt_image.pdf"));

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

	// step 4: we add content to the document
	for (int i = 0; i < 300; i++) {
		document.add(new Phrase("Who is this? "));
	}
	PdfContentByte cb = writer.getDirectContent();
	java.awt.Image awtImage = Toolkit.getDefaultToolkit().createImage(PdfTestBase.RESOURCES_DIR + "H.gif");
	Image image = Image.getInstance(awtImage, null);
	image.setAbsolutePosition(100, 500);
	cb.addImage(image);
	Image gif = Image.getInstance(awtImage, new Color(0x00, 0xFF, 0xFF), true);
	gif.setAbsolutePosition(300, 500);
	cb.addImage(gif);
	Image img1 = Image.getInstance(awtImage, null, true);
	img1.setAbsolutePosition(100, 200);
	cb.addImage(img1);
	Image img2 = Image.getInstance(awtImage, new Color(0xFF, 0xFF, 0x00), false);
	img2.setAbsolutePosition(300, 200);
	cb.addImage(img2);

	// step 5: we close the document
	document.close();
}
 
Example 5
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 6
Source File: AddWatermarkPageNumbersTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
    * Reads the pages of an existing PDF file, adds pagenumbers and a watermark.

    */
@Test
   public  void main() throws Exception {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(PdfTestBase.RESOURCES_DIR +"ChapterSection.pdf");
           int n = reader.getNumberOfPages();
           // we create a stamper that will copy the document to a new file
           PdfStamper stamp = new PdfStamper(reader,PdfTestBase.getOutputStream("watermark_pagenumbers.pdf"));
           // adding some metadata
           HashMap<String, String> moreInfo = new HashMap<String, String>();
           moreInfo.put("Author", "Bruno Lowagie");
           stamp.setMoreInfo(moreInfo);
           // adding content to each page
           int i = 0;
           PdfContentByte under;
           PdfContentByte over;
           Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR +"watermark.jpg");
           BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
           img.setAbsolutePosition(200, 400);
           while (i < n) {
           	i++;
           	// watermark under the existing page
           	under = stamp.getUnderContent(i);
           	under.addImage(img);
           	// text over the existing page
           	over = stamp.getOverContent(i);
           	over.beginText();
           	over.setFontAndSize(bf, 18);
           	over.setTextMatrix(30, 30);
           	over.showText("page " + i);
           	over.setFontAndSize(bf, 32);
           	over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
           	over.endText();
           }
           // adding an extra page
           stamp.insertPage(1, PageSize.A4);
           over = stamp.getOverContent(1);
       	over.beginText();
       	over.setFontAndSize(bf, 18);
           over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE OF AN EXISTING PDF DOCUMENT", 30, 600, 0);
           over.endText();
           // adding a page from another document
           PdfReader reader2 = new PdfReader(PdfTestBase.RESOURCES_DIR +"SimpleAnnotations1.pdf");
           under = stamp.getUnderContent(1);
           under.addTemplate(stamp.getImportedPage(reader2, 3), 1, 0, 0, 1, 0, 0);
           // closing PdfStamper will generate the new PDF file
           stamp.close();
   }
 
Example 7
Source File: PageNumbersWatermarkTest.java    From itext2 with GNU Lesser General Public License v3.0 4 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) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // write the headertable
    table.setTotalWidth(document.right() - document.left());
    table.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 50, 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);
    // for odd pagenumbers, show the footer at the left
    if ((writer.getPageNumber() & 1) == 1) {
        cb.setTextMatrix(document.left(), textBase);
        cb.showText(text);
        cb.endText();
        cb.addTemplate(tpl, document.left() + textSize, textBase);
    }
    // for even numbers, show the footer at the right
    else {
        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);
    }

    // draw a Rectangle around the page
    cb.setColorStroke(Color.orange);
    cb.setLineWidth(2);
    cb.rectangle(20, 20, document.getPageSize().getWidth() - 40, document.getPageSize().getHeight() - 40);
    cb.stroke();

    // starting on page 3, a watermark with an Image that is made transparent
    if (writer.getPageNumber() >= 3) {

        cb.setGState(gstate);
        cb.setColorFill(Color.red);
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        cb.showTextAligned(Element.ALIGN_CENTER, "Watermark Opacity " + writer.getPageNumber(), document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45);
        cb.endText();
        try {
            cb.addImage(headerImage, headerImage.getWidth(), 0, 0, headerImage.getHeight(), 440, 80);
        }
        catch(Exception e) {
            throw new ExceptionConverter(e);
        }
    }
    cb.restoreState();
    cb.sanityCheck();
}
 
Example 8
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 9
Source File: ColumnIrregularTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Demonstrates the use of ColumnText.
 */
@Test
public void main() throws Exception {

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

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

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

	// step 4:
	// we grab the contentbyte and do some stuff with it
	PdfContentByte cb = writer.getDirectContent();

	PdfTemplate t = cb.createTemplate(600, 800);
	Image caesar = Image.getInstance(PdfTestBase.RESOURCES_DIR + "caesar_coin.jpg");
	cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
	t.setGrayFill(0.75f);
	t.moveTo(310, 112);
	t.lineTo(280, 60);
	t.lineTo(340, 60);
	t.closePath();
	t.moveTo(310, 790);
	t.lineTo(310, 710);
	t.moveTo(310, 580);
	t.lineTo(310, 122);
	t.stroke();
	cb.addTemplate(t, 0, 0);

	ColumnText ct = new ColumnText(cb);
	ct.addText(new Phrase(
			"GALLIA est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur.  Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt.  Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt.\n",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));
	ct.addText(new Phrase(
			"[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]\n",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));
	ct.addText(new Phrase(
			"Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix.  Is M. Messala, [et P.] M.  Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent:  perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri.  Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur:  una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit.  His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore adficiebantur.  Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant.\n",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));
	ct.addText(new Phrase(
			"His rebus adducti et auctoritate Orgetorigis permoti constituerunt ea quae ad proficiscendum pertinerent comparare, iumentorum et carrorum quam maximum numerum coemere, sementes quam maximas facere, ut in itinere copia frumenti suppeteret, cum proximis civitatibus pacem et amicitiam confirmare.  Ad eas res conficiendas biennium sibi satis esse duxerunt; in tertium annum profectionem lege confirmant.  Ad eas res conficiendas Orgetorix deligitur.  Is sibi legationem ad civitates suscipit.  In eo itinere persuadet Castico, Catamantaloedis filio, Sequano, cuius pater regnum in Sequanis multos annos obtinuerat et a senatu populi Romani amicus appellatus erat, ut regnum in civitate sua occuparet, quod pater ante habuerit; itemque Dumnorigi Haeduo, fratri Diviciaci, qui eo tempore principatum in civitate obtinebat ac maxime plebi acceptus erat, ut idem conaretur persuadet eique filiam suam in matrimonium dat.  Perfacile factu esse illis probat conata perficere, propterea quod ipse suae civitatis imperium obtenturus esset:  non esse dubium quin totius Galliae plurimum Helvetii possent; se suis copiis suoque exercitu illis regna conciliaturum confirmat.  Hac oratione adducti inter se fidem et ius iurandum dant et regno occupato per tres potentissimos ac firmissimos populos totius Galliae sese potiri posse sperant.\n",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));
	ct.addText(new Phrase(
			"Ea res est Helvetiis per indicium enuntiata.  Moribus suis Orgetoricem ex vinculis causam dicere coegerunt; damnatum poenam sequi oportebat, ut igni cremaretur.  Die constituta causae dictionis Orgetorix ad iudicium omnem suam familiam, ad hominum milia decem, undique coegit, et omnes clientes obaeratosque suos, quorum magnum numerum habebat, eodem conduxit; per eos ne causam diceret se eripuit.  Cum civitas ob eam rem incitata armis ius suum exequi conaretur multitudinemque hominum ex agris magistratus cogerent, Orgetorix mortuus est; neque abest suspicio, ut Helvetii arbitrantur, quin ipse sibi mortem consciverit.",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));

	float[] left1 = { 70, 790, 70, 60 };
	float[] right1 = { 300, 790, 300, 700, 240, 700, 240, 590, 300, 590, 300, 106, 270, 60 };
	float[] left2 = { 320, 790, 320, 700, 380, 700, 380, 590, 320, 590, 320, 106, 350, 60 };
	float[] right2 = { 550, 790, 550, 60 };

	int status = 0;
	int column = 0;
	while ((status & ColumnText.NO_MORE_TEXT) == 0) {
		if (column == 0) {
			ct.setColumns(left1, right1);
			column = 1;
		} else {
			ct.setColumns(left2, right2);
			column = 0;
		}
		status = ct.go();
		ct.setYLine(790);
		ct.setAlignment(Element.ALIGN_JUSTIFIED);
		status = ct.go();
		if ((column == 0) && ((status & ColumnText.NO_MORE_COLUMN) != 0)) {
			document.newPage();
			cb.addTemplate(t, 0, 0);
			cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
		}
	}

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