Java Code Examples for com.itextpdf.text.pdf.PdfContentByte#rectangle()

The following examples show how to use com.itextpdf.text.pdf.PdfContentByte#rectangle() . 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: Abstract2DPdfPageSplittingTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 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 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: AbstractPdfPageSplittingTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
void split(PdfReader reader, int page) throws IOException {
    PdfImportedPage importedPage = writer.getImportedPage(reader, page);
    PdfContentByte directContent = writer.getDirectContent();
    yPosition = pageSize.getTop();

    Rectangle pageSizeToImport = reader.getPageSize(page);
    float[] borderPositions = determineSplitPositions(reader, page);
    if (borderPositions == null || borderPositions.length < 2)
        return;

    for (int borderIndex = 0; borderIndex + 1 < borderPositions.length; borderIndex++) {
        float height = borderPositions[borderIndex] - borderPositions[borderIndex + 1];
        if (height <= 0)
            continue;

        directContent.saveState();
        directContent.rectangle(0, yPosition - height, pageSizeToImport.getWidth(), height);
        directContent.clip();
        directContent.newPath();

        writer.getDirectContent().addTemplate(importedPage, 0, yPosition - (borderPositions[borderIndex] - pageSizeToImport.getBottom()));

        directContent.restoreState();
        newPage();
    }
}
 
Example 4
Source File: UseMillimeters.java    From testarea-itext5 with GNU Affero General Public License v3.0 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 5
Source File: HideContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 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 6
Source File: MarkContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/50121297/missing-colored-area-on-pdf-using-itext-pdf">
 * Missing colored area on pdf using itext pdf
 * </a>
 * <p>
 * This test shows how to mark a whole table row without the
 * marking hiding the existing content or vice versa.
 * </p>
 */
@Test
public void test() throws IOException, DocumentException {
    try (   InputStream resource = getClass().getResourceAsStream("document.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-marked.pdf"))) {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(pdfReader, result);

        PdfContentByte canvas = stamper.getOverContent(1);
        canvas.saveState();
        PdfGState state = new PdfGState();
        state.setBlendMode(new PdfName("Multiply"));
        canvas.setGState(state);
        canvas.setColorFill(BaseColor.YELLOW);
        canvas.rectangle(60, 586, 477, 24);
        canvas.fill();
        canvas.restoreState();

        stamper.close();
    }
}
 
Example 7
Source File: ParagraphBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onEndPage(PdfWriter writer, Document document) {
    if (active) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.setColorFill(color);
        cb.rectangle(document.left(), document.bottom() - offset,
                document.right() - document.left(), startPosition - document.bottom());
        cb.fill();
        cb.restoreState();
    }
}
 
Example 8
Source File: ParagraphBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) {
    if (active) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.setColorFill(color);
        cb.rectangle(document.left(), paragraphPosition - offset,
                document.right() - document.left(), startPosition - paragraphPosition);
        cb.fill();
        cb.restoreState();
    }
}
 
Example 9
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 10
Source File: CreateTableDirectContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43807931/creating-table-in-pdf-on-last-page-bottom-wrong-official-solution">
 * Creating table in pdf on last page bottom (wrong official solution)
 * </a>
 * <p>
 * Indeed, there is an error in the official sample which effectively
 * applies the margins twice.
 * </p>
 */
@Test
public void testCreateTableLikeUser7968180() throws FileNotFoundException, DocumentException
{
    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(new File(RESULT_FOLDER, "calendarUser7968180.pdf")));
    document.open();

    PdfPTable datatable = null;//createHeaderTable();
    //document.add(datatable);
    datatable = createFooterTable();

    drawTableAtTheEndOfPage(document, writer, datatable);

    // Marking the border
    PdfContentByte canvas = writer.getDirectContentUnder();
    canvas.setColorStroke(BaseColor.RED);
    canvas.setColorFill(BaseColor.PINK);
    canvas.rectangle(document.left(), document.bottom(), document.right() - document.left(), document.top() - document.bottom());
    Rectangle pageSize = document.getPageSize(); 
    canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight());
    canvas.eoFillStroke();

    document.close();
    System.out.println("done");
}
 
Example 11
Source File: TextLocationExtraction.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 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 12
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
void enhance(PdfContentByte page, Collection<Rectangle2D> rectangles)
{
    for (Rectangle2D rectangle : rectangles)
    {
        page.setColorStroke(pickColor());
        page.rectangle((float) rectangle.getMinX(), (float) rectangle.getMinY(), (float) rectangle.getWidth(), (float) rectangle.getHeight());
        page.stroke();
    }
}
 
Example 13
Source File: FindFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
void enhance(PdfContentByte page, Collection<Rectangle2D> rectangles, Point2D point, BaseColor color)
{
    Rectangle2D best = null;
    double bestDist = Double.MAX_VALUE;

    for (Rectangle2D rectangle : rectangles)
    {
        double distance = distance(rectangle, point);
        if (distance < bestDist)
        {
            best = rectangle;
            bestDist = distance;
        }
    }

    if (best != null)
    {
        page.setColorFill(color);
        page.rectangle((float) best.getMinX(), (float) best.getMinY(), (float) best.getWidth(), (float) best.getHeight());
        page.fill();
        System.out.printf("    Best rectangle for %7.3f, %7.3f is %7.3f, %7.3f, %7.3f, %7.3f\n", point.getX(), point.getY(), best.getMinX(),
                best.getMinY(), best.getWidth(), best.getHeight());
    }
    else
    {
        System.err.printf("!!! No best rectangle for %7.3f, %7.3f\n", point.getX(), point.getY());
    }
}
 
Example 14
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static byte[] createSimplePatternPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    PdfContentByte directContent = writer.getDirectContent();
    Rectangle pageSuze = document.getPageSize();
    
    PdfPatternPainter painter = directContent.createPattern(200, 150);
    painter.setColorStroke(BaseColor.GREEN);
    painter.beginText();
    painter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_STROKE);
    painter.setTextMatrix(AffineTransform.getTranslateInstance(0, 50));
    painter.setFontAndSize(BaseFont.createFont(), 100);
    painter.showText("Test");
    painter.endText();

    directContent.setColorFill(new PatternColor(painter));
    directContent.rectangle(pageSuze.getLeft(), pageSuze.getBottom(), pageSuze.getWidth(), pageSuze.getHeight());
    directContent.fill();

    document.close();

    return baos.toByteArray();
}
 
Example 15
Source File: PdfVeryDenseMergeTool.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
void merge(PdfReader reader, PdfReaderContentParser parser, int page) throws IOException
{
    PdfImportedPage importedPage = writer.getImportedPage(reader, page);
    PdfContentByte directContent = writer.getDirectContent();
    
    PageVerticalAnalyzer finder = parser.processContent(page, new PageVerticalAnalyzer());
    if (finder.verticalFlips.size() < 2)
        return;
    Rectangle pageSizeToImport = reader.getPageSize(page);

    int startFlip = finder.verticalFlips.size() - 1;
    boolean first = true;
    while (startFlip > 0)
    {
        if (!first)
            newPage();

        float freeSpace = yPosition - pageSize.getBottom(bottomMargin);
        int endFlip = startFlip + 1;
        while ((endFlip > 1) && (finder.verticalFlips.get(startFlip) - finder.verticalFlips.get(endFlip - 2) < freeSpace))
            endFlip -=2;
        if (endFlip < startFlip)
        {
            float height = finder.verticalFlips.get(startFlip) - finder.verticalFlips.get(endFlip);

            directContent.saveState();
            directContent.rectangle(0, yPosition - height, pageSizeToImport.getWidth(), height);
            directContent.clip();
            directContent.newPath();

            writer.getDirectContent().addTemplate(importedPage, 0, yPosition - (finder.verticalFlips.get(startFlip) - pageSizeToImport.getBottom()));

            directContent.restoreState();
            yPosition -= height + gap;
            startFlip = endFlip - 1;
        }
        else if (!first) 
            throw new IllegalArgumentException(String.format("Page %s content sections too large.", page));
        first = false;
    }
}