com.lowagie.text.PageSize Java Examples

The following examples show how to use com.lowagie.text.PageSize. 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: SpaceWordRatioTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Space Word Ratio.
 */
@Test
public void main() throws Exception {
	// step 1
	Document document = new Document(PageSize.A4, 50, 350, 50, 50);
	// step 2
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("spacewordratio.pdf"));
	// step 3
	document.open();
	// step 4
	String text = "Flanders International Filmfestival Ghent - Internationaal Filmfestival van Vlaanderen Gent";
	Paragraph p = new Paragraph(text);
	p.setAlignment(Element.ALIGN_JUSTIFIED);
	document.add(p);
	document.newPage();
	writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
	document.add(p);

	// step 5
	document.close();
}
 
Example #3
Source File: AcroFieldsTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
    * This test fails, because signatureCoversWholeDocument does only check the
    * last signed block.
    */
   @Test
public void testGetSignatures() throws Exception {
	// for algorithm SHA256 (without dash)
	Security.addProvider(new BouncyCastleProvider());
	InputStream moddedFile = AcroFieldsTest.class.getResourceAsStream("/siwa.pdf");
	PdfReader reader = new PdfReader(moddedFile);
	Document document = new Document(PageSize.A4);
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	PdfWriter writer = PdfWriter.getInstance(document, out);

	AcroFields fields = new AcroFields(reader, writer);
	@SuppressWarnings("unchecked")
	ArrayList<String> names = fields.getSignatureNames();
	Assert.assertEquals(1, names.size());

	for (String signName : names) {
		Assert.assertFalse(fields.signatureCoversWholeDocument(signName));
		PdfPKCS7 pdfPkcs7 = fields.verifySignature(signName, "BC");
		Assert.assertTrue(pdfPkcs7.verify());
	}

}
 
Example #4
Source File: FixedFontWidthTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Changing the width of font glyphs.
 * 
 * @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.getInstance(document, PdfTestBase.getOutputStream("fixedfontwidth.pdf"));
	// step 3
	document.open();
	// step 4
	BaseFont bf = BaseFont.createFont("Helvetica", "winansi", false, false, null, null);
	int widths[] = bf.getWidths();
	for (int k = 0; k < widths.length; ++k) {
		if (widths[k] != 0)
			widths[k] = 1000;
	}
	bf.setForceWidthsOutput(true);
	document.add(new Paragraph("A big text to show Helvetica with fixed width.", new Font(bf)));
	// step 5
	document.close();
}
 
Example #5
Source File: PageNumbersWatermarkTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
    * Generates a document with a header containing Page x of y and with a Watermark on every page.
    */
@Test
public void main() throws Exception {
       	// step 1: creating the document
           Document doc = new Document(PageSize.A4, 50, 50, 100, 72);
           // step 2: creating the writer
           PdfWriter writer = PdfWriter.getInstance(doc, PdfTestBase.getOutputStream( "pageNumbersWatermark.pdf"));
           // step 3: initialisations + opening the document
           writer.setPageEvent(new PageNumbersWatermarkTest());
           doc.open();
           // step 4: adding content
           String text = "some padding text ";
           for (int k = 0; k < 10; ++k) {
               text += text;
           }
           Paragraph p = new Paragraph(text);
           p.setAlignment(Element.ALIGN_JUSTIFIED);
           doc.add(p);
           // step 5: closing the document
           doc.close();
       
   }
 
Example #6
Source File: OpenTypeFontTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Using oth
 */
@Test
public void main() throws Exception {
	// step 1
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	// step 2
	PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("opentypefont.pdf"));
	// step 3
	document.open();
	// step 4
	BaseFont bf = BaseFont.createFont(PdfTestBase.RESOURCES_DIR
			+ "liz.otf", BaseFont.CP1252, true);
	String text = "Some text with the otf font LIZ.";
	document.add(new Paragraph(text, new Font(bf, 14)));
	// step 5
	document.close();
}
 
Example #7
Source File: FormComboTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates an Acroform with a Combobox
 */
@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("combo.pdf"));

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

	// step 4:
	PdfContentByte cb = writer.getDirectContent();
	cb.moveTo(0, 0);
	String options[] = { "Red", "Green", "Blue" };
	PdfFormField field = PdfFormField.createCombo(writer, true, options, 0);
	field.setWidget(new Rectangle(100, 700, 180, 720), PdfAnnotation.HIGHLIGHT_INVERT);
	field.setFieldName("ACombo");
	field.setValueAsString("Red");
	writer.addAnnotation(field);

	// step 5: we close the document
	document.close();
}
 
Example #8
Source File: FormSignatureTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates an Acroform with a Signature
 */
@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("signature.pdf"));

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

	// step 4:
	PdfAcroForm acroForm = writer.getAcroForm();
	document.add(new Paragraph("Hello World"));
	acroForm.addSignature("mysig", 73, 705, 149, 759);

	// step 5: we close the document
	document.close();
}
 
Example #9
Source File: AccountSummaryController.java    From primefaces-blueprints with The Unlicense 6 votes vote down vote up
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {  
    Document pdf = (Document) document;  
    pdf.setPageSize(PageSize.A3);
    pdf.open(); 
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();  
    String logo = servletContext.getRealPath("") + File.separator +"resources" + File.separator + "images" + File.separator +"logo" + File.separator + "logo.png";  
    Image image=Image.getInstance(logo);
    image.scaleAbsolute(100f, 50f);
    pdf.add(image); 
    // add a couple of blank lines
       pdf.add( Chunk.NEWLINE );
       pdf.add( Chunk.NEWLINE );
    Font fontbold = FontFactory.getFont("Times-Roman", 16, Font.BOLD);
    fontbold.setColor(55, 55, 55);;
    pdf.add(new Paragraph("Account Summary",fontbold));
    // add a couple of blank lines
    pdf.add( Chunk.NEWLINE );
    pdf.add( Chunk.NEWLINE );
}
 
Example #10
Source File: ArabicTextTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Draws arabic text using java.awt.Graphics2D.
    */
@Test
public void main() throws Exception {
   	// step 1
       Document document = new Document(PageSize.A4, 50, 50, 50, 50);
       try {
       	// step 2
           PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "arabictext.pdf"));
           // step 3
           document.open();
           // step 4
           String text1 = "This text has \u0634\u0627\u062f\u062c\u0645\u0647\u0648\u0631 123,456 \u0645\u0646 (Arabic)";
           java.awt.Font font = new java.awt.Font("arial", 0, 18);
           PdfContentByte cb = writer.getDirectContent();
           java.awt.Graphics2D g2 = cb.createGraphicsShapes(PageSize.A4.getWidth(), PageSize.A4.getHeight());
           g2.setFont(font);
           g2.drawString(text1, 100, 100);
           g2.dispose();
           cb.sanityCheck();
           // step 5
           document.close();
       }
       catch (Exception de) {
           de.printStackTrace();
       }
   }
 
Example #11
Source File: InvestmentSummaryController.java    From primefaces-blueprints with The Unlicense 6 votes vote down vote up
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {  
    Document pdf = (Document) document; 
    pdf.setPageSize(PageSize.A3); 
    pdf.open();  
     
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();  
    String logo = servletContext.getRealPath("") + File.separator +"resources" + File.separator + "images" + File.separator +"logo" + File.separator + "logo.png";  
    Image image=Image.getInstance(logo);
    image.scaleAbsolute(100f, 50f);
    pdf.add(image); 
    // add a couple of blank lines
       pdf.add( Chunk.NEWLINE );
       pdf.add( Chunk.NEWLINE );
    Font fontbold = FontFactory.getFont("Times-Roman", 16, Font.BOLD);
    fontbold.setColor(55, 55, 55);;
    pdf.add(new Paragraph("Investment Summary",fontbold));
    // add a couple of blank lines
    pdf.add( Chunk.NEWLINE );
    pdf.add( Chunk.NEWLINE );
}
 
Example #12
Source File: OpenApplicationTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a document with Named Actions.
 * 
 * @param args The file to open
 */
public void main(String... args) 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("OpenApplication.pdf"));
	// step 3: we open the document
	document.open();
	// step 4: we add some content
	String application = args[0];
	Paragraph p = new Paragraph(new Chunk("Click to open " + application).setAction(
			new PdfAction(application, null, null, null)));
	document.add(p);

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

}
 
Example #13
Source File: PdfInstructionalOfferingTableBuilder.java    From unitime with Apache License 2.0 6 votes vote down vote up
public void pdfTableForInstructionalOfferings(
  		OutputStream out,
          ClassAssignmentProxy classAssignment,
          ExamAssignmentProxy examAssignment,
          InstructionalOfferingListForm form, 
          String[] subjectAreaIds, 
          SessionContext context,
          boolean displayHeader,
          boolean allCoursesAreGiven) throws Exception{
  	
  	setVisibleColumns(form);
  	
  	iDocument = new Document(PageSize.A4, 30f, 30f, 30f, 30f); 
iWriter = PdfEventHandler.initFooter(iDocument, out);

  	for (String subjectAreaId: subjectAreaIds) {
      	pdfTableForInstructionalOfferings(out, classAssignment, examAssignment,
      			form.getInstructionalOfferings(Long.valueOf(subjectAreaId)), 
      			Long.valueOf(subjectAreaId),
      			context,
      			displayHeader, allCoursesAreGiven,
      			new ClassCourseComparator(form.getSortBy(), classAssignment, false));
  	}
 	
iDocument.close();
  }
 
Example #14
Source File: DocExportUtil.java    From DWSurvey with GNU Affero General Public License v3.0 6 votes vote down vote up
public void createDoc() throws FileNotFoundException{
	 /** 创建Document对象(word文档)  */
       Rectangle rectPageSize = new Rectangle(PageSize.A4);
       rectPageSize = rectPageSize.rotate();
       // 创建word文档,并设置纸张的大小
       doc = new Document(PageSize.A4);
       file=new File(path+docFileName);
       fileOutputStream=new FileOutputStream(file);
       /** 建立一个书写器与document对象关联,通过书写器可以将文档写入到输出流中 */
       RtfWriter2.getInstance(doc, fileOutputStream );
       doc.open();
       //设置页边距,上、下25.4毫米,即为72f,左、右31.8毫米,即为90f  
       doc.setMargins(90f, 90f, 72f, 72f);
       //设置标题字体样式,粗体、二号、华文中宋  
       tfont  = DocStyleUtils.setFontStyle("华文中宋", 22f, Font.BOLD);  
       //设置正文内容的字体样式,常规、三号、仿宋_GB2312  
       bfont = DocStyleUtils.setFontStyle("仿宋_GB2312", 16f, Font.NORMAL);
}
 
Example #15
Source File: AnnotatedImageTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Adds some annotated images to a PDF file.
 */
@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("annotated_images.pdf"));
	// step 3: we open the document
	document.open();
	// step 4: we add some content
	Image jpeg = Image.getInstance(PdfTestBase.RESOURCES_DIR + "otsoe.jpg");
	jpeg.setAnnotation(new Annotation("picture", "This is my dog", 0, 0, 0, 0));
	jpeg.setAbsolutePosition(100f, 550f);
	document.add(jpeg);
	Image wmf = Image.getInstance(PdfTestBase.RESOURCES_DIR + "iText.wmf");
	wmf.setAnnotation(new Annotation(0, 0, 0, 0, "http://www.lowagie.com/iText"));
	wmf.setAbsolutePosition(100f, 200f);
	document.add(wmf);

	// step 5: we close the document
	document.close();
}
 
Example #16
Source File: PdfExamGridTable.java    From unitime with Apache License 2.0 6 votes vote down vote up
public void export(OutputStream out) throws Exception {
    int nrCols = getNrColumns();
    iDocument = (iForm.getDispMode()==sDispModeInRowHorizontal || iForm.getDispMode()==sDispModeInRowVertical ?
        new Document(new Rectangle(Math.max(PageSize.LETTER.getWidth(),60.0f+100.0f*nrCols),Math.max(PageSize.LETTER.getHeight(),60.0f+150f*nrCols)).rotate(), 30, 30, 30, 30)
    :
        new Document(new Rectangle(Math.max(PageSize.LETTER.getWidth(),60.0f+100.0f*nrCols),Math.max(PageSize.LETTER.getHeight(),60.0f+150f*nrCols)), 30, 30, 30, 30));

    PdfEventHandler.initFooter(iDocument, out);
    iDocument.open();
    
    printTable();

    printLegend();

    iDocument.close();
}
 
Example #17
Source File: LandscapePortraitTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a PDF document with pages in portrait/landscape.
 */
@Test
public void main() throws Exception {

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

	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file

	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("LandscapePortrait.pdf"));

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

	// step 4: we add some content
	document.add(new Paragraph(
			"To create a document in landscape format, just make the height smaller than the width. For instance by rotating the PageSize Rectangle: PageSize.A4.rotate()"));
	document.setPageSize(PageSize.A4);
	document.newPage();
	document.add(new Paragraph("This is portrait again"));

	// step 5: we close the document
	document.close();
}
 
Example #18
Source File: BookmarksTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a document with outlines.
 * 
 */
@Test
public void main() throws Exception {

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

	// step 2:
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Bookmarks.pdf"));
	// step 3:
	writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
	document.open();
	// step 4: we grab the ContentByte and do some stuff with it
	writer.setPageEvent(new BookmarksTest());

	document.add(new Paragraph(
			"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.",
			new Font(Font.HELVETICA, 12)));
	document.add(new Paragraph(
			"[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.]",
			new Font(Font.HELVETICA, 12)));
	document.add(new Paragraph(
			"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.",
			new Font(Font.HELVETICA, 12)));
	document.add(new Paragraph(
			"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.",
			new Font(Font.HELVETICA, 12)));
	document.add(new Paragraph(
			"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.",
			new Font(Font.HELVETICA, 12)));

	// step 5: we close the document
	document.close();
}
 
Example #19
Source File: NestedTablesTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Using nested tables.
 * 
 */
@Test
public void main() throws Exception {
	// step1
	Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
	// step2
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("NestedTables.pdf"));
	// step3
	document.open();
	// step4
	PdfPTable table = new PdfPTable(4);
	PdfPTable nested1 = new PdfPTable(2);
	nested1.addCell("1.1");
	nested1.addCell("1.2");
	PdfPTable nested2 = new PdfPTable(1);
	nested2.addCell("2.1");
	nested2.addCell("2.2");
	for (int k = 0; k < 24; ++k) {
		if (k == 1) {
			table.addCell(nested1);
		} else if (k == 20) {
			table.addCell(nested2);
		} else {
			table.addCell("cell " + k);
		}
	}
	document.add(table);
	// step 5: we close the document
	document.close();

	// step5
	document.close();
}
 
Example #20
Source File: FormPushButtonTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates an Acroform with a PushButton
 */
@Test
public void main() throws Exception {

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

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

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

	// step 4:
	PdfFormField pushbutton = PdfFormField.createPushButton(writer);
	PdfContentByte cb = writer.getDirectContent();
	cb.moveTo(0, 0);
	PdfAppearance normal = cb.createAppearance(100, 50);
	normal.setColorFill(Color.GRAY);
	normal.rectangle(5, 5, 90, 40);
	normal.fill();
	PdfAppearance rollover = cb.createAppearance(100, 50);
	rollover.setColorFill(Color.RED);
	rollover.rectangle(5, 5, 90, 40);
	rollover.fill();
	PdfAppearance down = cb.createAppearance(100, 50);
	down.setColorFill(Color.BLUE);
	down.rectangle(5, 5, 90, 40);
	down.fill();
	pushbutton.setFieldName("PushMe");
	pushbutton.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, normal);
	pushbutton.setAppearance(PdfAnnotation.APPEARANCE_ROLLOVER, rollover);
	pushbutton.setAppearance(PdfAnnotation.APPEARANCE_DOWN, down);
	pushbutton.setWidget(new Rectangle(100, 700, 200, 750), PdfAnnotation.HIGHLIGHT_PUSH);
	writer.addAnnotation(pushbutton);

	// step 5: we close the document
	document.close();
}
 
Example #21
Source File: PdfReader.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void iteratePages(PRIndirectReference rpage) throws IOException {
    PdfDictionary page = (PdfDictionary)getPdfObject(rpage);
    PdfArray kidsPR = (PdfArray)getPdfObject(page.get(PdfName.KIDS));
    if (kidsPR == null) {
        page.put(PdfName.TYPE, PdfName.PAGE);
        PdfDictionary dic = (PdfDictionary)pageInh.get(pageInh.size() - 1);
        PdfName key;
        for (Iterator i = dic.getKeys().iterator(); i.hasNext();) {
            key = (PdfName)i.next();
            if (page.get(key) == null)
                page.put(key, dic.get(key));
        }
        if (page.get(PdfName.MEDIABOX) == null) {
            PdfArray arr = new PdfArray(new float[]{0,0,PageSize.LETTER.right(),PageSize.LETTER.top()});
            page.put(PdfName.MEDIABOX, arr);
        }
        refsn.add(rpage);
    }
    else {
        page.put(PdfName.TYPE, PdfName.PAGES);
        pushPageAttributes(page);
        ArrayList kids = kidsPR.getArrayList();
        for (int k = 0; k < kids.size(); ++k){
            iteratePages((PRIndirectReference)kids.get(k));
        }
        popPageAttributes();
    }
}
 
Example #22
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 #23
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 #24
Source File: ExamplePDF417Test.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Example Barcode PDF417.
 */
@Test
public void main() throws Exception {
       

           BarcodePDF417 pdf417 = new BarcodePDF417();
           String text = "It was the best of times, it was the worst of times, " + 
               "it was the age of wisdom, it was the age of foolishness, " +
               "it was the epoch of belief, it was the epoch of incredulity, " +
               "it was the season of Light, it was the season of Darkness, " +
               "it was the spring of hope, it was the winter of despair, " +
               "we had everything before us, we had nothing before us, " +
               "we were all going direct to Heaven, we were all going direct " +
               "the other way - in short, the period was so far like the present " +
               "period, that some of its noisiest authorities insisted on its " +
               "being received, for good or for evil, in the superlative degree " +
               "of comparison only.";
           pdf417.setText(text);
           Document document = new Document(PageSize.A4, 50, 50, 50, 50);
           PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "pdf417.pdf"));
           document.open();
           Image img = pdf417.getImage();
           img.scalePercent(50, 50 * pdf417.getYHeight());
           document.add(img);
           document.close();

}
 
Example #25
Source File: LargeCellTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates the features of the old Table class.
 */
@Test
public void main() throws Exception {
	// step 1: creation of a document-object
	Document document = new Document(PageSize.A6);
	// step 2: creation of the writer-object
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("largecell.pdf"));
	// step 3: we open the document
	document.open();
	// step 4: we create a table and add it to the document
	Table table = new Table(3);
	table.setCellsFitPage(true);
	String text = "long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long text";
	table.addCell("text");
	table.addCell("text");
	table.addCell("text");
	table.addCell(text);
	table.addCell(text + text);
	table.addCell(text);
	table.addCell("text");
	table.addCell("text");
	table.addCell("text");
	document.add(table);

	// step 5: we close the document
	document.close();
}
 
Example #26
Source File: PdfReaderTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Ignore("validity of test needs to be resolved")
   @Test
   public void testGetLink() throws Exception {
PdfReader currentReader = new PdfReader(PdfTestBase.RESOURCES_DIR +"getLinkTest1.pdf");
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
PdfWriter writer = PdfWriter.getInstance(document, new
	ByteArrayOutputStream());
document.open();
document.newPage();
List<?> links = currentReader.getLinks(1);
PdfAnnotation.PdfImportedLink link =
	(PdfAnnotation.PdfImportedLink) links.get(0);
writer.addAnnotation(link.createAnnotation(writer));
document.close();
   }
 
Example #27
Source File: ShadingPatternTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Shading example.
 */
@Test
public void main() throws Exception {
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	PdfWriter writer = PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("shading_pattern.pdf"));
	document.open();

	PdfShading shading = PdfShading.simpleAxial(writer, 100, 100, 400, 100,
			Color.red, Color.cyan);
	PdfShadingPattern shadingPattern = new PdfShadingPattern(shading);
	PdfContentByte cb = writer.getDirectContent();
	BaseFont bf = BaseFont.createFont(BaseFont.TIMES_BOLD,
			BaseFont.WINANSI, false);
	cb.setShadingFill(shadingPattern);
	cb.beginText();
	cb.setTextMatrix(100, 100);
	cb.setFontAndSize(bf, 40);
	cb.showText("Look at this text!");
	cb.endText();
	PdfShading shadingR = PdfShading.simpleRadial(writer, 200, 500, 50,
			300, 500, 100, new Color(255, 247, 148), new Color(247, 138,
					107), false, false);
	cb.paintShading(shadingR);
	cb.sanityCheck();
	document.close();

}
 
Example #28
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 #29
Source File: TransactionReport.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generates transaction report
 * 
 * @param errorSortedList list of error'd transactions
 * @param reportErrors map containing transactions and the errors associated with each transaction
 * @param reportSummary list of summary objects
 * @param runDate date report is run
 * @param title title of report
 * @param fileprefix file prefix of report file
 * @param destinationDirectory destination of where report file will reside
 */
public void generateReport(List<Transaction> errorSortedList, Map<Transaction, List<Message>> reportErrors, List<Summary> reportSummary, Date runDate, String title, String fileprefix, String destinationDirectory) {
    LOG.debug("generateReport() started");

    Font headerFont = FontFactory.getFont(FontFactory.COURIER, 8, Font.BOLD);
    Font textFont = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL);

    Document document = new Document(PageSize.A4.rotate());

    PageHelper helper = new PageHelper();
    helper.runDate = runDate;
    helper.headerFont = headerFont;
    helper.title = title;

    try {
        DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
        
        String filename = destinationDirectory + "/" + fileprefix + "_";
        filename = filename + dateTimeService.toDateTimeStringForFilename(runDate);
        filename = filename + ".pdf";
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        writer.setPageEvent(helper);

        document.open();
        appendReport(document, headerFont, textFont, errorSortedList, reportErrors, reportSummary, runDate);
    }
    catch (DocumentException de) {
        LOG.error("generateReport() Error creating PDF report", de);
        throw new RuntimeException("Report Generation Failed: " + de.getMessage());
    }
    catch (FileNotFoundException fnfe) {
        LOG.error("generateReport() Error writing PDF report", fnfe);
        throw new RuntimeException("Report Generation Failed: Error writing to file " + fnfe.getMessage());
    }
    finally {
        if ((document != null) && document.isOpen()) {
            document.close();
        }
    }
}
 
Example #30
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();
   }