Java Code Examples for com.itextpdf.text.pdf.PdfContentByte

The following are top voted examples for showing how to use com.itextpdf.text.pdf.PdfContentByte. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: weplantaforest   File: PdfGiftView.java   View source code 8 votes vote down vote up
public void buildPdfDocument(OutputStream toWrite, final String name, final int treeCount, String[] codeFragments, String imagePath) throws Exception {
    // create pdf
    final Document doc = new Document();
    final PdfWriter pdfWriter = PdfWriter.getInstance(doc, toWrite);
    pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
    _imagePath = imagePath;

    doc.open();

    PdfContentByte cb = pdfWriter.getDirectContent();

    PdfHelper.createHeaderBlock(cb,1,1);
    PdfHelper.createCircleAndText(cb, "Gutschein", 298f, 705f, 75, textFontForCircle, 0x7F, 0xAD, 0x09);

    createBlueBlock(cb, treeCount);
    createGreyBlock(cb, codeFragments);

    pdfHelper.addLogo(cb, _imagePath, 262f, 35f);
    doc.close();
}
 
Example 2
Project: polyGembler   File: JfreeChart.java   View source code 7 votes vote down vote up
public void print(String plot_pdf) {
	try {
		float width = jframe.getSize().width,
				height = jframe.getSize().height;
		Document document = new Document(new Rectangle(width, height));
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(plot_pdf));
		document.open();
		PdfContentByte canvas = writer.getDirectContent();
		PdfTemplate template = canvas.createTemplate(width, height);
		Graphics2D g2d = new PdfGraphics2D(template, width, height);
		jframe.paint(g2d);
		g2d.dispose();
		canvas.addTemplate(template, 0, 0);
		document.close();
	} catch (FileNotFoundException | DocumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 3
Project: Health   File: Histogram.java   View source code 7 votes vote down vote up
/**
 * Save the chart as pdf.
 *
 * @param chart
 *            chart that should be saved
 * @param fileName
 *            file name under which chart should be saved
 */
public static void writeChartToPDF(final JFreeChart chart,
		final String fileName) {
	PdfWriter writer = null;

	com.itextpdf.text.Document document = new com.itextpdf.text.Document(
			PageSize.A4);
	final int width = (int) PageSize.A4.getWidth();
	final int height = (int) PageSize.A4.getHeight();

	try {
		writer = PdfWriter.getInstance(document, new FileOutputStream(
				fileName + ".pdf"));
		document.open();
		PdfContentByte contentByte = writer.getDirectContent();
		PdfTemplate template = contentByte.createTemplate(width, height);
		Graphics2D graphics2d = template.createGraphics(width, height,
				new DefaultFontMapper());
		Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,
				height);

		chart.draw(graphics2d, rectangle2d);

		graphics2d.dispose();
		contentByte.addTemplate(template, 0, 0);

	} catch (Exception e) {
		e.printStackTrace();
	}
	document.close();
}
 
Example 4
Project: testarea-itext5   File: UseColumnText.java   View source code 7 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32162759/columntext-showtextaligned-vs-columntext-setsimplecolumn-top-alignment">
 * ColumnText.ShowTextAligned vs ColumnText.SetSimpleColumn Top Alignment
 * </a>
 * <p>
 * Indeed, the coordinates do not line up. The y coordinate of 
 * {@link ColumnText#showTextAligned(PdfContentByte, int, Phrase, float, float, float)}
 * denotes the baseline while {@link ColumnText#setSimpleColumn(Rectangle)} surrounds
 * the text to come.
 * </p>
 */
@Test
public void testShowTextAlignedVsSimpleColumnTopAlignment() throws DocumentException, IOException
{
    Document document = new Document(PageSize.A4);

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "ColumnTextTopAligned.pdf")));
    document.open();

    Font fontQouteItems = new Font(BaseFont.createFont(), 12);
    PdfContentByte canvas = writer.getDirectContent();

    // Item Number
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("36222-0", fontQouteItems), 60, 450, 0);

    // Estimated Qty
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("47", fontQouteItems), 143, 450, 0);

    // Item Description
    ColumnText ct = new ColumnText(canvas); // Uses a simple column box to provide proper text wrapping
    ct.setSimpleColumn(new Rectangle(193, 070, 390, 450));
    ct.setText(new Phrase("In-Situ : Poly Cable - 100'\nPoly vented rugged black gable 100ft\nThis is an additional description. It can wrap an extra line if it needs to so this text is long.", fontQouteItems));
    ct.go();

    document.close();
}
 
Example 5
Project: weplantaforest   File: PdfReceiptView.java   View source code 7 votes vote down vote up
private PdfPTable createLawTable(PdfContentByte cb) throws DocumentException {
    PdfPTable table = new PdfPTable(1);
    float[] rows = { 445f };
    table.setTotalWidth(rows);
    table.getDefaultCell()
         .setBorder(Rectangle.NO_BORDER);
    table.getDefaultCell()
         .setLeading(8f, 0);

    table.addCell(new Phrase(new Chunk("Es handelt sich nicht um den Verzicht auf Erstattung von Aufwendungen.", textFontLawText)));
    table.addCell(new Phrase(new Chunk("Die Gesellschaft ist wegen Förderung (begünstigter Zweck: Umweltschutz (§52 (2) S. 1 Nr.(n) 8 AO)) durch", textFontLawText)));
    table.addCell(new Phrase(new Chunk("Bescheinigung des Finanzamt Halle (Saale)-Nord, StNr. 110/108/91169, vom 19.11.2008 ab 01.01.2009", textFontLawText)));
    table.addCell(new Phrase(new Chunk("als gemeinnützig anerkannt. Letzter Freistellungsbescheid datiert auf den 20.06.2013.", textFontLawText)));
    table.addCell(new Phrase(new Chunk("Es wird bestätigt, dass die Zuwendung nur zur Förderung des Umweltschutzes verwendet wird.", textFontLawText)));

    PdfPCell emptyCell = new PdfPCell();
    emptyCell.setBorder(Rectangle.BOTTOM);
    emptyCell.setFixedHeight(15f);
    table.addCell(emptyCell);

    return table;
}
 
Example 6
Project: SyncRunner-Pub   File: Barcodes.java   View source code 7 votes vote down vote up
private static Image generate128(PdfContentByte cb, String sku){
	Barcode128 code128 = new Barcode128();
	code128.setCodeType(Barcode128.CODE_A);
	code128.setGuardBars(true);
    code128.setCode(sku);
    code128.setSize(7);
    code128.setBaseline(6f);
    code128.setBarHeight(27f);
    code128.setX(.70f);
    
    return code128.createImageWithBarcode(cb, null, null);
}
 
Example 7
Project: visitormanagement   File: NdaBuilder.java   View source code 6 votes vote down vote up
/**
 * Update NDA file with visitor name and visitor signature.
 * 
 * @param destFile 
 * @param signatureImage signature file
 * @param visitorName
 * @return File
 */
public static File build(Path destFile, File signatureImage, String visitorName) {
	try {
		PdfReader pdfReader = new PdfReader(ndaUrl);
		PdfStamper pdfStamper = new PdfStamper(pdfReader,
				new FileOutputStream(destFile.toString()));
		Image image = createNDAImage(signatureImage, 0, 0);
		PdfContentByte over = pdfStamper.getOverContent(5);
		over.addImage(image);
		PdfContentByte pdfContentByte = pdfStamper.getOverContent(5);
		pdfContentByte.beginText();
		pdfContentByte.setFontAndSize(BaseFont.createFont
				(BaseFont.HELVETICA, 
						BaseFont.CP1257, 
						BaseFont.EMBEDDED
						)
				, 10); 
		pdfContentByte.setTextMatrix(112, 428); 
		pdfContentByte.showText(visitorName);
		pdfContentByte.setTextMatrix(89, 406);
		pdfContentByte.showText(new SimpleDateFormat("E, dd MMM yyyy").format(new Date()));
		pdfContentByte.endText();
		pdfStamper.close();
		return destFile.toFile();
	} catch (IOException | DocumentException | NumberFormatException e) {
		logger.error("Exception while generating NDA file. ",e);
		return null;
	}
}
 
Example 8
Project: pdf-renderer   File: ImageFactory.java   View source code 6 votes vote down vote up
public ImageInstance getImageByFile( PdfContentByte cb , File file ) throws IOException, BadElementException{
	Image image = null;
	ImageInstance instance = null;
	if( file.getName().toLowerCase().endsWith( ".pdf")){	
		PdfReader reader = new PdfReader( file.getAbsolutePath() );
		PdfImportedPage p = cb.getPdfWriter().getImportedPage(reader, 1);
		image = Image.getInstance(p);
		instance = new ImageInstance(image, reader);
	}else{
		image = Image.getInstance( file.getAbsolutePath() );
		instance = new ImageInstance(image, null);
	}
	
	instances.add(instance);
	

	return instance;
}
 
Example 9
Project: pdf-renderer   File: BlockFactory.java   View source code 6 votes vote down vote up
public void createRoundRectangle(PdfContentByte cb, Block block ){
	PdfDocument request =  getPdfDocument(block);
	float[] positions = getBoundsInPs(block);
	float[] mmPositions = getBoundsInMMIncludeCutmark(block);
	PdfTemplate tp = cb.createTemplate(positions[2],positions[3]);

	tp.roundRectangle(
			0, 
			0, 
			positions[2], 
			positions[3], 
			SizeFactory.millimetersToPostscriptPoints( block.getRadius() )
	);
	
	
	
	
	// because pdf i calculated from bottom up
	cb.addTemplate(
			tp, 
			positions[0], 
			SizeFactory.millimetersToPostscriptPoints( request.getSize()[1] - ( mmPositions[1] + mmPositions[3]))
	);

}
 
Example 10
Project: pdf-renderer   File: Line.java   View source code 6 votes vote down vote up
@Override
public void onRender(PdfContentByte cb) throws PdfRenderException {
	
	Integer[] pageSizes = getPage().getPdfDocument().getSize();
	float[] pos = getPosition();
	float[] moveTo = getMoveTo();
	cb.setLineWidth( getThickness() );
	cb.setColorStroke(  getBaseColor() );		
	float y1 = pageSizes[1] + SizeFactory.CUT_MARK - pos[1]; // seams strange but pdf starts bottom and up.
	float y2 = pageSizes[1] + SizeFactory.CUT_MARK - moveTo[1];
	// x , y. y is backward in pdf so start pos is the entire page height
	cb.moveTo( SizeFactory.millimetersToPostscriptPoints( pos[0] + SizeFactory.CUT_MARK ) , SizeFactory.millimetersToPostscriptPoints( y1 ) );
	cb.lineTo( SizeFactory.millimetersToPostscriptPoints(  moveTo[0] + SizeFactory.CUT_MARK ) , SizeFactory.millimetersToPostscriptPoints( y2 ) );
	cb.stroke();
	
}
 
Example 11
Project: ephesoft   File: PDFUtil.java   View source code 6 votes vote down vote up
/**
 * The <code>closePassedStream</code> method closes the stream passed.
 * 
 * @param reader {@link PdfReader}
 * @param document {@link Document}
 * @param contentByte {@link PdfContentByte}
 * @param writer {@link PdfWriter}
 * @param fileInputStream {@link FileInputStream}
 * @param fileOutputStream {@link FileOutputStream}
 * @throws IOException {@link} if unable to close input or output stream
 */
private static void closePassedStream(final PdfReader reader, final Document document,
		final PdfContentByte contentByte, final PdfWriter writer,
		final FileInputStream fileInputStream, final FileOutputStream fileOutputStream) throws IOException {
	if (null != reader) {
		reader.close();
	} 
	if (null != document) {
		document.close();
	}
	if (null != contentByte) {
		contentByte.closePath();
	}
	if (null != writer) {
		writer.close();
	}
	if (null != fileInputStream) {
		fileInputStream.close();
	}
	
	if (null != fileOutputStream) {
		fileOutputStream.flush();
		fileOutputStream.close();
	}
}
 
Example 12
Project: testarea-itext5   File: Abstract2DPdfPageSplittingTool.java   View source code 6 votes vote down vote up
void split(PdfReader reader, int page) throws IOException
{
    PdfImportedPage importedPage = writer.getImportedPage(reader, page);

    Rectangle pageSizeToImport = reader.getPageSize(page);
    Iterable<Rectangle> rectangles = determineSplitRectangles(reader, page);

    for (Rectangle rectangle : rectangles) {
        newPage(rectangle);
        PdfContentByte directContent = writer.getDirectContent();
        directContent.saveState();
        directContent.rectangle(rectangle.getLeft(), rectangle.getBottom(), rectangle.getWidth(), rectangle.getHeight());
        directContent.clip();
        directContent.newPath();

        writer.getDirectContent().addTemplate(importedPage, -pageSizeToImport.getLeft(), -pageSizeToImport.getBottom());

        directContent.restoreState();
    }
}
 
Example 13
Project: testarea-itext5   File: PercentileCellBackground.java   View source code 6 votes vote down vote up
@Override
    public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
        PdfContentByte canvas = canvases[PdfPTable.BACKGROUNDCANVAS];

        float xTransition = position.getLeft() + (position.getRight() - position.getLeft()) * (percent/100.0f);
        float yTransition = (position.getTop() + position.getBottom()) / 2f;
        float radius = (position.getRight() - position.getLeft()) * 0.025f;
        PdfShading axial = PdfShading.simpleAxial(canvas.getPdfWriter(),
                xTransition - radius, yTransition, xTransition + radius, yTransition, leftColor, rightColor);
        PdfShadingPattern shading = new PdfShadingPattern(axial);

        canvas.saveState();
        canvas.setShadingFill(shading);
        canvas.rectangle(position.getLeft(), position.getBottom(), position.getWidth(), position.getHeight());
//        canvas.clip();
        canvas.fill();
        canvas.restoreState();
    }
 
Example 14
Project: testarea-itext5   File: StampColoredText.java   View source code 6 votes vote down vote up
/**
 * The OP's original code transformed into Java
 */
void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setColorFill(new BaseColor(255,200,200));
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example 15
Project: testarea-itext5   File: StampColoredText.java   View source code 6 votes vote down vote up
/**
 * The OP's code transformed into Java changed with the work-around.
 */
void stampTextChanged(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.setColorFill(new BaseColor(255,200,200));
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example 16
Project: testarea-itext5   File: StampUnicodeText.java   View source code 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0">
 * sampleOriginal.pdf
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader. With a different starting file, though, it doesn't, cf.
 * {@link #testAddUnicodeStampEg_01()}.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testAddUnicodeStampSampleOriginal() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("sampleOriginal.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "sampleOriginal-unicodeStamp.pdf"))  )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfContentByte cb = stamper.getOverContent(1);

        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0);
        
        stamper.close();
    }
}
 
Example 17
Project: testarea-itext5   File: StampUnicodeText.java   View source code 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0">
 * sampleOriginal.pdf
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With
 * a different starting file, though, it doesn't as this test shows.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testAddUnicodeStampEg_01() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("eg_01.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "eg_01-unicodeStamp.pdf"))  )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);

        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfContentByte cb = stamper.getOverContent(1);

        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0);
        
        stamper.close();
    }
}
 
Example 18
Project: testarea-itext5   File: AddField.java   View source code 6 votes vote down vote up
public void cellLayout(PdfPCell cell, Rectangle position,
                               PdfContentByte[] canvases) {
            PdfWriter writer = canvases[0].getPdfWriter();
            float x = position.getLeft();
            float y = position.getBottom();
            Rectangle rect = new Rectangle(x-5, y-5, x+5, y+5);
            RadioCheckField checkbox = new RadioCheckField(
                    writer, rect, name, "Yes");
            checkbox.setCheckType(RadioCheckField.TYPE_CROSS);
            checkbox.setChecked(check);
// change: set border color
            checkbox.setBorderColor(BaseColor.BLACK);

            try {
                pdfStamper.addAnnotation(checkbox.getCheckField(), page);
            } catch (Exception e) {
                throw new ExceptionConverter(e);
            }
        }
 
Example 19
Project: testarea-itext5   File: AppearanceAndRotation.java   View source code 6 votes vote down vote up
PdfAnnotation createAnnotation(PdfWriter writer, Rectangle rect, String contents) throws DocumentException, IOException {
    PdfContentByte cb = writer.getDirectContent();
    PdfAppearance cs = cb.createAppearance(rect.getWidth(), rect.getHeight());

    cs.rectangle(0 , 0, rect.getWidth(), rect.getHeight());
    cs.fill();

    cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12);                        
    cs.beginText();
    cs.setLeading(12 + 1.75f);
    cs.moveText(.75f, rect.getHeight() - 12 + .75f);
    cs.showText(contents);
    cs.endText();

    return PdfAnnotation.createFreeText(writer, rect, contents, cs);
}
 
Example 20
Project: testarea-itext5   File: DrawGradient.java   View source code 6 votes vote down vote up
private static void drawSexyTriangle(PdfWriter writer, boolean rotated)
{
    PdfContentByte canvas = writer.getDirectContent();
    float x = 36;
    float y = 400;
    float side = 70;
    PdfShading axial = rotated ?
            PdfShading.simpleAxial(writer, PageSize.A4.getRight() - y, x, PageSize.A4.getRight() - y, x + side, BaseColor.PINK, BaseColor.BLUE)
            : PdfShading.simpleAxial(writer, x, y, x + side, y, BaseColor.PINK, BaseColor.BLUE);
    PdfShadingPattern shading = new PdfShadingPattern(axial);
    canvas.setShadingFill(shading);
    canvas.moveTo(x,y);
    canvas.lineTo(x + side, y);
    canvas.lineTo(x + (side / 2), (float)(y + (side * Math.sin(Math.PI / 3))));
    canvas.closePathFillStroke();
}
 
Example 21
Project: testarea-itext5   File: UseMillimeters.java   View source code 6 votes vote down vote up
private static void createRectangle(PdfWriter writer, float x, float y, float width, float height, BaseColor color)
{
    float posX = Utilities.millimetersToPoints(x);
    float posY = Utilities.millimetersToPoints(y);

    float widthX = Utilities.millimetersToPoints(width + x);
    float heightY = Utilities.millimetersToPoints(height + y);

    Rectangle rectangle = new Rectangle(posX, posY, widthX, heightY);

    PdfContentByte canvas = writer.getDirectContent();
    rectangle.setBorder(Rectangle.BOX);
    rectangle.setBorderWidth(1);
    rectangle.setBorderColor(color);
    canvas.rectangle(rectangle);
}
 
Example 22
Project: testarea-itext5   File: HideContent.java   View source code 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43870545/filling-a-pdf-with-itextsharp-and-then-hiding-the-base-layer">
 * Filling a PDF with iTextsharp and then hiding the base layer
 * </a>
 * <p>
 * This test shows how to cover all content using a white rectangle.
 * </p>
 */
@Test
public void testHideContenUnderRectangle() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-hiddenContent.pdf")))
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, result);
        for (int page = 1; page <= pdfReader.getNumberOfPages(); page++)
        {
            Rectangle pageSize = pdfReader.getPageSize(page);
            PdfContentByte canvas = pdfStamper.getOverContent(page);
            canvas.setColorFill(BaseColor.WHITE);
            canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight());
            canvas.fill();
        }
        pdfStamper.close();
    }
}
 
Example 23
Project: testarea-itext5   File: AddRotatedImage.java   View source code 6 votes vote down vote up
void addRotatedImage(PdfContentByte contentByte, Image image, float x, float y, float width, float height, float rotation) throws DocumentException
{
    // Draw image at x,y without rotation
    contentByte.addImage(image, width, 0, 0, height, x, y);

    // Draw image as if the previous image was rotated around its center
    // Image starts out being 1x1 with origin in lower left
    // Move origin to center of image
    AffineTransform A = AffineTransform.getTranslateInstance(-0.5, -0.5);
    // Stretch it to its dimensions
    AffineTransform B = AffineTransform.getScaleInstance(width, height);
    // Rotate it
    AffineTransform C = AffineTransform.getRotateInstance(rotation);
    // Move it to have the same center as above
    AffineTransform D = AffineTransform.getTranslateInstance(x + width/2, y + height/2);
    // Concatenate
    AffineTransform M = (AffineTransform) A.clone();
    M.preConcatenate(B);
    M.preConcatenate(C);
    M.preConcatenate(D);
    //Draw
    contentByte.addImage(image, M);
}
 
Example 24
Project: testarea-itext5   File: TextLocationExtraction.java   View source code 6 votes vote down vote up
void mark(InputStream input, OutputStream output, Pattern pattern) throws DocumentException, IOException
{
    PdfReader reader = new PdfReader(input);
    PdfStamper stamper = new PdfStamper(reader, output);
    try {
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        for (int pageNr = 1; pageNr <= reader.getNumberOfPages(); pageNr++)
        {
            SearchTextLocationExtractionStrategy strategy = new SearchTextLocationExtractionStrategy(pattern);
            parser.processContent(pageNr, strategy, Collections.emptyMap()).getResultantText();
            Collection<TextRectangle> locations = strategy.getLocations(null);
            if (locations.isEmpty())
                continue;

            PdfContentByte canvas = stamper.getOverContent(pageNr);
            canvas.setRGBColorStroke(255, 255, 0);
            for (TextRectangle location : locations)
            {
                canvas.rectangle(location.getMinX(), location.getMinY(), location.getWidth(), location.getHeight());
            }
            canvas.stroke();
        }
        stamper.close();
    } finally {
        reader.close();
    }
}
 
Example 25
Project: testarea-itext5   File: SimpleRedactionTest.java   View source code 6 votes vote down vote up
static byte[] createRotatedImagePdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    PdfContentByte directContent = writer.getDirectContent();

    BufferedImage bim = new BufferedImage(1000, 250, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    directContent.addImage(image, 0, 500, -500, 0, 550, 50);

    document.close();

    return baos.toByteArray();
}
 
Example 26
Project: testarea-itext5   File: StampInLayer.java   View source code 6 votes vote down vote up
public static byte[] stampLayer(InputStream _pdfFile, Image iImage, int x, int y, String layername, boolean readLayers) throws IOException, DocumentException
{
    PdfReader reader = new PdfReader(_pdfFile);

    try (   ByteArrayOutputStream ms = new ByteArrayOutputStream()  )
    {
        PdfStamper stamper = new PdfStamper(reader, ms);
        //Don't delete otherwise the stamper flattens the layers
        if (readLayers)
            stamper.getPdfLayers();

        PdfLayer logoLayer = new PdfLayer(layername, stamper.getWriter());
        PdfContentByte cb = stamper.getUnderContent(1);
        cb.beginLayer(logoLayer);

        //300dpi
        iImage.scalePercent(24f);
        iImage.setAbsolutePosition(x, y);
        cb.addImage(iImage);

        cb.endLayer();
        stamper.close();

        return (ms.toByteArray());
    }
}
 
Example 27
Project: tellervo   File: PageNumbersWatermark.java   View source code 6 votes vote down vote up
/**
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
public void onStartPage(PdfWriter writer, Document document) {
    if (writer.getPageNumber() < 3) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.setColorFill(BaseColor.PINK);
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        cb.showTextAligned(Element.ALIGN_CENTER, "My Watermark Under " + writer.getPageNumber(), document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
}
 
Example 28
Project: tellervo   File: RecordCard.java   View source code 6 votes vote down vote up
/**
 * Create a series bar code for this series
 * 
 * @return Image 
 */
private static Image getBarCode(PdfContentByte cb, TridasSample s)
{
	UUID uuid = UUID.fromString(s.getIdentifier().getValue());
	LabBarcode barcode = new LabBarcode(LabBarcode.Type.SAMPLE, uuid);

	barcode.setX(1.0f);
	//barcode.setN(0.5f);
	//barcode.setSize(6f);
	barcode.setFont(null);
	//barcode.setBaseline(8f);
	barcode.setBarHeight(20f);
	
	
	Image image = barcode.createImageWithBarcode(cb, null, null);

	return image;

}
 
Example 29
Project: ScreePainter   File: PDFExporter.java   View source code 6 votes vote down vote up
/**
 * Writes commands to stroke and / or fill the last geometry.
 */
private void writeFillStroke(VectorSymbol symbol, boolean close, PdfContentByte cb) {
    if (symbol == null) {
        return;
    }

    final boolean fill = symbol.isFilled();
    final boolean stroke = symbol.isStroked();

    if (fill && stroke) {
        cb.fillStroke();
    } else if (fill) {
        cb.fill();
    } else if (stroke) {
        cb.stroke();
    } else // nothing: invisible element
        ;
}
 
Example 30
Project: weplantaforest   File: PdfCertificateView.java   View source code 6 votes vote down vote up
public void writePdfDataToOutputStream(OutputStream toWrite, final int treeCount, final String text, final String name, final String number, String imagePath) throws Exception {
    // create pdf
    final Document doc = new Document();
    final PdfWriter pdfWriter = PdfWriter.getInstance(doc, toWrite);
    pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);

    final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), Locale.GERMAN);
    cal.setTimeInMillis(System.currentTimeMillis());
    final String date = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.YEAR);

    _imagePath = imagePath;

    doc.open();

    PdfContentByte cb = pdfWriter.getDirectContent();
    PdfHelper.createHeaderBlock(cb,1,1);
    PdfHelper.createCircleAndText(cb, "Zertifikat", 298f, 665f, 75f, textFontForCircle, 0x9E, 0x3C, 0x59);
    createTreeCountAndCustomTextBlock(cb, text, treeCount);
    createLawTextDateAndSignatureBlock(cb, number, date);
    pdfHelper.addLogo(cb, imagePath, 262f, 20f);

    doc.close();
}
 
Example 31
Project: weplantaforest   File: PdfCertificateView2.java   View source code 6 votes vote down vote up
public void writePdfDataToOutputStream(OutputStream toWrite, final int treeCount, final String text, final String name, final String number, String imagePath) throws Exception {
    // create pdf
    final Document doc = new Document();
    final PdfWriter pdfWriter = PdfWriter.getInstance(doc, toWrite);
    pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);

    final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), Locale.GERMAN);
    cal.setTimeInMillis(System.currentTimeMillis());
    final String date = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.YEAR);

    _imagePath = imagePath;

    doc.open();

    PdfContentByte cb = pdfWriter.getDirectContent();
    PdfHelper.createHeaderBlock(cb,1,1);
    PdfHelper.createCircleAndText(cb, "Zertifikat", 298f, 665f, 75f, textFontForCircle, 0x9E, 0x3C, 0x59);
    createTreeCountAndCustomTextBlock(cb, text, treeCount);
    createLawTextDateAndSignatureBlock(cb, number, date);
    pdfHelper.addLogo(cb, _imagePath, 262f, 20f);

    doc.close();
}
 
Example 32
Project: weplantaforest   File: PdfReceiptView.java   View source code 6 votes vote down vote up
private void createReceiptHeaderAndTextBelow(PdfContentByte cb) throws DocumentException {
    PdfPTable headerTable = new PdfPTable(1);
    float[] rows = { 450f };
    headerTable.setTotalWidth(rows);
    headerTable.getDefaultCell()
               .setBorder(Rectangle.NO_BORDER);

    headerTable.addCell(new Phrase(new Chunk("Bestätigung über Geldzuwendungen", textFontForReceiptHeader)));

    headerTable.writeSelectedRows(0, 1, 75f, 625, cb);

    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(rows);
    table.getDefaultCell()
         .setBorder(Rectangle.NO_BORDER);
    table.getDefaultCell()
         .setLeading(8f, 0);

    table.addCell(new Phrase(new Chunk("im Sinne des §10b des Einkommensteuergesetzes", textFont)));
    table.addCell(new Phrase(new Chunk("an eine der in §5 Abs. 1 Nr. 9 des Körperschaftsteuergesetzes bezeichneten", textFont)));
    table.addCell(new Phrase(new Chunk("Körperschaften, Personenvereinigungen oder Vermögensmassen", textFont)));

    table.writeSelectedRows(0, 3, 75f, 590, cb);
}
 
Example 33
Project: weplantaforest   File: PdfReceiptView.java   View source code 6 votes vote down vote up
private PdfPTable createPriceTable(PdfContentByte cb, Receipt receipt) throws DocumentException {
    PdfPTable tableForPrices = new PdfPTable(1);
    float[] rowForTotalPrice = { 250f };
    tableForPrices.setTotalWidth(rowForTotalPrice);
    tableForPrices.getDefaultCell()
                  .setBorder(Rectangle.NO_BORDER);

    tableForPrices.addCell(new Phrase(new Chunk("Betrag der Zuwendung in Ziffern:", textFont)));
    tableForPrices.addCell(new Phrase(new Chunk(" ", textFont)));
    Double totalPrice = 0.0;
    for (final Cart cart : receipt.getCarts()) {
        tableForPrices.addCell(new Phrase(new Chunk(cart.getTotalPrice()
                                                        .toString()
                + " €", textFontUserData)));
        totalPrice += cart.getTotalPrice()
                          .doubleValue();
    }
    String formattedPrice = priceFormat.format(totalPrice)
                                       .toString();
    tableForPrices.addCell(new Phrase(new Chunk("Gesamt: " + formattedPrice + " €", textFontUserData)));
    return tableForPrices;
}
 
Example 34
Project: weplantaforest   File: PdfReceiptView.java   View source code 6 votes vote down vote up
private PdfPTable createDateTable(PdfContentByte cb, Receipt receipt) throws DocumentException {
    PdfPTable tableForDate = new PdfPTable(1);
    float[] rowForDate = { 110f };
    tableForDate.setTotalWidth(rowForDate);
    tableForDate.getDefaultCell()
                .setBorder(Rectangle.NO_BORDER);

    tableForDate.addCell(new Phrase(new Chunk("Datum der Zuwendung:", textFont)));
    tableForDate.addCell(new Phrase(new Chunk(" ", textFont)));
    final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), Locale.GERMAN);
    for (final Cart cart : receipt.getCarts()) {
        cal.setTimeInMillis(cart.getTimeStamp());
        final String date = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.YEAR);
        PdfPCell cell = new PdfPCell(new Phrase(new Chunk(date, textFontUserData)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setBorder(PdfPCell.NO_BORDER);
        tableForDate.addCell(cell);
    }
    return tableForDate;
}
 
Example 35
Project: weplantaforest   File: PdfHelper.java   View source code 6 votes vote down vote up
public static void createCircleAndText(PdfContentByte cb, String text, float xCoord, float yCoord, float radius, Font textFont, int circleColorRed, int circleColorGreen, int circleColorBlue)
        throws DocumentException, IOException {
    cb.saveState();
    cb.setRGBColorFill(circleColorRed, circleColorGreen, circleColorBlue);
    cb.circle(xCoord, yCoord, radius);
    cb.fill();
    cb.stroke();
    cb.restoreState();

    PdfPTable table = new PdfPTable(1);
    float[] rows = { 595f };
    table.setTotalWidth(rows);
    table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.getDefaultCell().setFixedHeight(radius * 2);
    table.addCell(new Phrase(new Chunk(text, textFont)));
    table.writeSelectedRows(0, 1, 0, yCoord + radius, cb);
}
 
Example 36
Project: pharmacogenomics   File: PGXPDFExporter.java   View source code 6 votes vote down vote up
/**
 * Create the multipage PDF report from the internal list of JPanels.
 * @throws DocumentException 
 */
public void createMultipagePDF() throws DocumentException {
	// Document defaults to A4, so specify the current dimensions
	Document doc= new Document(new Rectangle(pageWidth, pageHeight));
	PdfWriter writer= PdfWriter.getInstance(doc, os);
	doc.open();
	PdfContentByte cb= writer.getDirectContent();
	
	// Iterate over tabs
	for (int i= 0; i != tabs.getTabCount(); ++i) {
		JPanel jp= (JPanel) tabs.getComponent(i);
		// Iterate over pages
		for (int currentPage= 0; currentPage < getNumPages(jp); ++currentPage) {
			doc.newPage(); // not needed for page 1, needed for >1

			PdfTemplate template= cb.createTemplate(pageWidth, pageHeight);
			Graphics2D g2d= new PdfGraphics2D(template, pageWidth, pageHeight * (currentPage + 1));
			jp.printAll(g2d);
			g2d.dispose();

			cb.addTemplate(template, 0, 0);
		}
	}
	
	doc.close();
}
 
Example 37
Project: mica2   File: PdfUtils.java   View source code 6 votes vote down vote up
public static void addImage(byte[] input, OutputStream output, Image image, String placeholder)
  throws IOException, DocumentException {
  try (PdfReaderAutoclosable pdfReader = new PdfReaderAutoclosable(input);
       PdfStamperAutoclosable pdfStamper = new PdfStamperAutoclosable(pdfReader, output)) {
    AcroFields form = pdfStamper.getAcroFields();
    List<AcroFields.FieldPosition> positions = form.getFieldPositions(placeholder);

    positions.forEach(p -> {
      image.scaleToFit(p.position.getWidth(), p.position.getHeight());
      image.setAbsolutePosition(p.position.getLeft() + (p.position.getWidth() - image.getScaledWidth()) / 2,
        p.position.getBottom() + (p.position.getHeight() - image.getScaledHeight()) / 2);
      PdfContentByte cb = pdfStamper.getOverContent(p.page);

      try {
        cb.addImage(image);
      } catch(DocumentException e) {
        throw Throwables.propagate(e);
      }
    });
  }
}
 
Example 38
Project: gutenberg   File: PercentBackgroundEvent.java   View source code 6 votes vote down vote up
@Override
public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvas) {
    BaseColor color = colorProviders.apply(percent);
    if (color != null) {
        PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];
        cb.saveState();
        cb.setColorFill(color);
        cb.rectangle(
                rect.getLeft() + margin.marginLeft,
                rect.getBottom() + margin.marginBottom,
                rect.getWidth() * percent - (margin.marginLeft + margin.marginRight),
                rect.getHeight() - (margin.marginTop + margin.marginBottom));
        cb.fill();
        cb.restoreState();
    }
}
 
Example 39
Project: gutenberg   File: PygmentsAdapter.java   View source code 6 votes vote down vote up
public void tableLayout(PdfPTable table, float[][] width, float[] height,
                        int headerRows, int rowStart, PdfContentByte[] canvas) {
    // because table is only one cell length, one can focus on using the first width
    float xmin = width[0][0];
    float xmax = width[0][1];
    float ymin = height[height.length - 1];
    float ymax = height[0];
    float d = 3;

    PdfContentByte background = canvas[PdfPTable.BASECANVAS];
    background.saveState();
    background.setColorFill(backgroundColor);
    background.roundRectangle(
            xmin - d,
            ymin - d,
            (xmax + d) - (xmin - d),
            (ymax + d) - (ymin - d),
            d + d);
    background.fill();
    background.restoreState();
}
 
Example 40
Project: gutenberg   File: HeaderFooter.java   View source code 6 votes vote down vote up
public void drawFooter(PdfContentByte canvas, PageInfos pageInfos) {
    if (pageInfos.getRawPageNumber() == 1 && !footerOnFirstPage)
        return;

    if (drawLine) {
        BaseColor lineColor = styles.getColorOrDefault(HEADER_LINE_COLOR);
        canvas.saveState();
        canvas.setColorStroke(lineColor);
        canvas.setLineWidth(1.2f);
        canvas.moveTo(rect.getLeft(), rect.getBottom() - 6);
        canvas.lineTo(rect.getRight(), rect.getBottom() - 6);
        canvas.stroke();
        canvas.restoreState();
    }

    float bottom = rect.getBottom() - 20;
    Phrase footer = footerText(pageInfos);
    if (footer != null) {
        showTextAligned(canvas, Element.ALIGN_LEFT, footer, rect.getLeft(), bottom, 0);
    }

    Font footerFont = styles.getFontOrDefault(FOOTER_FONT);

    Phrase page = new Phrase(pageInfos.getFormattedPageNumber(), footerFont);
    showTextAligned(canvas, Element.ALIGN_RIGHT, page, rect.getRight(), bottom, 0);
}