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

The following examples show how to use com.itextpdf.text.Rectangle#getWidth() . 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: 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 2
Source File: ClusterCreator.java    From Briss-2.0 with GNU General Public License v3.0 6 votes vote down vote up
public static ClusterDefinition clusterPages(final File source, final PageExcludes pageExcludes) throws IOException {
    PdfReader reader = new PdfReader(source.getAbsolutePath());

    ClusterDefinition clusters = new ClusterDefinition();

    for (int page = 1; page <= reader.getNumberOfPages(); page++) {

        Rectangle layoutBox = getLayoutBox(reader, page);

        // create Cluster
        // if the pagenumber should be excluded then use it as a
        // discriminating parameter, else use default value

        boolean excluded = checkExclusionAndGetPageNumber(pageExcludes, page);

        PageCluster tmpCluster = new PageCluster(page % 2 == 0, (int) layoutBox.getWidth(), (int) layoutBox.getHeight(),
            excluded, page);

        clusters.addOrMergeCluster(tmpCluster);
    }
    reader.close();
    clusters.selectAndSetPagesForMerging();
    return clusters;
}
 
Example 3
Source File: ChartWriter.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
private Graphics2D getGraphics(ChartDimensions d) {
  if (myGraphics == null) {
    myTemplate = myWriter.getDirectContent().createTemplate(d.getFullWidth(), d.getChartHeight());
    Rectangle page = myDoc.getPageSize();
    final float width = page.getWidth() - myDoc.leftMargin() - myDoc.rightMargin();
    final float height = page.getHeight() - myDoc.bottomMargin() - myDoc.topMargin();

    final float xscale = width / d.getFullWidth();
    final float yscale = height / d.getChartHeight();
    myScale = Math.min(xscale, yscale);
    myYShift = height - d.getChartHeight() * myScale + myDoc.bottomMargin();
    myGraphics = myTemplate.createGraphics(d.getFullWidth(), d.getChartHeight(),
        myFontCache.getFontMapper(mySubstitutions, myCharset));
    myGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
  }
  return myGraphics;
}
 
Example 4
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 5
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 6
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 7
Source File: CropManager.java    From Briss-2.0 with GNU General Public License v3.0 5 votes vote down vote up
private static Rectangle calculateScaledRectangle(List<Rectangle> boxes, Float[] ratios, int rotation) {
    if (ratios == null || boxes.size() == 0)
        return null;
    Rectangle smallestBox = null;
    // find smallest box
    float smallestSquare = Float.MAX_VALUE;
    for (Rectangle box : boxes) {
        if (box != null) {
            if (smallestBox == null) {
                smallestBox = box;
            }
            if (smallestSquare > box.getWidth() * box.getHeight()) {
                // set new smallest box
                smallestSquare = box.getWidth() * box.getHeight();
                smallestBox = box;
            }
        }
    }
    if (smallestBox == null)
        return null; // no useable box was found

    // rotate the ratios according to the rotation of the page
    float[] rotRatios = rotateRatios(ratios, rotation);

    // use smallest box as basis for calculation
    Rectangle scaledBox = new Rectangle(smallestBox);

    scaledBox.setLeft(smallestBox.getLeft() + (smallestBox.getWidth() * rotRatios[0]));
    scaledBox.setBottom(smallestBox.getBottom() + (smallestBox.getHeight() * rotRatios[1]));
    scaledBox.setRight(smallestBox.getLeft() + (smallestBox.getWidth() * (1 - rotRatios[2])));
    scaledBox.setTop(smallestBox.getBottom() + (smallestBox.getHeight() * (1 - rotRatios[3])));

    return scaledBox;
}
 
Example 8
Source File: RectangleHandler.java    From Briss-2.0 with GNU General Public License v3.0 5 votes vote down vote up
public static Rectangle calculateScaledRectangle(final List<Rectangle> boxes, final Float[] ratios, final int rotation) {
    if (ratios == null || boxes.size() == 0)
        return null;
    Rectangle smallestBox = null;
    // find smallest box
    float smallestSquare = Float.MAX_VALUE;
    for (Rectangle box : boxes) {
        if (box != null) {
            if (smallestBox == null) {
                smallestBox = box;
            }
            if (smallestSquare > box.getWidth() * box.getHeight()) {
                // set new smallest box
                smallestSquare = box.getWidth() * box.getHeight();
                smallestBox = box;
            }
        }
    }
    if (smallestBox == null)
        return null; // no useable box was found

    // rotate the ratios according to the rotation of the page
    float[] rotRatios = rotateRatios(ratios, rotation);

    // use smallest box as basis for calculation
    Rectangle scaledBox = new Rectangle(smallestBox);

    scaledBox.setLeft(smallestBox.getLeft() + (smallestBox.getWidth() * rotRatios[0]));
    scaledBox.setBottom(smallestBox.getBottom() + (smallestBox.getHeight() * rotRatios[1]));
    scaledBox.setRight(smallestBox.getLeft() + (smallestBox.getWidth() * (1 - rotRatios[2])));
    scaledBox.setTop(smallestBox.getBottom() + (smallestBox.getHeight() * (1 - rotRatios[3])));

    return scaledBox;
}
 
Example 9
Source File: ClusterManager.java    From Briss-2.0 with GNU General Public License v3.0 5 votes vote down vote up
public static void clusterPages(ClusterJob clusterJob) throws IOException {
    PdfReader reader = new PdfReader(clusterJob.getSource().getAbsolutePath());

    ClusterCollection clusters = clusterJob.getClusterCollection();
    for (int page = 1; page <= reader.getNumberOfPages(); page++) {
        Rectangle layoutBox = reader.getBoxSize(page, "crop");

        if (layoutBox == null) {
            layoutBox = reader.getBoxSize(page, "media");
        }

        // create Cluster
        // if the pagenumber should be excluded then use it as a
        // discriminating parameter, else use default value

        int pageNumber = -1;
        if (clusterJob.getExcludedPageSet() != null && clusterJob.getExcludedPageSet().contains(page)) {
            pageNumber = page;
        }

        SingleCluster tmpCluster = new SingleCluster(page % 2 == 0, (int) layoutBox.getWidth(),
            (int) layoutBox.getHeight(), pageNumber);

        clusters.addPageToCluster(tmpCluster, page);
    }

    // for every cluster create a set of pages on which the preview will
    // be based
    for (SingleCluster cluster : clusters.getClusterToPagesMapping().keySet()) {
        cluster.choosePagesToMerge(clusters.getClusterToPagesMapping().get(cluster));
    }
    reader.close();
}
 
Example 10
Source File: AbstractSignatureActionExecuter.java    From CounterSign with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the X value for centering the signature stamp
 * 
 * @param r
 * @param img
 * @return
 */
protected float getCenterX(Rectangle r, Image img)
{
    float x = 0;
    float pdfwidth = r.getWidth();
    float imgwidth = img.getWidth();

    x = (pdfwidth - imgwidth) / 2;

    return x;
}
 
Example 11
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/45062602/itext-pdfappearence-issue">
 * Text - PDFAppearence issue
 * </a>
 * <p>
 * This test shows how one can create a custom signature layer 2.
 * As the OP of the question at hand mainly wants to generate a
 * pure DESCRIPTION appearance that uses the whole area, we here
 * essentially copy the PdfSignatureAppearance.getAppearance code
 * for generating layer 2 in pure DESCRIPTION mode and apply it
 * to a plain pre-fetched layer 2.
 * </p>
 */
@Test
public void signWithCustomLayer2() throws IOException, DocumentException, GeneralSecurityException
{
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf")  )
    {
        PdfReader reader = new PdfReader(resource);
        FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "test-customLayer2.pdf"));
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');

        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setReason("reason");
        appearance.setLocation("location");
        appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");

        // This essentially is the PdfSignatureAppearance.getAppearance code
        // for generating layer 2 in pure DESCRIPTION mode applied to a plain
        // pre-fetched layer 2.
        // vvvvv
        PdfTemplate layer2 = appearance.getLayer(2);
        String text = "We're using iText to put a text inside a signature placeholder in a PDF. "
                + "We use a code snippet similar to this to define the Signature Appearence.\n"
                + "Everything works fine, but the signature text does not fill all the signature "
                + "placeholder area as expected by us, but the area filled seems to have an height "
                + "that is approximately the 70% of the available space.\n"
                + "As a result, sometimes especially if the length of the signature text is quite "
                + "big, the signature text does not fit in the placeholder and the text is striped "
                + "away.";
        Font font = new Font();
        float size = font.getSize();
        final float MARGIN = 2;
        Rectangle dataRect = new Rectangle(
                MARGIN,
                MARGIN,
                appearance.getRect().getWidth() - MARGIN,
                appearance.getRect().getHeight() - MARGIN);
        if (size <= 0) {
            Rectangle sr = new Rectangle(dataRect.getWidth(), dataRect.getHeight());
            size = ColumnText.fitText(font, text, sr, 12, appearance.getRunDirection());
        }
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(appearance.getRunDirection());
        ct.setSimpleColumn(new Phrase(text, font), dataRect.getLeft(), dataRect.getBottom(), dataRect.getRight(), dataRect.getTop(), size, Element.ALIGN_LEFT);
        ct.go();
        // ^^^^^

        ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC");
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
    }
}