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

The following examples show how to use com.lowagie.text.Document#close() . 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: CashReceiptCoverSheetServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Generate a cover sheet for the <code>{@link CashReceiptDocument}</code>. An <code>{@link OutputStream}</code> is written
 * to for the cover sheet.
 *
 * @param document The cash receipt document the cover sheet is for.
 * @param searchPath The directory path to the template to be used to generate the cover sheet.
 * @param returnStream The output stream the cover sheet will be written to.
 * @exception DocumentException Thrown if the document provided is invalid, including null.
 * @exception IOException Thrown if there is a problem writing to the output stream.
 * @see org.kuali.rice.kns.module.financial.service.CashReceiptCoverSheetServiceImpl#generateCoverSheet(
 *      org.kuali.module.financial.documentCashReceiptDocument )
 */
@Override
public void generateCoverSheet(CashReceiptDocument document, String searchPath, OutputStream returnStream) throws Exception {

    if (isCoverSheetPrintingAllowed(document)) {
        ByteArrayOutputStream stamperStream = new ByteArrayOutputStream();

        stampPdfFormValues(document, searchPath, stamperStream);

        PdfReader reader = new PdfReader(stamperStream.toByteArray());
        Document pdfDoc = new Document(reader.getPageSize(FRONT_PAGE));
        PdfWriter writer = PdfWriter.getInstance(pdfDoc, returnStream);

        pdfDoc.open();
        populateCheckDetail(document, writer, reader);
        pdfDoc.close();
        writer.close();
    }
}
 
Example 2
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 3
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 4
Source File: HelloWorldTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates a PDF file with the text 'Hello World'
 * 
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document();
	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("HelloWorld.pdf"));

	// step 3: we open the document
	document.open();
	// step 4: we add a paragraph to the document
	document.add(new Paragraph("Hello World"));

	// step 5: we close the document
	document.close();
}
 
Example 5
Source File: DocumentSettingsTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Document settings example.
 * 
 * 
 */
@Test
public void main() throws Exception {
	Document document = new Document();

	// Keep a reference to the RtfWriter2 instance.
	RtfWriter2 writer2 = RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("DocumentSettings.rtf"));

	// Specify that the document caching is to be done on disk.
	writer2.getDocumentSettings().setDataCacheStyle(RtfDataCache.CACHE_DISK);

	// Specify that all \n are translated into soft linebreaks.
	writer2.getDocumentSettings().setAlwaysGenerateSoftLinebreaks(true);

	document.open();
	document.add(new Paragraph("This example has been cached on disk\nand all "
			+ "\\n have been translated into soft linebreaks."));
	document.close();
}
 
Example 6
Source File: TrueTypeTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Embedding True Type Fonts.
 */
@Test
public void main() throws Exception {



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

	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "truetype.pdf"));

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

	// step 4: we add content to the document
	BaseFont bfComic = BaseFont.createFont(PdfTestBase.RESOURCES_DIR + "/liberation-fonts-ttf/LiberationSans-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	Font font = new Font(bfComic, 12);
	String text1 = "This is the quite popular True Type font 'LiberationSans'.";
	String text2 = "Some greek characters: \u0393\u0394\u03b6";
	String text3 = "Some cyrillic characters: \u0418\u044f";
	document.add(new Paragraph(text1, font));
	document.add(new Paragraph(text2, font));
	document.add(new Paragraph(text3, font));

	// step 5: we close the document
	document.close();
}
 
Example 7
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 8
Source File: TrialBalanceReportAction.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generate pdf for sending response using itext
 *
 * @param reportFileFullName
 * @return
 * @throws IOException
 * @throws DocumentException
 * @throws BadPdfFormatException
 */
protected ByteArrayOutputStream generatePdfOutStream(String reportFileFullName) throws IOException, DocumentException, BadPdfFormatException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // we create a reader for a certain document
    PdfReader reader = new PdfReader(reportFileFullName);
    reader.consolidateNamedDestinations();

    // step 1: creation of a document-object
    Document document = new Document(reader.getPageSizeWithRotation(1));
    // step 2: we create a writer that listens to the document
    PdfCopy writer = new PdfCopy(document, baos);
    // step 3: we open the document
    document.open();

    // we retrieve the total number of pages
    int n = reader.getNumberOfPages();

    // step 4: we add content
    PdfImportedPage page;
    for (int i = 0; i < n;) {
        ++i;
        page = writer.getImportedPage(reader, i);
        writer.addPage(page);
    }
    writer.freeReader(reader);

    // step 5: we close the document
    document.close();
    return baos;
}
 
Example 9
Source File: EncriptionTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
private byte[] createEncryptedPDF () throws DocumentException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	
	Rectangle rec = new Rectangle(PageSize.A4.getWidth(),
			PageSize.A4.getHeight());
	Document document = new Document(rec);		
	PdfWriter writer = PdfWriter.getInstance(document, baos);
	writer.setEncryption("Hello".getBytes(), "World".getBytes(), PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
	document.open();
	document.add(new Paragraph("Hello World"));
	document.close();
			
	return baos.toByteArray();
}
 
Example 10
Source File: DefaultPdfDataEntryFormService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void generatePDFDataEntryForm( Document document, PdfWriter writer, String dataSetUid, int typeId,
    Rectangle pageSize, PdfFormFontSettings pdfFormFontSettings, I18nFormat format )
{
    try
    {
        this.pdfFormFontSettings = pdfFormFontSettings;
        this.format = format;

        document.setPageSize( pageSize );

        document.open();

        if ( typeId == PdfDataEntryFormUtil.DATATYPE_DATASET )
        {
            setDataSet_DocumentContent( document, writer, dataSetUid );
        }
        else if ( typeId == PdfDataEntryFormUtil.DATATYPE_PROGRAMSTAGE )
        {
            setProgramStage_DocumentContent( document, writer, dataSetUid );
        }
    }
    catch ( Exception ex )
    {
        throw new RuntimeException( ex );
    }
    finally
    {
        document.close();
    }
}
 
Example 11
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 12
Source File: WidthTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates how to measure and scale the width of a Chunk.
 * 
 */
@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
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Width.pdf"));

	// step 3: we open the document
	document.open();
	// step 4:
	Chunk c = new Chunk("quick brown fox jumps over the lazy dog");
	float w = c.getWidthPoint();
	Paragraph p = new Paragraph("The width of the chunk: '");
	p.add(c);
	p.add("' is ");
	p.add(String.valueOf(w));
	p.add(" points or ");
	p.add(String.valueOf(w / 72f));
	p.add(" inches.");
	document.add(p);
	document.add(c);
	document.add(Chunk.NEWLINE);
	c.setHorizontalScaling(0.5f);
	document.add(c);
	document.add(c);

	// step 5: we close the document
	document.close();
}
 
Example 13
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 14
Source File: TextTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Adding text at absolute positions.
 */
@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("text.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();

	// first we draw some lines to be able to visualize the text alignment
	// functions
	cb.setLineWidth(0f);
	cb.moveTo(250, 500);
	cb.lineTo(250, 800);
	cb.moveTo(50, 700);
	cb.lineTo(400, 700);
	cb.moveTo(50, 650);
	cb.lineTo(400, 650);
	cb.moveTo(50, 600);
	cb.lineTo(400, 600);
	cb.stroke();

	// we tell the ContentByte we're ready to draw text
	cb.beginText();

	BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
			BaseFont.NOT_EMBEDDED);
	cb.setFontAndSize(bf, 12);
	String text = "Sample text for alignment";
	// we show some text starting on some absolute position with a given
	// alignment
	cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 250,
			700, 0);
	cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 250,
			650, 0);
	cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 250, 600,
			0);

	// we draw some text on a certain position
	cb.setTextMatrix(100, 400);
	cb.showText("Text at position 100,400.");

	// we draw some rotated text on a certain position
	cb.setTextMatrix(0, 1, -1, 0, 100, 300);
	cb.showText("Text at position 100,300, rotated 90 degrees.");

	// we draw some mirrored, rotated text on a certain position
	cb.setTextMatrix(0, 1, 1, 0, 200, 200);
	cb.showText("Text at position 200,200, mirrored and rotated 90 degrees.");

	// we tell the contentByte, we've finished drawing text
	cb.endText();

	cb.sanityCheck();

	// step 5: we close the document
	document.close();
}
 
Example 15
Source File: ExtendedTableCellTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Extended borders for Table Cells.
 * 
 * 
 */
@Test
public void main() throws Exception {
	Document document = new Document();
	RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("ExtendedTableCell.rtf"));

	document.open();

	Table table = new Table(3);

	// Create a simple RtfCell with a dotted border.
	RtfCell cellDotted = new RtfCell("Dotted border");
	cellDotted.setBorders(new RtfBorderGroup(Rectangle.BOX, RtfBorder.BORDER_DOTTED, 1, new Color(0, 0, 0)));

	// Create a simple RtfCell with an embossed border.
	RtfCell cellEmbossed = new RtfCell("Embossed border");
	cellEmbossed.setBorders(new RtfBorderGroup(Rectangle.BOX, RtfBorder.BORDER_EMBOSS, 1, new Color(0, 0, 0)));

	// Create a simple RtfCell with no border.
	RtfCell cellNoBorder = new RtfCell("No border");
	cellNoBorder.setBorders(new RtfBorderGroup());
	cellNoBorder.setRowspan(2);

	// Create a simple RtfCell that only has a border
	// on the bottom side.
	RtfCell bottomBorder = new RtfCell("Bottom border");
	bottomBorder.setBorders(new RtfBorderGroup(Rectangle.BOTTOM, RtfBorder.BORDER_SINGLE, 2, new Color(255, 0, 0)));

	// Create a simple RtfCell that has different borders
	// on the left and bottom sides.
	RtfCell mixedBorder = new RtfCell("Mixed border");
	RtfBorderGroup mixedBorders = new RtfBorderGroup();
	mixedBorders.addBorder(Rectangle.RIGHT, RtfBorder.BORDER_DOUBLE_WAVY, 2, Color.GREEN);
	mixedBorders.addBorder(Rectangle.BOTTOM, RtfBorder.BORDER_DOT_DASH, 1, Color.BLUE);
	mixedBorder.setBorders(mixedBorders);

	// Add the cells to the table
	table.addCell(cellDotted);
	table.addCell(cellEmbossed);
	table.addCell(cellNoBorder);
	table.addCell(bottomBorder);
	table.addCell(mixedBorder);

	document.add(table);

	document.close();
}
 
Example 16
Source File: RepeatingTableTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Shows how a table is split if it doesn't fit the page.
 */
@Test
public void main() throws Exception {
	// creation of the document with a certain size and certain margins
	Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);

	// creation of the different writers
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("repeatingtable.pdf"));

	// we add some meta information to the document
	document.addAuthor("Alan Soukup");
	document.addSubject("This is the result of a Test.");

	document.open();

	Table datatable = new Table(10);

	int headerwidths[] = { 10, 24, 12, 12, 7, 7, 7, 7, 7, 7 };
	datatable.setWidths(headerwidths);
	datatable.setWidth(100);
	datatable.setPadding(3);

	// the first cell spans 10 columns
	Cell cell = new Cell(new Phrase("Administration -System Users Report", FontFactory.getFont(
			FontFactory.HELVETICA, 24, Font.BOLD)));
	cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	cell.setLeading(30);
	cell.setColspan(10);
	cell.setBorder(Rectangle.NO_BORDER);
	cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
	datatable.addCell(cell);

	// These cells span 2 rows
	datatable.getDefaultCell().setBorderWidth(2);
	datatable.getDefaultCell().setHorizontalAlignment(1);
	datatable.addCell("User Id");
	datatable.addCell("Name\nAddress");
	datatable.addCell("Company");
	datatable.addCell("Department");
	datatable.addCell("Admin");
	datatable.addCell("Data");
	datatable.addCell("Expl");
	datatable.addCell("Prod");
	datatable.addCell("Proj");
	datatable.addCell("Online");

	// this is the end of the table header
	datatable.endHeaders();

	datatable.getDefaultCell().setBorderWidth(1);

	for (int i = 1; i < 30; i++) {

		datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);

		datatable.addCell("myUserId");
		datatable
				.addCell("Somebody with a very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very long long name");
		datatable.addCell("No Name Company");
		datatable.addCell("D" + i);

		datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
		datatable.addCell("No");
		datatable.addCell("Yes");
		datatable.addCell("No");
		datatable.addCell("Yes");
		datatable.addCell("No");
		datatable.addCell("Yes");

	}
	document.add(new Paragraph("com.lowagie.text.Table - Cells split"));
	document.add(datatable);
	document.newPage();
	document.add(new Paragraph("com.lowagie.text.pdf.PdfPTable - Cells split\n\n"));
	datatable.setConvert2pdfptable(true);
	document.add(datatable);
	document.newPage();
	document.add(new Paragraph("com.lowagie.text.Table - Cells kept together"));
	datatable.setConvert2pdfptable(false);
	datatable.setCellsFitPage(true);
	document.add(datatable);
	document.newPage();
	document.add(new Paragraph("com.lowagie.text.pdf.PdfPTable - Cells kept together\n\n"));
	datatable.setConvert2pdfptable(true);
	document.add(datatable);

	// we close the document
	document.close();
}
 
Example 17
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 18
Source File: PhrasesTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Demonstrates how the class Phrase works.
 * 
 */
@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
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Phrases.pdf"));

	// step 3: we open the document
	document.open();
	// step 4:
	Phrase phrase1 = new Phrase("(1) this is a phrase\n");
	// In this example the leading is passed as a parameter
	Phrase phrase2 = new Phrase(
			24,
			"(2) this is a phrase with leading 24. You can only see the difference if the line is long enough. Do you see it? There is more space between this line and the previous one.\n");
	// When a Font is passed (explicitely or embedded in a chunk),
	// the default leading = 1.5 * size of the font
	Phrase phrase3 = new Phrase(
			"(3) this is a phrase with a red, normal font Courier, size 20. As you can see the leading is automatically changed.\n",
			FontFactory.getFont(FontFactory.COURIER, 20, Font.NORMAL, new Color(255, 0, 0)));
	Phrase phrase4 = new Phrase(new Chunk("(4) this is a phrase\n"));
	Phrase phrase5 = new Phrase(18, new Chunk(
			"(5) this is a phrase in Helvetica, bold, red and size 16 with a given leading of 18 points.\n",
			FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0))));
	// A Phrase can contains several chunks with different fonts
	Phrase phrase6 = new Phrase("(6)");
	Chunk chunk = new Chunk(" This is a font: ");
	phrase6.add(chunk);
	phrase6.add(new Chunk("Helvetica", FontFactory.getFont(FontFactory.HELVETICA, 12)));
	phrase6.add(chunk);
	phrase6.add(new Chunk("Times New Roman", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
	phrase6.add(chunk);
	phrase6.add(new Chunk("Courier", FontFactory.getFont(FontFactory.COURIER, 12)));
	phrase6.add(chunk);
	phrase6.add(new Chunk("Symbol", FontFactory.getFont(FontFactory.SYMBOL, 12)));
	phrase6.add(chunk);
	phrase6.add(new Chunk("ZapfDingBats", FontFactory.getFont(FontFactory.ZAPFDINGBATS, 12)));
	Phrase phrase7 = new Phrase("(7) if you don't add a newline yourself, all phrases are glued to eachother!");

	document.add(phrase1);
	document.add(phrase2);
	document.add(phrase3);
	document.add(phrase4);
	document.add(phrase5);
	document.add(phrase6);
	document.add(phrase7);

	// step 5: we close the document
	document.close();
}
 
Example 19
Source File: SpotColorsTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
    * Demonstrates the use of spotcolors.
    */
@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("spotcolor.pdf"));
           BaseFont bf = BaseFont.createFont("Helvetica", "winansi", BaseFont.NOT_EMBEDDED);
           
           // step 3: we open the document
           document.open();
           
           // step 4: we grab the ContentByte and do some stuff with it
           PdfContentByte cb = writer.getDirectContent();
           
           // step 5: we instantiate PdfSpotColor
           
           // Note: I made up these names unless someone give me a PANTONE swatch as gift ([email protected])
           PdfSpotColor spc_cmyk = new PdfSpotColor("PANTONE 280 CV", new CMYKColor(0.9f, .2f, .3f, .1f));
           PdfSpotColor spc_rgb = new PdfSpotColor("PANTONE 147", new Color(114, 94, 38));
           PdfSpotColor spc_g = new PdfSpotColor("PANTONE 100 CV", new GrayColor(0.9f));
           
           // Stroke a rectangle with CMYK alternate
           cb.setColorStroke(spc_cmyk, .5f);
           cb.setLineWidth(10f);
           // draw a rectangle
           cb.rectangle(100, 700, 100, 100);
           // add the diagonal
           cb.moveTo(100, 700);
           cb.lineTo(200, 800);
           // stroke the lines
           cb.stroke();
           
           // Fill a rectangle with CMYK alternate
           cb.setColorFill(spc_cmyk, 0.25f);
           cb.rectangle(250, 700, 100, 100);
           cb.fill();
           
           // Stroke a circle with RGB alternate
           cb.setColorStroke(spc_rgb, 0.9f);
           cb.setLineWidth(5f);
           cb.circle(150f, 500f, 100f);
           cb.stroke();
           
           // Fill the circle with RGB alternate
           cb.setColorFill(spc_rgb, 0.9f);
           cb.circle(150f, 500f, 50f);
           cb.fill();
           
           // example with colorfill
           cb.setColorFill(spc_g, 0.5f);
           cb.moveTo(100f, 200f);
           cb.lineTo(200f, 250f);
           cb.lineTo(400f, 150f);
           cb.fill();
           // cb.sanityCheck is called during newPage().
           document.newPage();
           String text = "Some text to show";
           document.add(new Paragraph(text, new Font(Font.HELVETICA, 24, Font.NORMAL, new SpotColor(spc_cmyk, 0.25f))));
           document.add(new Paragraph(text, new Font(Font.HELVETICA, 24, Font.NORMAL, new SpotColor(spc_cmyk, 0.5f))));
           
           // example with template
           PdfTemplate t = cb.createTemplate(500f, 500f);
           // Stroke a rectangle with CMYK alternate
           t.setColorStroke(new SpotColor(spc_cmyk, .5f));
           t.setLineWidth(10f);
           // draw a rectangle
           t.rectangle(100, 10, 100, 100);
           // add the diagonal
           t.moveTo(100, 10);
           t.lineTo(200, 100);
           // stroke the lines
           t.stroke();
           
           // Fill a rectangle with CMYK alternate
           t.setColorFill(spc_g, 0.5f);
           t.rectangle(100, 125, 100, 100);
           t.fill();
           t.beginText();
           t.setFontAndSize(bf, 20f);
           t.setTextMatrix(1f, 0f, 0f, 1f, 10f, 10f);
           t.showText("Template text upside down");
           t.endText();
           t.rectangle(0, 0, 499, 499);
           t.stroke();
           t.sanityCheck();
           cb.addTemplate(t, -1.0f, 0.00f, 0.00f, -1.0f, 550f, 550f);
           
           cb.sanityCheck();

       
       // step 5: we close the document
       document.close();
   }
 
Example 20
Source File: ContractsGrantsInvoiceReportServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Generates the pdf file for printing the envelopes.
 *
 * @param list
 * @param outputStream
 * @throws DocumentException
 * @throws IOException
 */
protected void generateCombinedPdfForEnvelopes(Collection<ContractsGrantsInvoiceDocument> list, OutputStream outputStream) throws DocumentException, IOException {
    Document document = new Document(new Rectangle(ArConstants.InvoiceEnvelopePdf.LENGTH, ArConstants.InvoiceEnvelopePdf.WIDTH));
    PdfWriter.getInstance(document, outputStream);
    boolean pageAdded = false;

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

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

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

                    document.add(sentBy);
                    document.add(sendTo);
                }
            }
        }
    }
    if (pageAdded) {
        document.close();
    }
}