Java Code Examples for com.lowagie.text.pdf.PdfWriter#getDirectContent()

The following examples show how to use com.lowagie.text.pdf.PdfWriter#getDirectContent() . 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: 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 2
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 3
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 4
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 5
Source File: ShadingTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void main() throws Exception {

	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	PdfWriter writer = PdfWriter.getInstance(document,	PdfTestBase.getOutputStream( "shading.pdf"));
	document.open();

	PdfFunction function1 = PdfFunction.type2(writer, new float[] { 0, 1 },
			null, new float[] { .929f, .357f, 1, .298f }, new float[] {
					.631f, .278f, 1, .027f }, 1.048f);
	PdfFunction function2 = PdfFunction.type2(writer, new float[] { 0, 1 },
			null, new float[] { .929f, .357f, 1, .298f }, new float[] {
					.941f, .4f, 1, .102f }, 1.374f);
	PdfFunction function3 = PdfFunction.type3(writer, new float[] { 0, 1 },
			null, new PdfFunction[] { function1, function2 },
			new float[] { .708f }, new float[] { 1, 0, 0, 1 });
	PdfShading shading = PdfShading.type3(writer,
			new CMYKColor(0, 0, 0, 0),
			new float[] { 0, 0, .096f, 0, 0, 1 }, null, function3,
			new boolean[] { true, true });
	PdfContentByte cb = writer.getDirectContent();
	cb.moveTo(316.789f, 140.311f);
	cb.curveTo(303.222f, 146.388f, 282.966f, 136.518f, 279.122f, 121.983f);
	cb.lineTo(277.322f, 120.182f);
	cb.curveTo(285.125f, 122.688f, 291.441f, 121.716f, 298.156f, 119.386f);
	cb.lineTo(336.448f, 119.386f);
	cb.curveTo(331.072f, 128.643f, 323.346f, 137.376f, 316.789f, 140.311f);
	cb.clip();
	cb.newPath();
	cb.saveState();
	cb.concatCTM(27.7843f, 0, 0, -27.7843f, 310.2461f, 121.1521f);
	cb.paintShading(shading);
	cb.restoreState();

	cb.sanityCheck();

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

}
 
Example 7
Source File: PdfDocumentFactory.java    From javamelody with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
	cb = writer.getDirectContent();
	template = cb.createTemplate(50, 50);
}
 
Example 8
Source File: PaperightPdfConverter.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
private String createA5(String originalPdfFile) throws IOException, DocumentException {
	logger.debug("Started create A5 file from " + originalPdfFile);
	String filename = FilenameUtils.getBaseName(originalPdfFile) + "_a5." + FilenameUtils.getExtension(originalPdfFile);
	String tempFilename =  FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename + ".tmp");
	filename = FilenameUtils.concat(getPdfFileFolder(), filename);
	File tempFile = new File(tempFilename);
	//float scale = 0.72906403940886699507389162561576f;
	PdfReader reader = new PdfReader(originalPdfFile);
	
	//new RectangleReadOnly(425.16f, 606.96f)
	Document doc = new Document(PageSize.A5, 0, 0, 0, 0);
	PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile));
	doc.open();
	for (int i = 1; i <= reader.getNumberOfPages(); i++) {
		doc.newPage();
		PdfContentByte cb = writer.getDirectContent();
		PdfImportedPage page = writer.getImportedPage(reader, i); // page #1
		
		float documentWidth = doc.getPageSize().getWidth();
		float documentHeight = doc.getPageSize().getHeight();
		if (i > 1) {
			documentHeight = documentHeight - 65f;
		}
		//float documentHeight = doc.getPageSize().getHeight() - 65f;

		float pageWidth = page.getWidth();
		float pageHeight = page.getHeight();
		
		float widthScale = documentWidth / pageWidth;
		float heightScale = documentHeight / pageHeight;
		float scale = Math.min(widthScale, heightScale);
		
		//float offsetX = 50f;
		float offsetX = (documentWidth - (pageWidth * scale)) / 2;
		float offsetY = 0f;
		if (i > 1) {
			offsetY = 65f;
		}
		//float offsetY = ((documentHeight) - (pageHeight * scale)) / 2;
		
		cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY);
		//cb.addTemplate(page, scale, 0, 0, scale, 50f, 100f);
	}
	doc.close();
	//FileUtils.moveFile(tempFile, new File(filename));
	overlayLicenceArea(tempFilename, filename, PageLayout.A5);
	logger.debug("Deleting temporary file " + tempFile.getAbsolutePath());
	FileUtils.deleteQuietly(tempFile);
	logger.debug("Completed create A5 file from " + originalPdfFile);
	return filename;
}
 
Example 9
Source File: NestedLayersTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Demonstrates the use of nested layers
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {
	// step 1
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	// step 2
	PdfWriter writer = PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("nestedlayers.pdf"));
	writer.setPdfVersion(PdfWriter.VERSION_1_5);
	writer.setViewerPreferences(PdfWriter.PageModeUseOC);
	// step 3
	document.open();
	// step 4
	PdfContentByte cb = writer.getDirectContent();
	Phrase explanation = new Phrase("Layer nesting", new Font(
			Font.HELVETICA, 20, Font.BOLD, Color.red));
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50,
			650, 0);
	PdfLayer l1 = new PdfLayer("Layer 1", writer);
	PdfLayer l23 = new PdfLayer("Top Layer 2 3", writer);
	PdfLayer l2 = new PdfLayer("Layer 2", writer);
	PdfLayer l3 = new PdfLayer("Layer 3", writer);
	Phrase p1 = new Phrase("Text in layer 1");
	Phrase p2 = new Phrase("Text in layer 2");
	Phrase p3 = new Phrase("Text in layer 3");
	cb.beginLayer(l1);
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0);
	cb.endLayer();
	cb.beginLayer(l23);
	cb.beginLayer(l2);
	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();
	cb.endLayer();
	cb.sanityCheck();

	PdfOCProperties p = writer.getOCProperties();
	PdfArray order = new PdfArray();
	order.add(l1.getRef());
	order.add(l23.getRef());
	PdfArray group = new PdfArray();
	group.add(l2.getRef());
	group.add(l3.getRef());
	order.add(group);
	PdfDictionary d = new PdfDictionary();
	d.put(PdfName.ORDER, order);
	p.put(PdfName.D, d);
	// step 5
	document.close();
}
 
Example 10
Source File: LayersTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Draws different things into different layers.
 */
@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("layers.pdf"));

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

	// step 4:

	// high level
	Paragraph p = new Paragraph();
	for (int i = 0; i < 100; i++)
		p.add(new Chunk("Blah blah blah blah blah. "));
	document.add(p);
	Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR
			+ "hitchcock.png");
	img.setAbsolutePosition(100, 500);
	document.add(img);

	// low level
	PdfContentByte cb = writer.getDirectContent();
	PdfContentByte cbu = writer.getDirectContentUnder();
	cb.setRGBColorFill(0xFF, 0xFF, 0xFF);
	cb.circle(250.0f, 500.0f, 50.0f);
	cb.fill();
	cb.sanityCheck();

	cbu.setRGBColorFill(0xFF, 0x00, 0x00);
	cbu.circle(250.0f, 500.0f, 100.0f);
	cbu.fill();
	cbu.sanityCheck();

	// step 5: we close the document
	document.close();
}
 
Example 11
Source File: AffineTransformationTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Changes the transformation matrix with AffineTransform.
 */
@Test
public void main() throws Exception {

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

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

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

	// step 4:
	PdfContentByte cb = writer.getDirectContent();
	cb.transform(AffineTransform.getScaleInstance(1.2, 0.75));

	// we create a PdfTemplate
	PdfTemplate template = cb.createTemplate(25, 25);

	// we add some crosses to visualize the coordinates
	template.moveTo(13, 0);
	template.lineTo(13, 25);
	template.moveTo(0, 13);
	template.lineTo(50, 13);
	template.stroke();
	template.sanityCheck();

	// we add the template on different positions
	cb.addTemplate(template, 216 - 13, 720 - 13);
	cb.addTemplate(template, 360 - 13, 360 - 13);
	cb.addTemplate(template, 360 - 13, 504 - 13);
	cb.addTemplate(template, 72 - 13, 144 - 13);
	cb.addTemplate(template, 144 - 13, 288 - 13);

	cb.moveTo(216, 720);
	cb.lineTo(360, 360);
	cb.lineTo(360, 504);
	cb.lineTo(72, 144);
	cb.lineTo(144, 288);
	cb.stroke();

	BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
			BaseFont.NOT_EMBEDDED);
	cb.beginText();
	cb.setFontAndSize(bf, 12);
	cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
			"(3\" * 1.2, 10\" * .75)", 216 + 25, 720 + 5, 0);
	cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
			"(5\" * 1.2, 5\" * .75)", 360 + 25, 360 + 5, 0);
	cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
			"(5\" * 1.2, 7\" * .75)", 360 + 25, 504 + 5, 0);
	cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
			"(1\" * 1.2, 2\" * .75)", 72 + 25, 144 + 5, 0);
	cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
			"(2\" * 1.2, 4\" * .75)", 144 + 25, 288 + 5, 0);
	cb.endText();

	cb.sanityCheck();

	// step 5: we close the document
	document.close();
}
 
Example 12
Source File: UpsideDownTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
    * Changes the default coordinate system so that the origin is in the upper left corner
    * instead of the lower left corner.
    */
@Test
public void main() throws Exception {
       
       // 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( "upsidedown.pdf"));
           
           // step 3: we open the document
           document.open();
           
           // step 4:
           PdfContentByte cb = writer.getDirectContent();
           cb.concatCTM(1f, 0f, 0f, -1f, 0f, PageSize.A4.getHeight());
           
           // we create a PdfTemplate
           PdfTemplate template = cb.createTemplate(25, 25);
           
           // we add some crosses to visualize the coordinates
           template.moveTo(13, 0);
           template.lineTo(13, 25);
           template.moveTo(0, 13);
           template.lineTo(50, 13);
           template.stroke();
           template.sanityCheck();
           
           // we add the template on different positions
           cb.addTemplate(template, 216 - 13, 720 - 13);
           cb.addTemplate(template, 360 - 13, 360 - 13);
           cb.addTemplate(template, 360 - 13, 504 - 13);
           cb.addTemplate(template, 72 - 13, 144 - 13);
           cb.addTemplate(template, 144 - 13, 288 - 13);

           cb.moveTo(216, 720);
           cb.lineTo(360, 360);
           cb.lineTo(360, 504);
           cb.lineTo(72, 144);
           cb.lineTo(144, 288);
           cb.stroke();
           
           BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
           cb.beginText();
           cb.setFontAndSize(bf, 12);
           cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(3\", 10\")", 216 + 25, 720 + 5, 0);
           cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(5\", 5\")", 360 + 25, 360 + 5, 0);
           cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(5\", 7\")", 360 + 25, 504 + 5, 0);
           cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(1\", 2\")", 72 + 25, 144 + 5, 0);
           cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(2\", 4\")", 144 + 25, 288 + 5, 0);
           cb.endText();
           
           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 13
Source File: FormRadioButtonTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Generates an Acroform with a RadioButton
 */
@Test
public void main() throws Exception {

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

	// step 2:
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("radiobutton.pdf"));

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

	// step 4:
	PdfContentByte cb = writer.getDirectContent();
	cb.moveTo(0, 0);
	PdfFormField radio = PdfFormField.createRadioButton(writer, true);
	PdfAppearance tpOff = cb.createAppearance(20, 20);
	PdfAppearance tpOn = cb.createAppearance(20, 20);

	tpOff.circle(10, 10, 9);
	tpOff.stroke();

	tpOn.circle(10, 10, 9);
	tpOn.stroke();
	tpOn.circle(10, 10, 3);
	tpOn.fillStroke();

	radio.setFieldName("CreditCard");
	radio.setValueAsName("MasterCard");

	PdfFormField radio1 = PdfFormField.createEmpty(writer);
	radio1.setWidget(new Rectangle(100, 700, 120, 720), PdfAnnotation.HIGHLIGHT_INVERT);
	radio1.setAppearanceState("MasterCard");
	radio1.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", tpOff);
	radio1.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "MasterCard", tpOn);
	radio.addKid(radio1);

	PdfFormField radio2 = PdfFormField.createEmpty(writer);
	radio2.setWidget(new Rectangle(100, 660, 120, 680), PdfAnnotation.HIGHLIGHT_INVERT);
	radio2.setAppearanceState("Off");
	radio2.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", tpOff);
	radio2.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Visa", tpOn);
	radio.addKid(radio2);

	PdfFormField radio3 = PdfFormField.createEmpty(writer);
	radio3.setWidget(new Rectangle(100, 620, 120, 640), PdfAnnotation.HIGHLIGHT_INVERT);
	radio3.setAppearanceState("Off");
	radio3.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", tpOff);
	radio3.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "American", tpOn);
	radio.addKid(radio3);

	writer.addAnnotation(radio);

	// step 5: we close the document
	document.close();
}
 
Example 14
Source File: AutomaticTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Automatic grouping and nesting.
 */
@Test
public void main() throws Exception {
	// step 1
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	// step 2
	PdfWriter writer = PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("automatic.pdf"));
	writer.setPdfVersion(PdfWriter.VERSION_1_5);
	writer.setViewerPreferences(PdfWriter.PageModeUseOC);
	// step 3
	document.open();
	// step 4
	PdfContentByte cb = writer.getDirectContent();
	Phrase explanation = new Phrase("Automatic layer grouping and nesting",
			new Font(Font.HELVETICA, 20, Font.BOLD, Color.red));
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50,
			650, 0);
	PdfLayer l12 = new PdfLayer("Layer nesting", writer);
	PdfLayer l1 = new PdfLayer("Layer 1", writer);
	PdfLayer l2 = new PdfLayer("Layer 2", writer);
	PdfLayer title = PdfLayer.createTitle("Layer grouping", writer);
	PdfLayer l3 = new PdfLayer("Layer 3", writer);
	PdfLayer l4 = new PdfLayer("Layer 4", writer);
	l12.addChild(l1);
	l12.addChild(l2);
	title.addChild(l3);
	title.addChild(l4);
	Phrase p1 = new Phrase("Text in layer 1");
	Phrase p2 = new Phrase("Text in layer 2");
	Phrase p3 = new Phrase("Text in layer 3");
	Phrase p4 = new Phrase("Text in layer 4");
	cb.beginLayer(l1);
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0);
	cb.endLayer();
	cb.beginLayer(l2);
	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();
	cb.beginLayer(l4);
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p4, 50, 450, 0);
	cb.endLayer();
	cb.sanityCheck();

	// step 5
	document.close();
}
 
Example 15
Source File: GroupsTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Demonstrates the Transparency functionality.
 */
@Test
public void main() {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    try {
        // step 2: creation of a writer 
        PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("groups.pdf"));
        // step 3: we open the document
        document.open();
        // step 4: content
        PdfContentByte cb = writer.getDirectContent();
        float gap = (document.getPageSize().getWidth() - 400) / 3;
        
        pictureBackdrop(gap, 500, cb);
        pictureBackdrop(200 + 2 * gap, 500, cb);
        pictureBackdrop(gap, 500 - 200 - gap, cb);
        pictureBackdrop(200 + 2 * gap, 500 - 200 - gap, cb);

        PdfTemplate tp;
        PdfTransparencyGroup group;
        
        tp = cb.createTemplate(200, 200);
        pictureCircles(0, 0, tp);
        group = new PdfTransparencyGroup();
        group.setIsolated(true);
        group.setKnockout(true);
        tp.setGroup(group);
        tp.sanityCheck();
        cb.addTemplate(tp, gap, 500);

        
        tp = cb.createTemplate(200, 200);
        pictureCircles(0, 0, tp);
        group = new PdfTransparencyGroup();
        group.setIsolated(true);
        group.setKnockout(false);
        tp.setGroup(group);
        tp.sanityCheck();
        cb.addTemplate(tp, 200 + 2 * gap, 500);

        
        tp = cb.createTemplate(200, 200);
        pictureCircles(0, 0, tp);
        group = new PdfTransparencyGroup();
        group.setIsolated(false);
        group.setKnockout(true);
        tp.setGroup(group);
        tp.sanityCheck();
        cb.addTemplate(tp, gap, 500 - 200 - gap);

        
        tp = cb.createTemplate(200, 200);
        pictureCircles(0, 0, tp);
        group = new PdfTransparencyGroup();
        group.setIsolated(false);
        group.setKnockout(false);
        tp.setGroup(group);
        tp.sanityCheck();
        cb.addTemplate(tp, 200 + 2 * gap, 500 - 200 - gap);

        cb.sanityCheck();
    }
    catch (Exception de) {
        de.printStackTrace();
    }
    // step 5: we close the document
    document.close();
}
 
Example 16
Source File: ColumnTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Demonstrating 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("column.pdf"));

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

	// step 4:

	// we create some content
	BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
	Font font = new Font(bf, 11, Font.NORMAL);

	Phrase unicodes = new Phrase(15, "UNI\n", font);
	Phrase characters = new Phrase(15, "\n", font);
	Phrase names = new Phrase(15, "NAME\n", font);

	for (int i = 0; i < 27; i++) {
		unicodes.add(uni[i] + "\n");
		characters.add(code[i] + "\n");
		names.add(name[i] + "\n");
	}

	// we grab the ContentByte and do some stuff with it
	PdfContentByte cb = writer.getDirectContent();

	ColumnText ct = new ColumnText(cb);
	ct.setSimpleColumn(unicodes, 60, 300, 100, 300 + 28 * 15, 15, Element.ALIGN_CENTER);
	ct.go();
	cb.rectangle(103, 295, 52, 8 + 28 * 15);
	cb.stroke();
	ct.setSimpleColumn(characters, 105, 300, 150, 300 + 28 * 15, 15, Element.ALIGN_RIGHT);
	ct.go();
	ct.setSimpleColumn(names, 160, 300, 500, 300 + 28 * 15, 15, Element.ALIGN_LEFT);
	ct.go();

	// step 5: we close the document
	document.close();
}
 
Example 17
Source File: LiteralTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void main() throws Exception {
       
       Document.compress = false;
       
       // step 1: creation of a document-object
       Document document = new Document();
       
       try {
           
           // 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( "literal.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();
           String star = "0.3 g\n15.000 27.000 m\n"
               + "7.947 5.292 l\n26.413 18.708 l\n"
               + "3.587 18.708 l\n22.053 5.292 l\nf\n"
               + "45.000 57.000 m\n37.947 35.292 l\n"
               + "56.413 48.708 l\n33.587 48.708 l\n"
               + "52.053 35.292 l\nf\n"
               + "0.7 g\n15.000 57.000 m\n"
               + "7.947 35.292 l\n26.413 48.708 l\n"
               + "3.587 48.708 l\n22.053 35.292 l\nf\n"
               + "45.000 27.000 m\n37.947 5.292 l\n"
               + "56.413 18.708 l\n33.587 18.708 l\n"
               + "52.053 5.292 l\nf";
           cb.setLiteral(star);
           
           // sanityCheck doesn't check literals.
           //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 18
Source File: TemplatesTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
   
    */
@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("templates.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();

	// we create a PdfTemplate
	PdfTemplate template = cb.createTemplate(500, 200);

	// we add some graphics
	template.moveTo(0, 200);
	template.lineTo(500, 0);
	template.stroke();
	template.setRGBColorStrokeF(255f, 0f, 0f);
	template.circle(250f, 100f, 80f);
	template.stroke();

	// we add some text
	template.beginText();
	BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
			BaseFont.NOT_EMBEDDED);
	template.setFontAndSize(bf, 12);
	template.setTextMatrix(100, 100);
	template.showText("Text at the position 100,100 (relative to the template!)");
	template.endText();
	template.sanityCheck();

	// we add the template on different positions
	cb.addTemplate(template, 0, 0);
	cb.addTemplate(template, 0, 1, -1, 0, 500, 200);
	cb.addTemplate(template, .5f, 0, 0, .5f, 100, 400);

	// we go to a new page
	document.newPage();
	cb.addTemplate(template, 0, 400);
	cb.addTemplate(template, 2, 0, 0, 2, -200, 400);
	cb.sanityCheck();

	// step 5: we close the document
	document.close();
}
 
Example 19
Source File: PaperightPdfConverter.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
private String createOneUp(String originalPdfFile) throws IOException, DocumentException {
	logger.debug("Started create 1-up file from " + originalPdfFile);
	String filename = FilenameUtils.getBaseName(originalPdfFile) + "_1up." + FilenameUtils.getExtension(originalPdfFile);
	String tempFilename =  FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename + ".tmp");
	filename = FilenameUtils.concat(getPdfFileFolder(), filename);
	File tempFile = new File(tempFilename);
	//float scale = 0.80f;
	PdfReader reader = new PdfReader(originalPdfFile);
	Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
	//Document doc = new Document(new RectangleReadOnly(606.96f, 850.32f), 0, 0, 0, 0);
	PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile));
	doc.open();
	for (int i = 1; i <= reader.getNumberOfPages(); i++) {
		doc.newPage();
		PdfContentByte cb = writer.getDirectContent();
		PdfImportedPage page = writer.getImportedPage(reader, i);
		
		
		float documentWidth = doc.getPageSize().getWidth();
		float documentHeight = doc.getPageSize().getHeight();
		if (i > 1) {
			documentHeight = documentHeight - 65f;
		}
		
		
		/*float documentHeight = doc.getPageSize().getHeight();
		if (i > 1) {
			documentHeight = documentHeight - 65f;
		}
		float documentWidth = doc.getPageSize().getWidth();*/

		float pageWidth = page.getWidth();
		float pageHeight = page.getHeight();
		
		float widthScale = documentWidth / pageWidth;
		float heightScale = documentHeight / pageHeight;
		float scale = Math.min(widthScale, heightScale);
		
		float offsetX = (documentWidth - (pageWidth * scale)) / 2;
		float offsetY = 0f;
		if (i > 1) {
			offsetY = 65f;
		}
		/*
		
		float offsetX = 0f;
		if (i > 1) {
			offsetX = 65f; //100f
		}
		//float offsetX = 65f;
		float offsetY = ((documentHeight) - (pageHeight * scale)) / 2;*/
		
		cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY);

	}
	doc.close();
	overlayLicenceArea(tempFilename, filename, PageLayout.ONE_UP);
	logger.debug("Deleting temporary file " + tempFile.getAbsolutePath());
	FileUtils.deleteQuietly(tempFile);
	logger.debug("Completed create 1-up file from " + originalPdfFile);
	return filename;
}
 
Example 20
Source File: VisualizePanelCharts2D.java    From KEEL with GNU General Public License v3.0 4 votes vote down vote up
private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed
    // Save chart as a PDF file
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("pdf");
    fileFilter.setFilterName("PDF images (.pdf)");
    chooser.setFileFilter(fileFilter);
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".pdf")) {
            // Add correct extension
            nombre += ".pdf";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this, "File " + nombre + " already exists. Do you want to replace it?",
                "Confirm", JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(nombre));
                document.addAuthor("KEEL");
                document.addSubject("Attribute comparison");
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(550, 412);
                Graphics2D g2 = tp.createGraphics(550, 412,
                        new DefaultFontMapper());
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412);
                chart2.setBackgroundPaint(Color.white);
                chart2.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 20, 350);
                document.close();
            } catch (Exception exc) {
            }
        }
    }
}