Java Code Examples for com.itextpdf.text.Rectangle#getBottom()

The following examples show how to use com.itextpdf.text.Rectangle#getBottom() . 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: VeryDenseMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 8 votes vote down vote up
static byte[] createSimpleCircleGraphicsPdf(int radius, int gap, int count) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    float y = writer.getPageSize().getTop();
    for (int i = 0; i < count; i++)
    {
        Rectangle pageSize = writer.getPageSize();
        if (y <= pageSize.getBottom() + 2*radius)
        {
            y = pageSize.getTop();
            writer.getDirectContent().fillStroke();
            document.newPage();
        }
        writer.getDirectContent().circle(pageSize.getLeft() + pageSize.getWidth() * Math.random(), y-radius, radius);
        y-= 2*radius + gap;
    }
    writer.getDirectContent().fillStroke();
    document.close();

    return baos.toByteArray();
}
 
Example 2
Source File: PercentileCellBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 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 3
Source File: AddField.java    From testarea-itext5 with GNU Affero General Public License v3.0 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 4
Source File: SplitPages.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46466747/how-to-split-a-pdf-page-in-java">
 * How to split a PDF page in java?
 * </a>
 * <p>
 * This test shows how to split the pages of a document into tiles of A6
 * size using the {@link Abstract2DPdfPageSplittingTool}.
 * </p>
 */
@Test
public void testSplitDocumentA6() throws IOException, DocumentException {
    try (InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-A6.pdf"))) {
        Abstract2DPdfPageSplittingTool tool = new Abstract2DPdfPageSplittingTool() {
            @Override
            protected Iterable<Rectangle> determineSplitRectangles(PdfReader reader, int page) {
                Rectangle targetSize = PageSize.A6;
                List<Rectangle> rectangles = new ArrayList<>();
                Rectangle pageSize = reader.getPageSize(page);
                for (float y = pageSize.getTop(); y > pageSize.getBottom() + 5; y-=targetSize.getHeight()) {
                    for (float x = pageSize.getLeft(); x < pageSize.getRight() - 5; x+=targetSize.getWidth()) {
                        rectangles.add(new Rectangle(x, y - targetSize.getHeight(), x + targetSize.getWidth(), y));
                    }
                }
                return rectangles;
            }
        };
        tool.split(result, new PdfReader(resource));
    }
}
 
Example 5
Source File: PdfCleanUpRegionFilter.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
private Point2D[] getVertices(Rectangle rect) {
    Point2D[] points = {
            new Point2D.Double(rect.getLeft(), rect.getBottom()),
            new Point2D.Double(rect.getRight(), rect.getBottom()),
            new Point2D.Double(rect.getRight(), rect.getTop()),
            new Point2D.Double(rect.getLeft(), rect.getTop())
    };

    return points;
}
 
Example 6
Source File: StrictPdfCleanUpRegionFilter.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Checks if the text is COMPLETELY inside render filter region.
 */
@Override
public boolean allowText(TextRenderInfo renderInfo) {
    LineSegment ascent = renderInfo.getAscentLine();
    LineSegment descent = renderInfo.getDescentLine();

    Point2D[] glyphRect = new Point2D[] {
            new Point2D.Float(ascent.getStartPoint().get(0), ascent.getStartPoint().get(1)),
            new Point2D.Float(ascent.getEndPoint().get(0), ascent.getEndPoint().get(1)),
            new Point2D.Float(descent.getEndPoint().get(0), descent.getEndPoint().get(1)),
            new Point2D.Float(descent.getStartPoint().get(0), descent.getStartPoint().get(1)),
    };

    for (Rectangle rectangle : rectangles)
    {
        boolean glyphInRectangle = true;
        for (Point2D point2d : glyphRect)
        {
            glyphInRectangle &= rectangle.getLeft() <= point2d.getX();
            glyphInRectangle &= point2d.getX() <= rectangle.getRight();
            glyphInRectangle &= rectangle.getBottom() <= point2d.getY();
            glyphInRectangle &= point2d.getY() <= rectangle.getTop();
        }
        if (glyphInRectangle)
            return false;
    }

    return true;
}
 
Example 7
Source File: TableKeepTogether.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
private void printPage3(Document document, PdfContentByte canvas) throws DocumentException {
    int cols = 3;
    int rows = 15;

    PdfPTable table = new PdfPTable(cols);
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            table.addCell(new Phrase("Cell " + row + ", " + col));
        }
    }
    table.setSpacingBefore(5);

    Rectangle docBounds = document.getPageSize();
    Rectangle upper = new Rectangle(docBounds.getLeft(20), docBounds.getTop(20) - 200, docBounds.getRight(20), docBounds.getTop(20));
    upper.setBackgroundColor(new BaseColor(23, 142, 255, 20));
    Rectangle lower = new Rectangle(docBounds.getLeft(20), docBounds.getBottom(20), docBounds.getRight(20), docBounds.getBottom(20) + 600);
    lower.setBackgroundColor(new BaseColor(255, 142, 23, 20));
    Rectangle[] rectangles = new Rectangle[] { upper, lower };

    for (Rectangle bounds : rectangles)
    {
        bounds.setBorder(Rectangle.BOX);
        bounds.setBorderColor(BaseColor.BLACK);
        bounds.setBorderWidth(1);

        canvas.rectangle(bounds);
    }

    rectangles = drawKeepTogether(new Paragraph("This table should keep together!"), canvas, rectangles);
    rectangles = drawKeepTogether(table, canvas, rectangles);
}
 
Example 8
Source File: SplitIntoHalfPages.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This methods creates a copy of the source document containing each page twice,
 * once with the cropbox limited to the left half page, once to the right one.
 */
void splitIntoHalfPages(InputStream source, File target) throws IOException, DocumentException
{
    final PdfReader reader = new PdfReader(source);
    
    try (   OutputStream targetStream = new FileOutputStream(target)    )
    {
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, targetStream);
        document.open();

        for (int page = 1; page <= reader.getNumberOfPages(); page++)
        {
            PdfDictionary pageN = reader.getPageN(page);
            Rectangle cropBox = reader.getCropBox(page);
            PdfArray leftBox = new PdfArray(new float[]{cropBox.getLeft(), cropBox.getBottom(), (cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getTop()});
            PdfArray rightBox = new PdfArray(new float[]{(cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getBottom(), cropBox.getRight(), cropBox.getTop()});

            PdfImportedPage importedPage = copy.getImportedPage(reader, page);
            pageN.put(PdfName.CROPBOX, leftBox);
            copy.addPage(importedPage);
            pageN.put(PdfName.CROPBOX, rightBox);
            copy.addPage(importedPage);
        }
        
        document.close();
    }
    finally
    {
        reader.close();
    }
}
 
Example 9
Source File: UnifiedPagesizeMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
Rectangle centerIn(Rectangle source, int rotation, float width, float height)
{
    if (rotation % 180 != 0)
    {
        float temp = height;
        height = width;
        width = temp;
    }

    float halfWidthToRemove = (source.getWidth() - width) / 2.0f;
    float halfHeightToRemove = (source.getHeight() - height) / 2.0f;
    return new Rectangle(source.getLeft(halfWidthToRemove), source.getBottom(halfHeightToRemove),
            source.getRight(halfWidthToRemove), source.getTop(halfHeightToRemove));
}
 
Example 10
Source File: UnifiedPagesizeMerging.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
Rectangle enhanceBy(Rectangle source, Rectangle addition)
{
    Rectangle result = new Rectangle(source);
    if (addition.getLeft() < result.getLeft())
        result.setLeft(addition.getLeft());
    if (addition.getRight() > result.getRight())
        result.setRight(addition.getRight());
    if (addition.getBottom() < result.getBottom())
        result.setBottom(addition.getBottom());
    if (addition.getTop() > result.getTop())
        result.setTop(addition.getTop());
    return result;
}
 
Example 11
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
public Collection<Rectangle2D> find(PdfReader reader, float minWidth, float minHeight, int page) throws IOException
{
    Rectangle cropBox = reader.getCropBox(page);
    Rectangle2D crop = new Rectangle2D.Float(cropBox.getLeft(), cropBox.getBottom(), cropBox.getWidth(), cropBox.getHeight());
    FreeSpaceFinder finder = new FreeSpaceFinder(crop, minWidth, minHeight);
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    parser.processContent(page, finder);
    return finder.freeSpaces;
}
 
Example 12
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
public Collection<Rectangle2D> findExt(PdfReader reader, float minWidth, float minHeight, int page) throws IOException
{
    Rectangle cropBox = reader.getCropBox(page);
    Rectangle2D crop = new Rectangle2D.Float(cropBox.getLeft(), cropBox.getBottom(), cropBox.getWidth(), cropBox.getHeight());
    FreeSpaceFinder finder = new FreeSpaceFinderExt(crop, minWidth, minHeight);
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    parser.processContent(page, finder);
    return finder.freeSpaces;
}
 
Example 13
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
Point2D[] getPointsOfInterest(Rectangle box)
{
    Point2D[] result = new Point2D[6];
    result[0] = new Point2D.Float(box.getLeft(), box.getTop());
    result[1] = new Point2D.Float(box.getRight(), box.getTop());
    result[2] = new Point2D.Float(box.getRight(), (box.getTop() + box.getBottom()) / 2.0f);
    result[3] = new Point2D.Float(box.getRight(), box.getBottom());
    result[4] = new Point2D.Float(box.getLeft(), box.getBottom());
    result[5] = new Point2D.Float(box.getLeft(), (box.getTop() + box.getBottom()) / 2.0f);
    return result;
}
 
Example 14
Source File: WatermarkPdfTests.java    From kbase-doc with Apache License 2.0 4 votes vote down vote up
/**
 * pdf 用图片加水印
 * @author eko.zhan at 2018年9月2日 下午1:44:58
 * @throws FileNotFoundException
 * @throws IOException
 * @throws DocumentException
 */
@Test
public void testVisioAsPdfWithImg() throws FileNotFoundException, IOException, DocumentException{
	File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx");
	File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf");
	if (!outputFile.exists()) {
		convert(inputFile, outputFile);
	}
	File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf");
	final String IMG = "D:\\Xiaoi\\logo\\logo.png";
	//转换成 pdf 后利用 itext 加水印 
	PdfReader reader = new PdfReader(new FileInputStream(outputFile));
	PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
	int pageNo = reader.getNumberOfPages();
	// text watermark
	Font f = new Font(FontFamily.HELVETICA, 30);
	Phrase p = new Phrase("Xiaoi Robot Image", f);
	// image watermark
	Image img = Image.getInstance(IMG);
	float w = img.getScaledWidth();
	float h = img.getScaledHeight();
	// transparency
	PdfGState gs1 = new PdfGState();
	gs1.setFillOpacity(0.5f);
	// properties
	PdfContentByte over;
	Rectangle pagesize;
	float x, y;
	// loop over every page
	for (int i = 1; i <= pageNo; i++) {
		pagesize = reader.getPageSizeWithRotation(i);
		x = (pagesize.getLeft() + pagesize.getRight()) / 2;
		y = (pagesize.getTop() + pagesize.getBottom()) / 2;
		over = stamper.getOverContent(i);
		over.saveState();
		over.setGState(gs1);
		if (i % 2 == 1)
			ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 0);
		else
			over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
		over.restoreState();
	}
	stamper.close();
	reader.close();
}
 
Example 15
Source File: PDFManager.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 4 votes vote down vote up
private static boolean overlaps(Rectangle rect1, Rectangle rect2) {
    if (rect1.getLeft() >= rect2.getRight() || rect1.getRight() <= rect2.getLeft() || rect1.getTop() <= rect2.getBottom() || rect1.getBottom() >= rect2.getTop())
        return false;
    return true;
}
 
Example 16
Source File: PDFManager.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 4 votes vote down vote up
private static boolean contains(Rectangle rect1, Rectangle rect2) {
    return rect1.getLeft() <= rect2.getLeft() && rect1.getRight() >= rect2.getRight() && rect1.getBottom() <= rect2.getBottom() && rect1.getTop() >= rect2.getTop();
}