當前位置: 首頁>>代碼示例>>Java>>正文


Java PdfContentByte.addImage方法代碼示例

本文整理匯總了Java中com.lowagie.text.pdf.PdfContentByte.addImage方法的典型用法代碼示例。如果您正苦於以下問題:Java PdfContentByte.addImage方法的具體用法?Java PdfContentByte.addImage怎麽用?Java PdfContentByte.addImage使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.lowagie.text.pdf.PdfContentByte的用法示例。


在下文中一共展示了PdfContentByte.addImage方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: printImage

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/** Print an iText image */
private void printImage(Image image, PdfContentByte cb, float x1, float y1, float x2, float y2, int alignment, int fitMethod, float rotate)
throws DocumentException {
    if(image!=null) {
        float boxWidth = Math.abs(x2-x1)+1;
        float boxHeight = Math.abs(y2-y1)+1;
        log.debug("Print Image (Size w="+image.getPlainWidth()+",h="+image.getPlainHeight()+") wthin BOX (w="+boxWidth+",h="+boxHeight+") FitMethod = "+fitMethod);

        // Clip the image based on the bounding box
        if(fitMethod==FIT_METHOD_CLIP) {
            if( (boxWidth < image.getPlainWidth()) || (boxHeight < image.getPlainHeight()) ) {
                // @TODO - Clip image
                log.warn("IMAGE CLIPPING REQUIRED, but not implemented - default to 'SCALE'...");
                fitMethod=FIT_METHOD_SCALE;
            }
        }
        // Stretch/shrink both the X/Y to fit the bounding box
        if(fitMethod==FIT_METHOD_FILL) {
            log.debug("Scale image to fill box");
            image.scaleToFit(x2-x1, y2-y1);
        }
        // Stretch/shrink preserving the aspect ratio to fit the bounding box
        if(fitMethod==FIT_METHOD_SCALE) {
            float multipler = Math.min(boxWidth / image.getPlainWidth(), boxHeight /image.getPlainHeight());
            log.debug("Need to scale image by " + (Math.floor(multipler*10000)/100) + "%");
            image.scalePercent(multipler*100);
        }
        log.debug("Print image at (" + x1 + "," + y1 +")");
        image.setAbsolutePosition(x1,y1);
        image.setRotationDegrees(rotate);
        cb.addImage(image);
        //Phrase text = new Phrase(new Chunk(image, 0, 0));
        //ColumnText ct = new ColumnText(cb);
        //ct.setSimpleColumn(text, x1, y1, x2, y2, 10, alignment);
        //ct.go();
    }
}
 
開發者ID:jaffa-projects,項目名稱:jaffa-framework,代碼行數:38,代碼來源:FormPrintEngineIText.java

示例2: insertImage

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
private void insertImage(Image img, PdfContentByte canvas, float[] imgPosition) throws Exception {

		com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img.getBytes());

		float fieldLx = imgPosition[1];
		float fieldLy = imgPosition[2];
		float fieldUx = imgPosition[3];
		float fieldUy = imgPosition[4];
		Rectangle rect = new Rectangle(fieldLx, fieldLy, fieldUx, fieldUy);
		float absPosWidth = fieldLx;
		float absPosHeight = fieldLy;
		image.scaleToFit(rect.getWidth(), rect.getHeight());
		image.setAbsolutePosition(absPosWidth, absPosHeight);
		canvas.addImage(image, rect.getWidth(), 0, 0, rect.getHeight(), absPosWidth, absPosHeight);
	}
 
開發者ID:dvbern,項目名稱:doctemplate,代碼行數:16,代碼來源:PDFMergeEngine.java

示例3: main

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
    * 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();
   }
 
開發者ID:albfernandez,項目名稱:itext2,代碼行數:34,代碼來源:TransformImageTest.java

示例4: main

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
 * 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();
}
 
開發者ID:albfernandez,項目名稱:itext2,代碼行數:82,代碼來源:OptionalContentTest.java

示例5: main

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
 * 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();
}
 
開發者ID:albfernandez,項目名稱:itext2,代碼行數:41,代碼來源:AwtImageTest.java

示例6: main

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
 * 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();

}
 
開發者ID:albfernandez,項目名稱:itext2,代碼行數:42,代碼來源:OddEvenTest.java

示例7: addBarcode

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
public void addBarcode(String barcode, int x, int y) throws ParserException {
    try {
        Barcode128 code128 = new Barcode128();
        code128.setCode(barcode);

        PdfContentByte cb = stamp.getOverContent(1);
        Image image128 = Image.getInstance(code128.createImageWithBarcode(cb, null, null));

        cb.addImage(image128, image128.width(), 0, 0, image128.height(), x, y);
        cb.moveTo(0, 0);
    } catch (DocumentException e) {
        throw new ParserException("Could not add barcode", e);
    }
}
 
開發者ID:GovernIB,項目名稱:sistra,代碼行數:15,代碼來源:ITextParser.java

示例8: generateBarcode

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
 * Generate barcode in the form
 *
 * @param pdfStamper
 * @throws DocumentException
 */
private void generateBarcode(PdfStamper pdfStamper, String userId) throws DocumentException {

    // add barcode on the first page
    PdfContentByte cb = pdfStamper.getOverContent(BARCODE_PAGE);

    // barcode format 128C
    Barcode128 code128 = new Barcode128();

    // barcode format e.g. *1502A1234567890
    //  asterisk - * [constant]
    //  WebPOS Transaction - 1502 [constant]
    //  Form Version - A [constant for MyPost 1.5]
    //  10-digit APCN
    code128.setCode(ASTERISK + WEBPOS_TRANSACTIION + MYPOST_FORM_VERSION + userId);

    code128.setCodeType(Barcode128.CODE128);

    // convert barcode into image
    Image code128Image = code128.createImageWithBarcode(cb, null, null);

    // set barcode position x pixel, y pixel
    code128Image.setAbsolutePosition(BARCODE_POSITION_X, BARCODE_POSITION_Y);
    code128Image.scalePercent(BARCODE_SCALE_PERCENTAGE);

    // add barcode image into PDF template
    cb.addImage(code128Image);
}
 
開發者ID:TerrenceMiao,項目名稱:camel-spring,代碼行數:34,代碼來源:PdfController.java

示例9: generateQRCode

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
 * Generate a QR code including URL on the page
 * 
 * @param pdfStamper
 * @throws DocumentException
 */
private void generateQRCode(PdfStamper pdfStamper) throws DocumentException {

    // add barcode on the first page
    PdfContentByte pdfContentByte = pdfStamper.getOverContent(APPENDED_PAGE);

    BarcodeQRCode qrcode = new BarcodeQRCode("http://www.vendian.org/mncharity/dir3/paper_rulers/", 200, 200, null);
    Image qrcodeImage = qrcode.getImage();
    qrcodeImage.setAbsolutePosition(360,500);
    qrcodeImage.scalePercent(100);
    pdfContentByte.addImage(qrcodeImage);
}
 
開發者ID:TerrenceMiao,項目名稱:camel-spring,代碼行數:18,代碼來源:PdfController.java

示例10: main

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
    * 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();
   }
 
開發者ID:albfernandez,項目名稱:itext2,代碼行數:52,代碼來源:AddWatermarkPageNumbersTest.java

示例11: onEndPage

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
 * @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();
}
 
開發者ID:albfernandez,項目名稱:itext2,代碼行數:57,代碼來源:PageNumbersWatermarkTest.java

示例12: main

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
 * 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();
}
 
開發者ID:albfernandez,項目名稱:itext2,代碼行數:38,代碼來源:SoftMaskTest.java

示例13: main

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
    * 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();
       }
   }
 
開發者ID:albfernandez,項目名稱:itext2,代碼行數:63,代碼來源:ImageMasksTest.java

示例14: main

import com.lowagie.text.pdf.PdfContentByte; //導入方法依賴的package包/類
/**
 * 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();
}
 
開發者ID:albfernandez,項目名稱:itext2,代碼行數:81,代碼來源:ColumnIrregularTest.java


注:本文中的com.lowagie.text.pdf.PdfContentByte.addImage方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。