Java Code Examples for com.itextpdf.text.pdf.PdfStamper#addAnnotation()

The following examples show how to use com.itextpdf.text.pdf.PdfStamper#addAnnotation() . 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: 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 2
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 3
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 4
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 with rotation.
 * The ellipse form looks ok but it is moved to the right of the actual appearance rectangle when viewed in Adobe Reader.
 * This is caused by iText creating a non-standard rectangle, the lower left not being the lower left etc.
 * </p>
 * @see #testCreateEllipse()
 * @see #testCreateEllipseAppearance()
 * @see #testCreateEllipseAppearanceOnRotated()
 * @see #testCreateCorrectEllipseAppearanceOnRotated()
 */
@Test
public void testCreateEllipseOnRotated() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90));

        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 5
Source File: InsertPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <p>
 * A primitive attempt at copying links from page <code>sourcePage</code>
 * of <code>PdfReader reader</code> to page <code>targetPage</code> of
 * <code>PdfStamper stamper</code>.
 * </p>
 * <p>
 * This method is meant only for the use case at hand, i.e. copying a link
 * to an external URI without expecting any advanced features.
 * </p>
 */
void copyLinks(PdfStamper stamper, int targetPage, PdfReader reader, int sourcePage)
{
    PdfDictionary sourcePageDict = reader.getPageNRelease(sourcePage);
    PdfArray annotations = sourcePageDict.getAsArray(PdfName.ANNOTS);
    if (annotations != null && annotations.size() > 0)
    {
        for (PdfObject annotationObject : annotations)
        {
            annotationObject = PdfReader.getPdfObject(annotationObject);
            if (!annotationObject.isDictionary())
                continue;
            PdfDictionary annotation = (PdfDictionary) annotationObject;
            if (!PdfName.LINK.equals(annotation.getAsName(PdfName.SUBTYPE)))
                continue;

            PdfArray rectArray = annotation.getAsArray(PdfName.RECT);
            if (rectArray == null || rectArray.size() < 4)
                continue;
            Rectangle rectangle = PdfReader.getNormalizedRectangle(rectArray);

            PdfName hightLight = annotation.getAsName(PdfName.H);
            if (hightLight == null)
                hightLight = PdfAnnotation.HIGHLIGHT_INVERT;

            PdfDictionary actionDict = annotation.getAsDict(PdfName.A);
            if (actionDict == null || !PdfName.URI.equals(actionDict.getAsName(PdfName.S)))
                continue;
            PdfString urlPdfString = actionDict.getAsString(PdfName.URI);
            if (urlPdfString == null)
                continue;
            PdfAction action = new PdfAction(urlPdfString.toString());

            PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(), rectangle, hightLight, action);
            stamper.addAnnotation(link, targetPage);
        }
    }
}
 
Example 6
Source File: RotateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testOwnAppearances() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-annotate-app.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        BaseColor baseColorRed = new BaseColor(255,0,0);
        BaseColor baseColorGreen = new BaseColor(0,255,0);
        Rectangle linkLocation = new Rectangle( 100, 700, 100 + 200, 700 + 25 );
        PdfName highlight = PdfAnnotation.HIGHLIGHT_INVERT;

        PdfAnnotation linkGreen = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "green" );
        PdfTemplate appearance = PdfTemplate.createTemplate(stamper.getWriter(), linkLocation.getWidth(), linkLocation.getHeight());
        appearance.setColorFill(baseColorGreen);
        appearance.rectangle(0, 0, linkLocation.getWidth(), linkLocation.getHeight());
        appearance.fill();
        double angleDegrees = 35;
        double angleRadians = Math.PI*angleDegrees/180;
        AffineTransform at = AffineTransform.getRotateInstance(angleRadians);
        appearance.setMatrix((float)at.getScaleX(), (float)at.getShearY(),(float) at.getShearX(), (float)at.getScaleY(),(float) at.getTranslateX(), (float)at.getTranslateY());
        linkGreen.setAppearance(PdfName.N, appearance);
        linkGreen.setColor(baseColorGreen);
        stamper.addAnnotation(linkGreen, 1);

        PdfAnnotation linkRed  = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "red" );
        linkRed.setColor(baseColorRed);
        stamper.addAnnotation(linkRed, 1);

        stamper.close();
    }
}
 
Example 7
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();
    }
}
 
Example 8
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 with rotation.
 * The ellipse position looks ok but it is deformed.
 * This is caused by iText rotating the annotation rectangle but not (how could it?) the appearance rectangle.
 * </p>
 * @see #testCreateEllipse()
 * @see #testCreateEllipseAppearance()
 * @see #testCreateEllipseOnRotated()
 * @see #testCreateCorrectEllipseAppearanceOnRotated()
 */
@Test
public void testCreateEllipseAppearanceOnRotated() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse-appearance.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90));

        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();
    }
}
 
Example 9
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 with switched dimensions on a page with rotation.
 * Everything looks ok.
 * </p>
 * @see #testCreateEllipse()
 * @see #testCreateEllipseAppearance()
 * @see #testCreateEllipseOnRotated()
 * @see #testCreateEllipseAppearanceOnRotated()
 */
@Test
public void testCreateCorrectEllipseAppearanceOnRotated() throws IOException, DocumentException
{
    try (   InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf");
            OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse-appearance-correct.pdf"))    )
    {
        PdfReader reader = new PdfReader(resourceStream);
        reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90));

        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.getHeight(), rect.getWidth());
        app.setColorStroke(BaseColor.RED);
        app.setLineWidth(3.5);
        app.ellipse( 1.5,  1.5, rect.getHeight() - 1.5, rect.getWidth() - 1.5);
        app.stroke();
        annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, app);

        stamper.addAnnotation(annotation, 1);

        stamper.close();
        reader.close();
    }
}
 
Example 10
Source File: CreateEmptyField.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32332490/new-signature-field-rotated-90-degrees">
 * New Signature Field Rotated 90 Degrees
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=0B3pKBz-WDrXnM3hYeDFtXzhldnM">
 * DA3161-Template.pdf
 * </a>
 * <p>
 * The page in your document is rotated using the Rotate page dictionary entry.
 * When creating a field to be filled-in by others later, you have to add a hint
 * to the field indicating a counter-rotation if you want the field content to
 * effectively appear upright.
 * </p>
 * <p>
 * You do this by setting the MKRotation attribute of the field. This creates a
 * rotation entry R with value 90 in the appearance characteristics dictionary
 * MK of the field.
 * </p>
 */
@Test
public void testDA3161_Template() throws IOException, GeneralSecurityException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("DA3161-Template.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "DA3161-Template_Field.pdf"))    )
    {
        System.out.println("DA3161-Template.pdf");
        PdfReader reader = new PdfReader(resource);
        PdfStamper pdfStamper = new PdfStamper(reader, result);
        AcroFields fields = pdfStamper.getAcroFields();
        int itemno = 3;

      //Get location to the field where we will place the signature field
        FieldPosition NewPosition = fields.getFieldPositions("DESC_0_" + (itemno + 1)).get(0);
        float l1 = NewPosition.position.getLeft();
        float r1 = NewPosition.position.getRight();
        float t1 = NewPosition.position.getTop();
        float b1 = NewPosition.position.getBottom();

        PdfFormField field = PdfFormField.createSignature(pdfStamper.getWriter());
        field.setFieldName("G4_SignatureX");

        // Set the widget properties
        field.setWidget(new Rectangle(r1, t1, l1, b1), PdfAnnotation.HIGHLIGHT_NONE);
        field.setFlags(PdfAnnotation.FLAGS_PRINT);

        // !!!!!!!!!!!!!!!!!!!
        field.setMKRotation(90);

        // Add the annotation
        pdfStamper.addAnnotation(field, 1);

        pdfStamper.close();
    }
}
 
Example 11
Source File: AddField.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32445174/missing-deselected-display-items-at-the-beginning-of-the-list-box-itextsharp">
 * Missing deselected display items at the beginning of the list box (iTextSharp)
 * </a>
 * <br/>
 * <a href="http://stackoverflow.com/questions/37587703/deselected-display-items-missing-at-the-beginning-of-the-list-box-itextsharp">
 * Deselected display items missing at the beginning of the list box (iTextSharp)
 * </a>
 * 
 * <p>
 * This is the equivalent code to the OP's VB .Net code.
 * </p>
 * <p>
 * Indeed, "One" is invisible at first. As a fix, set the VisibleTopChoice.
 * </p>
 */
@Test
public void testAddLikeNickK() throws IOException, DocumentException
{
    File myFile = new File(RESULT_FOLDER, "test-multiSelectBox.pdf");
    
    Rectangle newRect = new Rectangle(231.67f, 108.0f, 395.67f, 197.0f);
    String newFldName = "ListBox1";
    int pg = 1;

    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf");
            OutputStream output = new FileOutputStream(myFile)  )
    {
        PdfReader pdfReader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(pdfReader, output);
        
        TextField txtField = new TextField(stamper.getWriter(), newRect, newFldName);
        txtField.setTextColor(BaseColor.BLACK);
        txtField.setBackgroundColor(BaseColor.WHITE);
        txtField.setBorderColor(BaseColor.BLACK);
        txtField.setFieldName(newFldName);
        txtField.setAlignment(0); //LEFT
        txtField.setBorderStyle(0); //SOLID
        txtField.setBorderWidth(1.0F); //THIN
        txtField.setVisibility(TextField.VISIBLE);
        txtField.setRotation(0); //None
        txtField.setBox(newRect);
        //PdfArray opt = new PdfArray();
        List<String> ListBox_ItemDisplay = new ArrayList<String>();
        ListBox_ItemDisplay.add("One");
        ListBox_ItemDisplay.add("Two");
        ListBox_ItemDisplay.add("Three");
        ListBox_ItemDisplay.add("Four");
        ListBox_ItemDisplay.add("Five");
        List<String> ListBox_ItemValue = new ArrayList<String>();
        ListBox_ItemValue.add("1X");
        ListBox_ItemValue.add("2X");
        ListBox_ItemValue.add("3X");
        ListBox_ItemValue.add("4X");
        ListBox_ItemValue.add("5X");
        txtField.setOptions(txtField.getOptions() | TextField.MULTISELECT);
        ArrayList<Integer> selIndex = new ArrayList<Integer>();
        //List<String> selValues = new ArrayList<String>();
        selIndex.add(1); // SELECT #1 (index)
        selIndex.add(3); // SELECT #3 (index)
        txtField.setChoices(ListBox_ItemDisplay.toArray(new String[0]));
        txtField.setChoiceExports(ListBox_ItemValue.toArray(new String[0]));
        txtField.setChoiceSelections(selIndex);
        // vvv--- Add this line as a fix
        txtField.setVisibleTopChoice(0);
        // ^^^--- Add this line as a fix
        PdfFormField listField = txtField.getListField();
        stamper.addAnnotation(listField, pg);

        stamper.close();
    }
}