com.lowagie.text.Document Java Examples

The following examples show how to use com.lowagie.text.Document. 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: DrawingTextTest.java    From itext2 with GNU Lesser General Public License v3.0 7 votes vote down vote up
/**
 * Demonstrates setting text into an RTF drawing object.
 * 
 * 
 */
@Test
public void main() throws Exception {
	Document document = new Document();
	RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("DrawingText.rtf"));

	document.open();

	// Create a new rectangle RtfShape.
	RtfShapePosition position = new RtfShapePosition(1000, 1000, 3000, 2000);
	RtfShape shape = new RtfShape(RtfShape.SHAPE_RECTANGLE, position);

	// Set the text to display in the drawing object
	shape.setShapeText("This text will appear in the drawing object.");

	document.add(shape);

	document.close();

}
 
Example #2
Source File: MyFirstTableTest.java    From itext2 with GNU Lesser General Public License v3.0 7 votes vote down vote up
/**
 * A very simple Table example.
 * 
 */
@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("MyFirstTable.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(2, 2); // 2 rows, 2 columns
	table.addCell("0.0");
	table.addCell("0.1");
	table.addCell("1.0");
	table.addCell("1.1");
	document.add(table);
	document.add(new Paragraph("converted to PdfPTable:"));
	table.setConvert2pdfptable(true);
	document.add(table);

	// step 5: we close the document
	document.close();
}
 
Example #3
Source File: PRStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Creates a new PDF stream object that will replace a stream in a existing PDF file.
 *
 * @param reader the reader that holds the existing PDF
 * @param conts the new content
 * @param compressionLevel the compression level for the content
 * @since 2.1.3 (replacing the existing constructor without param compressionLevel)
 */
public PRStream(PdfReader reader, byte[] conts, int compressionLevel) {
	this.reader = reader;
	offset = -1;
	if (Document.compress) {
		try {
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			Deflater deflater = new Deflater(compressionLevel);
			DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater);
			zip.write(conts);
			zip.close();
			deflater.end();
			bytes = stream.toByteArray();
		} catch (IOException ioe) {
			throw new ExceptionConverter(ioe);
		}
		put(PdfName.FILTER, PdfName.FLATEDECODE);
	} else {
		bytes = conts;
	}
	setLength(bytes.length);
}
 
Example #4
Source File: EventsTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * After the content of the page is written, we put page X of Y at the
 * bottom of the page and we add either "Romeo and Juliet" of the title
 * of the current act as a header.
 * 
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
	int pageN = writer.getPageNumber();
	String text = "Page " + pageN + " of ";
	float len = bf.getWidthPoint(text, 8);
	cb.beginText();
	cb.setFontAndSize(bf, 8);
	cb.setTextMatrix(280, 30);
	cb.showText(text);
	cb.endText();
	cb.addTemplate(template, 280 + len, 30);
	cb.beginText();
	cb.setFontAndSize(bf, 8);
	cb.setTextMatrix(280, 820);
	if (pageN % 2 == 1) {
		cb.showText("Romeo and Juliet");
	} else {
		cb.showText(act);
	}
	cb.endText();
}
 
Example #5
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 #6
Source File: TestPdfCopyAndStamp.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void createTempFile(String filename, String[] pageContents) throws Exception{
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    document.open();
    
    for (int i = 0; i < pageContents.length; i++) {
        if (i != 0)
            document.newPage();

        String content = pageContents[i];
        Chunk contentChunk = new Chunk(content);
        document.add(contentChunk);
    }
    
    
    document.close();
}
 
Example #7
Source File: TablePdfTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testTableSpacingPercentage() throws FileNotFoundException,
		DocumentException {
	Document document = PdfTestBase
			.createPdf("testTableSpacingPercentage.pdf");
	document.setMargins(72, 72, 72, 72);
	document.open();
	PdfPTable table = new PdfPTable(1);
	table.setSpacingBefore(20);
	table.setWidthPercentage(100);
	PdfPCell cell;
	cell = new PdfPCell();
	Phrase phase = new Phrase("John Doe");
	cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // This has no
														// effect
	cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // This has no effect
	cell.addElement(phase);
	table.addCell(cell);
	document.add(table);
	document.close();
}
 
Example #8
Source File: JavaScriptActionTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a document with a javascript action.
 * 
 */
@Test
public void main() throws Exception {

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

	// step 2:
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("JavaScriptAction.pdf"));
	// step 3: we add Javascript as Metadata and we open the document
	document.open();
	// step 4: we add some content
	Paragraph p = new Paragraph(new Chunk("Click to say Hello").setAction(PdfAction.javaScript(
			"app.alert('Hello');\r", writer)));
	document.add(p);

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

}
 
Example #9
Source File: HelloHtmlTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates an HTML page 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 HTML-stream to a file
	HtmlWriter.getInstance(document, PdfTestBase.getOutputStream("HelloWorld.html"));

	// 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 #10
Source File: TestPdfReport.java    From javamelody with Apache License 2.0 6 votes vote down vote up
/** Test.
 * @throws IOException e
 * @throws DocumentException e */
@Test
public void testEmptyPdfCounterRequestContext() throws IOException, DocumentException {
	final ByteArrayOutputStream output = new ByteArrayOutputStream();
	final PdfDocumentFactory pdfDocumentFactory = new PdfDocumentFactory(TEST_APP, null,
			output);
	final Document document = pdfDocumentFactory.createDocument();
	document.open();
	final PdfCounterRequestContextReport report = new PdfCounterRequestContextReport(
			Collections.<CounterRequestContext> emptyList(),
			Collections.<PdfCounterReport> emptyList(),
			Collections.<ThreadInformations> emptyList(), true, pdfDocumentFactory, document);
	report.toPdf();
	report.setTimeOfSnapshot(System.currentTimeMillis());
	report.writeContextDetails();
	// on ne peut fermer le document car on n'a rien écrit normalement
	assertNotNull("PdfCounterRequestContextReport", report);
}
 
Example #11
Source File: MPdfWriter.java    From javamelody with Apache License 2.0 6 votes vote down vote up
/**
 * We create a writer that listens to the document and directs a PDF-stream to out
 *
 * @param table
 *           MBasicTable
 * @param document
 *           Document
 * @param out
 *           OutputStream
 * @return DocWriter
 * @throws DocumentException
 *            e
 */
protected DocWriter createWriter(final MBasicTable table, final Document document,
		final OutputStream out) throws DocumentException {
	final PdfWriter writer = PdfWriter.getInstance(document, out);
	// writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft);

	// title
	if (table.getName() != null) {
		final HeaderFooter header = new HeaderFooter(new Phrase(table.getName()), false);
		header.setAlignment(Element.ALIGN_LEFT);
		header.setBorder(Rectangle.NO_BORDER);
		document.setHeader(header);
		document.addTitle(table.getName());
	}

	// simple page numbers : x
	// HeaderFooter footer = new HeaderFooter(new Phrase(), true);
	// footer.setAlignment(Element.ALIGN_RIGHT);
	// footer.setBorder(Rectangle.TOP);
	// document.setFooter(footer);

	// add the event handler for advanced page numbers : x/y
	writer.setPageEvent(new AdvancedPageNumberEvents());

	return writer;
}
 
Example #12
Source File: GridUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Writes a PDF representation of the given list of Grids to the given OutputStream.
 */
public static void toPdf( List<Grid> grids, OutputStream out )
{
    if ( hasNonEmptyGrid( grids ) )
    {
        Document document = openDocument( out );

        for ( Grid grid : grids )
        {
            toPdfInternal( grid, document, 40F );
        }

        addPdfTimestamp( document, false );

        closeDocument( document );
    }
}
 
Example #13
Source File: PurchaseOrderQuoteRequestsPdf.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Invokes the createPOQuoteRequestsListPdf method to create a purchase order quote list request pdf document 
 * and saves it into a file which name and location are specified in the input parameters.
 * 
 * @param po               The PurchaseOrderDocument to be used to generate the pdf.
 * @param pdfFileLocation  The location to save the pdf file.
 * @param pdfFilename      The name for the pdf file.
 * @param institutionName  The purchasing institution name.
 * @return                 Collection of errors which are made of the messages from DocumentException.    
 */
public Collection savePOQuoteRequestsListPdf(PurchaseOrderDocument po, String pdfFileLocation, String pdfFilename, String institutionName) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("savePOQuoteRequestsListPDF() started for po number " + po.getPurapDocumentIdentifier());
    }

    Collection errors = new ArrayList();

    try {
        Document doc = this.getDocument();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(pdfFileLocation + pdfFilename));
        this.createPOQuoteRequestsListPdf(po, doc, writer, institutionName);
    }
    catch (DocumentException de) {
        LOG.error(de.getMessage(), de);
        errors.add(de.getMessage());
    }
    catch (FileNotFoundException f) {
        LOG.error(f.getMessage(), f);
        errors.add(f.getMessage());
    }
    return errors;
}
 
Example #14
Source File: HelloWorldMetaTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates a PDF file with metadata
 * 
 */
@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("HelloWorldMeta.pdf"));

	// step 3: we add some metadata open the document
	document.addTitle("Hello World example");
	document.addSubject("This example explains how to add metadata.");
	document.addKeywords("iText, Hello World, step 3, metadata");
	document.addCreator("My program using iText");
	document.addAuthor("Bruno Lowagie");
	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 #15
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 #16
Source File: HelloWorldTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Hello World! example
 * 
 */
@Test
public void main() throws Exception {
	// Step 1: Create a new Document
	Document document = new Document();

	// Step 2: Create a new instance of the RtfWriter2 with the document
	// and target output stream.
	RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("HelloWorld.rtf"));

	// Step 3: Open the document.
	document.open();

	// Step 4: Add content to the document.
	document.add(new Paragraph("Hello World!"));

	// Step 5: Close the document. It will be written to the target output
	// stream.
	document.close();

}
 
Example #17
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 #18
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 #19
Source File: ActionsTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a document with some goto actions.
 * 
 */
@Test
public void main() throws Exception {

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

	// step 2:
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Actions.pdf"));
	PdfWriter.getInstance(remote, PdfTestBase.getOutputStream("remote.pdf"));
	// step 3:
	document.open();
	remote.open();
	// step 4: we add some content
	PdfAction action = PdfAction.gotoLocalPage(2, new PdfDestination(PdfDestination.XYZ, -1, 10000, 0), writer);
	writer.setOpenAction(action);
	document.add(new Paragraph("Page 1"));
	document.newPage();
	document.add(new Paragraph("Page 2"));
	document.add(new Chunk("goto page 1").setAction(PdfAction.gotoLocalPage(1, new PdfDestination(
			PdfDestination.FITH, 500), writer)));
	document.add(Chunk.NEWLINE);
	document.add(new Chunk("goto another document").setAction(PdfAction.gotoRemotePage("remote.pdf", "test", false,
			true)));
	remote.add(new Paragraph("Some remote document"));
	remote.newPage();
	Paragraph p = new Paragraph("This paragraph contains a ");
	p.add(new Chunk("local destination").setLocalDestination("test"));
	remote.add(p);

	// step 5: we close the document
	document.close();
	remote.close();
}
 
Example #20
Source File: TablePdfTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testCreateTable() throws FileNotFoundException,
		DocumentException {
	// create document
	Document document = PdfTestBase.createPdf("testCreateTable.pdf");
	try {
		// new page with a table
		document.open();
		document.newPage();

		PdfPTable table = createPdfTable(2);

		for (int i = 0; i < 10; i++) {
			PdfPCell cell = new PdfPCell();
			cell.setRowspan(2);
			table.addCell(cell);

		}
		table.calculateHeights(true);
		document.add(table);
		document.newPage();

	} finally {
		// close document
		if (document != null)
			document.close();
	}

}
 
Example #21
Source File: OutSimplePdf.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Performs the action: generate a PDF from a GET or POST.
 * 
 * @param request	the Servlets request object
 * @param response	the Servlets request object
 * @param methodGetPost	the method that was used in the form
 */
public void makePdf(HttpServletRequest request, HttpServletResponse response, String methodGetPost) {
	try {

		// take the message from the URL or create default message
		String msg = request.getParameter("msg");
		if (msg == null || msg.trim().length() <= 0)
			msg = "[ specify a message in the 'msg' argument on the URL ]";

		// create simple doc and write to a ByteArrayOutputStream
		Document document = new Document();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		PdfWriter.getInstance(document, baos);
		document.open();
		document.add(new Paragraph(msg));
		document.add(Chunk.NEWLINE);
		document.add(new Paragraph("The method used to generate this PDF was: " + methodGetPost));
		document.close();

		// setting some response headers
		response.setHeader("Expires", "0");
		response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
		response.setHeader("Pragma", "public");
		// setting the content type
		response.setContentType("application/pdf");
		// the contentlength is needed for MSIE!!!
		response.setContentLength(baos.size());
		// write ByteArrayOutputStream to the ServletOutputStream
		ServletOutputStream out = response.getOutputStream();
		baos.writeTo(out);
		out.flush();

	} catch (Exception e2) {
		System.out.println("Error in " + getClass().getName() + "\n" + e2);
	}
}
 
Example #22
Source File: SurveyPdf.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeAnswer(Document document,String questionText , String answerValue) throws Exception{
	Paragraph questionParagraph = new Paragraph();
	questionParagraph.setLeading(14, 0);
	questionParagraph.add(new Chunk(questionText.trim() + ": ",boldedFont)); 
    questionParagraph.add(new Chunk(answerValue == null ? "": answerValue.trim() ,normalFont));  
	document.add(questionParagraph);
}
 
Example #23
Source File: DepreciationReport.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This method creates the report file and invokes the methods that write the data
 * 
 * @param reportLog
 * @param errorMsg
 */
public void generateReport(List<String[]> reportLog, String errorMsg, String sDepreciationDate) {
    try {
        DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
        LOG.debug("createReport() started");
        this.document = new Document();

        String destinationDirectory = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(KFSConstants.REPORTS_DIRECTORY_KEY);

        SimpleDateFormat sdf = new SimpleDateFormat(CamsConstants.DateFormats.YEAR_MONTH_DAY_NO_DELIMITER + "_" + CamsConstants.DateFormats.MILITARY_TIME_NO_DELIMITER);

        String filename = destinationDirectory + File.separator + "cam" + File.separator + CamsConstants.Report.FILE_PREFIX + "_" + CamsConstants.Depreciation.REPORT_FILE_NAME + "_" + sdf.format(dateTimeService.getCurrentDate()) + "." + CamsConstants.Report.REPORT_EXTENSION;

        Font headerFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);

        PageHelper helper = new PageHelper();
        helper.runDate = dateTimeService.getCurrentDate();
        helper.headerFont = headerFont;
        helper.title = CamsConstants.Depreciation.DEPRECIATION_REPORT_TITLE;

        writer = PdfWriter.getInstance(this.document, new FileOutputStream(filename));
        writer.setPageEvent(helper);

        this.document.open();

        // Generate body of document.
        this.generateReportLogBody(reportLog);
        this.generateReportErrorLog(errorMsg);

    }
    catch (Exception e) {
        throw new RuntimeException("DepreciationReport.generateReport(List<String[]> reportLog, List<String> errorLog) - Error on report generation: " + e.getMessage());
    }
    finally {
        if ((this.document != null) && this.document.isOpen()) {
            this.document.close();
        }
    }
}
 
Example #24
Source File: PDFPageDevice.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * constructor for test
 *
 * @param output
 */
public PDFPageDevice( OutputStream output )
{
	doc = new Document( );
	try
	{
		writer = PdfWriter.getInstance( doc, new BufferedOutputStream(
				output ) );
	}
	catch ( DocumentException de )
	{
		logger.log( Level.SEVERE, de.getMessage( ), de );
	}
}
 
Example #25
Source File: RenderingTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Special rendering of Chunks.
 * 
 */
@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("Rendering.pdf"));

	// step 3: we open the document
	document.open();
	// step 4:
	Paragraph p = new Paragraph("Text Rendering:");
	document.add(p);
	Chunk chunk = new Chunk("rendering test");
	chunk.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_FILL, 100f, new Color(0xFF, 0x00, 0x00));
	document.add(chunk);
	document.add(Chunk.NEWLINE);
	chunk.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, 0.3f, new Color(0xFF, 0x00, 0x00));
	document.add(chunk);
	document.add(Chunk.NEWLINE);
	chunk.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE, 100f, new Color(0x00, 0xFF, 0x00));
	document.add(chunk);
	document.add(Chunk.NEWLINE);
	chunk.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_STROKE, 0.3f, new Color(0x00, 0x00, 0xFF));
	document.add(chunk);
	document.add(Chunk.NEWLINE);
	Chunk bold = new Chunk("This looks like Font.BOLD");
	bold.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, 0.5f, new Color(0x00, 0x00, 0x00));
	document.add(bold);

	// step 5: we close the document
	document.close();
}
 
Example #26
Source File: StatisticsPdf.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeEntry(Document document,String label , String value) throws Exception{
	Paragraph questionParagraph = new Paragraph();
	questionParagraph.setLeading(14, 0);
	questionParagraph.setIndentationLeft(18);
	questionParagraph.add(new Chunk(label.trim() + ": ",boldedFont)); 
    questionParagraph.add(new Chunk(value == null ? "": value.trim() ,normalFont));  
	document.add(questionParagraph);
}
 
Example #27
Source File: StatisticsPdf.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeEntry(Document document,String label , Date value, String dateFormat) throws Exception{
	Paragraph questionParagraph = new Paragraph();
	questionParagraph.setLeading(14, 0);
	questionParagraph.setIndentationLeft(18);
	questionParagraph.add(new Chunk(label.trim() + ": ",boldedFont)); 
    questionParagraph.add(new Chunk(DateValidator.getInstance().format(value ,dateFormat) , normalFont));  
	document.add(questionParagraph);
}
 
Example #28
Source File: TestPdfReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/** Test.
 * @throws IOException e
 * @throws DocumentException e */
@Test
public void testPdfCounterReportWithIncludeGraph() throws IOException, DocumentException {
	// counterName doit être http, sql ou ejb pour que les libellés de graph soient trouvés dans les traductions
	final Counter counter = new Counter("http", "db.png");
	final Counter errorCounter = new Counter(Counter.ERROR_COUNTER_NAME, null);
	final List<Counter> counters = Arrays.asList(counter, errorCounter);
	final Collector collector = new Collector(TEST_APP, counters);
	final JavaInformations javaInformations = new JavaInformations(null, true);
	final ByteArrayOutputStream output = new ByteArrayOutputStream();
	final List<JavaInformations> javaInformationsList = Collections
			.singletonList(javaInformations);
	counter.addRequest("test include graph", 1, 1, 1, false, 1000);
	errorCounter.addRequestForSystemError("error", 1, 1, 1, null);
	collector.collectWithoutErrors(javaInformationsList);
	counter.addRequest("test include graph", 1, 1, 1, false, 1000);
	errorCounter.addRequestForSystemError("error", 1, 1, 1, null);
	collector.collectWithoutErrors(javaInformationsList);
	final Document document = new PdfDocumentFactory(TEST_APP, null, output).createDocument();
	document.open();
	final PdfCounterReport pdfCounterReport = new PdfCounterReport(collector, counter,
			Period.TOUT.getRange(), true, document);
	pdfCounterReport.toPdf();
	pdfCounterReport.writeRequestDetails();
	final PdfCounterReport pdfErrorCounterReport = new PdfCounterReport(collector, errorCounter,
			Period.TOUT.getRange(), true, document);
	pdfErrorCounterReport.writeRequestDetails();
	document.close();
	assertNotEmptyAndClear(output);
}
 
Example #29
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 #30
Source File: PdfWriter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Use this method to get an instance of the <CODE>PdfWriter</CODE>.
 *
 * @param document The <CODE>Document</CODE> that has to be written
 * @param os The <CODE>OutputStream</CODE> the writer has to write to.
 * @return a new <CODE>PdfWriter</CODE>
 * @throws DocumentException on error
 */

public static PdfWriter getInstance(Document document, OutputStream os) throws DocumentException {
	PdfDocument pdf = new PdfDocument();
	document.addDocListener(pdf);
	PdfWriter writer = new PdfWriter(pdf, os);
	pdf.addWriter(writer);
	return writer;
}