com.itextpdf.text.Rectangle Java Examples

The following examples show how to use com.itextpdf.text.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: AnnotationIcons.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46204693/cant-get-itext-rectangle-to-work-correctly-with-annotations">
 * Can't get itext Rectangle to work correctly with annotations
 * </a>
 * <p>
 * This test looks at a <b>Text</b> annotation added via a {@link Chunk}
 * as done by the OP. As this way of adding annotations resets the
 * annotation <b>Rect</b> to the bounding box of the rendered {@link Chunk},
 * it is not really what the OP wants.
 * </p>
 */
@Test
public void testAnnotationIconForTYD() throws FileNotFoundException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "annotationIcons.pdf")));
    document.open();

    // Not "new Rectangle(164, 190, 164, 110)" which would be empty
    Rectangle rect = new Rectangle(164, 190, 328, 300);

    // Annotation added like the OP does
    Chunk chunk_text = new Chunk("Let's test a Text annotation...");
    chunk_text.setAnnotation(PdfAnnotation.createText(writer, rect, "Warning", "This is a Text annotation with Comment icon.", false, "Comment"));        

    document.add(chunk_text);

    // Annotation added to the document without Chunk
    writer.addAnnotation(PdfAnnotation.createText(writer, rect, "Warning 2", "This is another Text annotation with Comment icon.", false, "Comment"));

    document.close();
}
 
Example #2
Source File: AddAnnotation.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41949253/how-to-add-columntext-as-an-annotation-in-itext-pdf">
 * How to add columnText as an annotation in itext pdf
 * </a>
 * <p>
 * This test demonstrates how to use a columntext in combination with an annotation.
 * </p>
 */
@Test
public void testAddAnnotationLikeJasonY() throws IOException, DocumentException
{
    String html ="<html><h1>Header</h1><p>A paragraph</p><p>Another Paragraph</p></html>";
    String css = "h1 {color: red;}";
    ElementList elementsList = XMLWorkerHelper.parseToElementList(html, css);

    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "JasonY.pdf"))   )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);

        Rectangle cropBox = reader.getCropBox(1);

        PdfAnnotation annotation = stamper.getWriter().createAnnotation(cropBox, PdfName.FREETEXT);
        PdfAppearance appearance = PdfAppearance.createAppearance(stamper.getWriter(), cropBox.getWidth(), cropBox.getHeight());

        ColumnText ct = new ColumnText(appearance);
        ct.setSimpleColumn(new Rectangle(cropBox.getWidth(), cropBox.getHeight()));
        elementsList.forEach(element -> ct.addElement(element));
        ct.go();

        annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, appearance);
        stamper.addAnnotation(annotation, 1);

        stamper.close();
        reader.close();
    }
}
 
Example #3
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
@Test
public void signCertify2gNoAppend() throws IOException, DocumentException, GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath, null, true);
    FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-certified-noAppend.pdf"));
    PdfStamper stamper =
        PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain,
        null, null, null, 0, subfilter);
}
 
Example #4
Source File: PageHeaderFooterEvent.java    From ureport with Apache License 2.0 7 votes vote down vote up
private PdfPCell buildPdfPCell(HeaderFooter phf,String text,int type){
	PdfPCell cell=new PdfPCell();
	cell.setPadding(0);
	cell.setBorder(Rectangle.NO_BORDER);
	Font font=FontBuilder.getFont(phf.getFontFamily(), phf.getFontSize(), phf.isBold(), phf.isItalic(),phf.isUnderline());
	String fontColor=phf.getForecolor();
	if(StringUtils.isNotEmpty(fontColor)){
		String[] color=fontColor.split(",");
		font.setColor(Integer.valueOf(color[0]), Integer.valueOf(color[1]), Integer.valueOf(color[2]));			
	}
	Paragraph graph=new Paragraph(text,font);
	cell.setPhrase(graph);
	switch(type){
	case 1:
		cell.setHorizontalAlignment(Element.ALIGN_LEFT);
		break;
	case 2:
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		break;
	case 3:
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		break;
	}
	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	return cell;
}
 
Example #5
Source File: PdfCleanUpRegionFilter.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Checks if the text is 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) {
        Point2D[] redactRect = getVertices(rectangle);

        if (intersect(glyphRect, redactRect)) {
            return false;
        }
    }

    return true;
}
 
Example #6
Source File: SwitchPageCanvas.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34394199/i-cant-rotate-my-page-from-existing-pdf">
 * I can't rotate my page from existing PDF
 * </a>
 * <p>
 * Switching between portrait and landscape like this obviously will cut off some parts of the page.
 * </p>
 */
@Test
public void testSwitchOrientation() throws DocumentException, IOException
{
    try (InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/n2013.00849449.pdf"))
    {
        PdfReader reader = new PdfReader(resourceStream);
        int n = reader.getNumberOfPages();
        PdfDictionary pageDict;
        for (int i = 1; i <= n; i++) {
            Rectangle rect = reader.getPageSize(i);
            Rectangle crop = reader.getCropBox(i);
            pageDict = reader.getPageN(i);
            pageDict.put(PdfName.MEDIABOX, new PdfArray(new float[] {rect.getBottom(), rect.getLeft(), rect.getTop(), rect.getRight()}));
            pageDict.put(PdfName.CROPBOX, new PdfArray(new float[] {crop.getBottom(), crop.getLeft(), crop.getTop(), crop.getRight()}));
        }
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "n2013.00849449-switch.pdf")));
        stamper.close();
        reader.close();
    }
}
 
Example #7
Source File: EnlargePagePart.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35374110/how-do-i-use-itext-to-have-a-landscaped-pdf-on-half-of-a-a4-back-to-portrait-and">
 * How do i use iText to have a landscaped PDF on half of a A4 back to portrait and full size on A4
 * </a>
 * <p>
 * This sample shows how to rotate and enlarge the upper half of an A4 page to fit into a new A4 page.
 * </p>
 */
@Test
public void testRotateAndZoomUpperHalfPage() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test-upperHalf.pdf"))   )
    {
        PdfReader reader = new PdfReader(resource);
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, result);
        document.open();

        double sqrt2 = Math.sqrt(2);
        Rectangle pageSize = reader.getPageSize(1);
        PdfImportedPage importedPage = writer.getImportedPage(reader, 1);
        writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2);
        
        document.close();
    }
}
 
Example #8
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 #9
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38605538/itextpdf-redaction-partly-redacted-text-string-is-fully-removed">
 * itextpdf Redaction :Partly redacted text string is fully removed
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B42NqA5UnXMVMDc4MnE5VmU5YVk/view">
 * Document.pdf
 * </a>
 * <p>
 * This indeed is a case which shows that glyphs are completely removed even if their
 * bounding box merely minutely intersects the redaction area. While not desired by
 * the OP, this is how <code>PdfCleanUp</code> works.
 * </p>
 * 
 * @see #testRedactStrictForMayankPandey()
 * @see #testRedactStrictForMayankPandeyLarge()
 */
@Test
public void testRedactLikeMayankPandey() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("Document.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Document-redacted.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfCleanUpProcessor cleaner= null;
        PdfStamper stamper = new PdfStamper(reader, result);
        stamper.setRotateContents(false);
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
        Rectangle rectangle = new Rectangle(380, 640, 430, 665);
        cleanUpLocations.add(new PdfCleanUpLocation(1, rectangle, BaseColor.BLACK));
        cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);   
        cleaner.cleanUp();
        stamper.close();
        reader.close();
    }
}
 
Example #10
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 #11
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/44304695/itext-5-5-11-bold-text-looks-blurry-after-using-pdfcleanupprocessor">
 * iText 5.5.11 - bold text looks blurry after using PdfCleanUpProcessor
 * </a>
 * <br/>
 * <a href="http://s000.tinyupload.com/index.php?file_id=52420782334200922303">
 * before.pdf
 * </a>
 * <p>
 * Indeed, the observation by the OP can be reproduced. The issue has been introduced
 * into iText in commits d5abd23 and 9967627, both dated May 4th, 2015.
 * </p>
 */
@Test
public void testRedactLikeTieco() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("before.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "before-redacted.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();

        cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(0f, 0f, 595f, 680f)));

        PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);
        cleaner.cleanUp();

        stamper.close();
        reader.close();
    }
}
 
Example #12
Source File: ImportPageWithoutFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method creates a PDF with a single styled paragraph.
 */
static byte[] createSimpleCircleGraphicsPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    float y = writer.getPageSize().getTop(document.topMargin());
    float radius = 20;
    for (int i = 0; i < 3; i++)
    {
        Rectangle pageSize = writer.getPageSize();
        writer.getDirectContent().circle(
                pageSize.getLeft(document.leftMargin()) + (pageSize.getWidth() - document.leftMargin() - document.rightMargin()) * Math.random(),
                y-radius, radius);
        y-= 2*radius + 5;
    }

    writer.getDirectContent().fillStroke();
    document.close();

    return baos.toByteArray();
}
 
Example #13
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void sign50MBrunoPartial() throws IOException, DocumentException, GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath, null, true);
    FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "50m-signedBrunoPartial.pdf"));
    PdfStamper stamper =
        PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, false);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain,
        null, null, null, 0, subfilter);
}
 
Example #14
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void sign50MBrunoAppend() throws IOException, DocumentException, GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath);
    FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "50m-signedBrunoAppend.pdf"));
    PdfStamper stamper =
        PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain,
        null, null, null, 0, subfilter);
}
 
Example #15
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example #16
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/38240692/error-in-redaction-with-itext-5-the-color-depth-1-is-not-supported-exception">
 * Error in redaction with iText 5: “The color depth 1 is not supported.” exception when apply redaction on pdf which contain image also
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B42NqA5UnXMVbkhQQk9tR2hpSUE/view?pref=2&pli=1">
 * Pages from Miscellaneous_corrupt.pdf
 * </a>
 * <p>
 * In iText 5.5.11 a work-around for this issue has been added to iText, images in
 * formats not explicitly supported by itext are now removed as a whole if they
 * intersect a redaction area.
 * </p>
 */
@Test
public void testRedactLikeMayankPandeyPagesfromMiscellaneous_corrupt() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("Pages from Miscellaneous_corrupt.pdf");
            OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Pages from Miscellaneous_corrupt-redacted.pdf")) )
    {
        PdfReader reader = new PdfReader(resource);
        PdfCleanUpProcessor cleaner= null;
        PdfStamper stamper = new PdfStamper(reader, result);
        stamper.setRotateContents(false);
        List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
        Rectangle rectangle = new Rectangle(190, 320, 430, 665);
        cleanUpLocations.add(new PdfCleanUpLocation(1, rectangle, BaseColor.BLACK));
        cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);   
        cleaner.cleanUp();
        stamper.close();
        reader.close();
    }
}
 
Example #17
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void sign50MBrunoPartialAppend() throws IOException, DocumentException, GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath, null, true);
    FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "50m-signedBrunoPartialAppend.pdf"));
    PdfStamper stamper =
        PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain,
        null, null, null, 0, subfilter);
}
 
Example #18
Source File: PdfCleanUpRegionFilter.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Calculates intersection of the image and the render filter region in the coordinate system relative to the image.
 *
 * @return <code>null</code> if the image is not allowed, {@link java.util.List} of
 * {@link com.itextpdf.text.Rectangle} objects otherwise.
 */
protected List<Rectangle> getCoveredAreas(ImageRenderInfo renderInfo) {
    Rectangle imageRect = calcImageRect(renderInfo);
    List<Rectangle> coveredAreas = new ArrayList<Rectangle>();

    if (imageRect == null) {
        return null;
    }

    for (Rectangle rectangle : rectangles) {
        Rectangle intersectionRect = intersection(imageRect, rectangle);

        if (intersectionRect != null) {
            // True if the image is completely covered
            if (imageRect.equals(intersectionRect)) {
                return null;
            }

            coveredAreas.add(transformIntersection(renderInfo.getImageCTM(), intersectionRect));
        }
    }

    return coveredAreas;
}
 
Example #19
Source File: PdfCleanUpRegionFilter.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Note: this method will close all unclosed subpaths of the passed path.
 *
 * @param fillingRule If the subpath is contour, pass any value.
 */
protected Path filterFillPath(Path path, Matrix ctm, int fillingRule) {
    path.closeAllSubpaths();

    Clipper clipper = new DefaultClipper();
    addPath(clipper, path);

    for (Rectangle rectangle : rectangles) {
        Point2D[] transfRectVertices = transformPoints(ctm, true, getVertices(rectangle));
        addRect(clipper, transfRectVertices, PolyType.CLIP);
    }

    PolyFillType fillType = PolyFillType.NON_ZERO;

    if (fillingRule == PathPaintingRenderInfo.EVEN_ODD_RULE) {
        fillType = PolyFillType.EVEN_ODD;
    }

    PolyTree resultTree = new PolyTree();
    clipper.execute(ClipType.DIFFERENCE, resultTree, fillType, PolyFillType.NON_ZERO);

    return convertToPath(resultTree);
}
 
Example #20
Source File: TestTrimPdfPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testWithWriter() throws DocumentException, IOException
{
    InputStream resourceStream = getClass().getResourceAsStream("test.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        Rectangle pageSize = reader.getPageSize(1);

        Rectangle rect = getOutputPageSize(pageSize, reader, 1);

        Document document = new Document(rect, 0, 0, 0, 0);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-writer.pdf")));

        document.open();
        PdfImportedPage page;

        // Go through all pages
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++)
        {
            document.newPage();
            page = writer.getImportedPage(reader, i);
            System.out.println("BBox:  "+ page.getBoundingBox().toString());
            Image instance = Image.getInstance(page);
            document.add(instance);
            Rectangle outputPageSize = document.getPageSize();
            System.out.println(outputPageSize.toString());
        }
        document.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example #21
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
void run(IGanttProject project, UIFacade facade, OutputStream out) throws ExportException {
  myProject = project;
  myUIFacade = facade;
  Rectangle pageSize = PageSize.getRectangle(myPageSizeOption.getValue());
  if (myLandscapeOption.isChecked()) {
    pageSize = pageSize.rotate();
  }
  myDoc = new Document(pageSize, 20, 20, 70, 40);
  try {
    myWriter = PdfWriter.getInstance(myDoc, out);
    myWriter.setPageEvent(this);
    myDoc.open();
    writeProject();
  } catch (Throwable e) {
    e.printStackTrace();
    throw new ExportException("Export failed", e);
  } finally {
    myDoc.close();
  }
}
 
Example #22
Source File: OrganizationReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example #23
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createMultiUseIndirectTextPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    PdfReader reader = new PdfReader(createSimpleTextPdf());
    PdfImportedPage template = writer.getImportedPage(reader, 1);
    Rectangle pageSize = reader.getPageSize(1);
    writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), (pageSize.getTop() + pageSize.getBottom()) / 2);
    writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), pageSize.getBottom());
    document.newPage();
    writer.getDirectContent().addTemplate(template, pageSize.getLeft(), pageSize.getBottom());
    document.close();

    return baos.toByteArray();
}
 
Example #24
Source File: UseColumnText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 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 #25
Source File: CreateEllipse.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t">
 * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5
 * </a>
 * <p>
 * This test creates an ellipse annotation without appearance on a page without rotation. Everything looks ok.
 * </p>
 * @see #testCreateEllipseAppearance()
 * @see #testCreateEllipseOnRotated()
 * @see #testCreateEllipseAppearanceOnRotated()
 * @see #testCreateCorrectEllipseAppearanceOnRotated()
 */
@Test
public void testCreateEllipse() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-ellipse.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150);

        PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false);
        annotation.setFlags(PdfAnnotation.FLAGS_PRINT);
        annotation.setColor(BaseColor.RED);
        annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID));

        stamper.addAnnotation(annotation, 1);

        stamper.close();
        reader.close();
    }
}
 
Example #26
Source File: RotateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testOPCode() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-annotate.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        Rectangle linkLocation = new Rectangle( 100, 700, 100 + 200, 700 + 25 );
        PdfName highlight = PdfAnnotation.HIGHLIGHT_INVERT;
        PdfAnnotation linkRed  = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "red" );
        PdfAnnotation linkGreen = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "green" );
        BaseColor baseColorRed = new BaseColor(255,0,0);
        BaseColor baseColorGreen = new BaseColor(0,255,0);
        linkRed.setColor(baseColorRed);
        linkGreen.setColor(baseColorGreen);
        double angleDegrees = 10;
        double angleRadians = Math.PI*angleDegrees/180;
        stamper.addAnnotation(linkRed, 1);
        linkGreen.applyCTM(AffineTransform.getRotateInstance(angleRadians));
        stamper.addAnnotation(linkGreen, 1);
        stamper.close();
    }
}
 
Example #27
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void signCertify2gFix() throws IOException, DocumentException, GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g-fix.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath, null, true);
    FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-fix-certified.pdf"));
    PdfStamper stamper =
        PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain,
        null, null, null, 0, subfilter);
}
 
Example #28
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 #29
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testRotatedRedactionIndirect() throws DocumentException, IOException
{
    byte[] simple = createRotatedIndirectTextPdf();
    Files.write(new File(OUTPUTDIR, "rotateIndirect.pdf").toPath(), simple);

    byte[] redacted = cleanUp(simple, Collections.singletonList(new PdfCleanUpLocation(1, new Rectangle(97f, 405f, 480f, 445f), BaseColor.GRAY)));
    Files.write(new File(OUTPUTDIR, "rotateIndirectRedacted.pdf").toPath(), redacted);
}
 
Example #30
Source File: CreateEllipse.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t">
 * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5
 * </a>
 * <p>
 * This test creates an ellipse annotation with appearance on a page without rotation. Everything looks ok.
 * </p>
 * @see #testCreateEllipse()
 * @see #testCreateEllipseOnRotated()
 * @see #testCreateEllipseAppearanceOnRotated()
 * @see #testCreateCorrectEllipseAppearanceOnRotated()
 */
@Test
public void testCreateEllipseAppearance() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-ellipse-appearance.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150);

        PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false);
        annotation.setFlags(PdfAnnotation.FLAGS_PRINT);
        annotation.setColor(BaseColor.RED);
        annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID));

        PdfContentByte cb = stamper.getOverContent(1);
        PdfAppearance app = cb.createAppearance(rect.getWidth(), rect.getHeight());
        app.setColorStroke(BaseColor.RED);
        app.setLineWidth(3.5);
        app.ellipse( 1.5,  1.5, rect.getWidth() - 1.5, rect.getHeight() - 1.5);
        app.stroke();
        annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, app);

        stamper.addAnnotation(annotation, 1);

        stamper.close();
        reader.close();
    }
}