1

I would like to add a link in my overlay text. I've read that using Anchor will only work for documents made from scratch but not for existing pdfs. My code is adding an overlay text to every page. My goal is to make a portion of that text clickable. I don't know how to make a link annotation that is part of a phrase.

Here's my code:

            int n = reader.getNumberOfPages();
            // step 4: we add content
            PdfImportedPage page;
            PdfCopy.PageStamp stamp;
            for (int j = 0; j < n; )
            {
                ++j;
                page = writer.getImportedPage(reader, j);
                if (i == 1) {
                    stamp = writer.createPageStamp(page);
                    Rectangle mediabox = reader.getPageSize(j);
                    Rectangle crop = new Rectangle(mediabox);
                    writer.setCropBoxSize(crop);
                    // add overlay text
                    Paragraph p = new Paragraph();
                    p.setAlignment(Element.ALIGN_CENTER);
                    FONT_URL_OVERLAY.setColor(0, 191, 255);
                    // get current user
                    EPerson loggedin = context.getCurrentUser();
                    String eperson = null;
                    if (loggedin != null)
                    {
                        eperson = loggedin.getFullName();
                    }
                    else eperson = "Anonymous";
                    Phrase downloaded = new Phrase();
                    Chunk site = new Chunk("My Website",FONT_URL_OVERLAY);
                    site.setAction(new PdfAction("http://www.mywebsite.com"));
                    downloaded.add(new Chunk("Downloaded by [" + eperson + "] from ", FONT_OVERLAY));
                    downloaded.add(site);
                    downloaded.add(new Chunk(" on ", FONT_OVERLAY));
                    downloaded.add(new Chunk(new SimpleDateFormat("MMMM d, yyyy").format(new Date()), FONT_OVERLAY));
                    downloaded.add(new Chunk(" at ", FONT_OVERLAY));
                    downloaded.add(new Chunk(new SimpleDateFormat("h:mm a z").format(new Date()), FONT_OVERLAY));
                    p.add(downloaded);
                    ColumnText.showTextAligned(stamp.getOverContent(), Element.ALIGN_CENTER, p,
                            crop.getLeft(10), crop.getHeight() / 2 + crop.getBottom(), 90);
                    stamp.alterContents();
                }
                writer.addPage(page);
            }

So my overlay would looked like this:

Downloaded by [Anonymous] from My Website on February 17, 2015 at 1:20 AM CST

How can I convert My Website to a link annotation? Searching here in SO, I found this post, but I don't know how to apply adding link annotation to a portion of my overlay text.

Thanks in advance.

EDIT: How to add a rotated overlay text with link annotations to existing pdf?
Thanks to Bruno Lowagie for going out of his way in answering my question. Although I originally asked how to add link annotations in an overlay text to existing pdfs, he also catered my questions in the comments section of his answer about setting the coordinates properly if the overlay text were rotated.

Community
  • 1
  • 1
euler
  • 1,401
  • 2
  • 18
  • 39

1 Answers1

2

You are using ColumnText.showAligned() which is sufficient to add a line of text without any special features, but if you want the anchor to work, you need to use ColumnText differently.

This is shown in the AddLinkAnnotation2 example:

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    PdfContentByte canvas = stamper.getOverContent(1);
    Font bold = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    Chunk chunk = new Chunk("The Best iText Questions on StackOverflow", bold);
    chunk.setAnchor("http://pages.itextpdf.com/ebook-stackoverflow-questions.html");
    Phrase p = new Phrase("Download ");
    p.add(chunk);
    p.add(" and discover more than 200 questions and answers.");
    ColumnText ct = new ColumnText(canvas);
    ct.setSimpleColumn(36, 700, 559, 750);
    ct.addText(p);
    ct.go();
    stamper.close();
    reader.close();
}

In this case, we define a rectangle for a ColumnText object, we add the Phrase to the column, and we go().

If you check the result, link_annotation2.pdf, you'll notice that you can click the words in bold.

There are no plans to support this in ColumnText.showTextAligned(). That is a convenience method that can be used as a short-cut for the handful of lines shown above, but there are some known limitations: lines are not wrapped, interactivity is ignored,...

Update 1: in the comment section, you asked an additional question about rotation the content and the link.

Rotating the content isn't difficult. There's even more than one way to do that. Rotating the link isn't trivial, as a link is a type of annotation, and annotations aren't part of the content.

Let's first take a look at AddLinkAnnotation3:

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    AffineTransform transform = AffineTransform.getRotateInstance(Math.PI / 6);
    stamper.getWriter().setPageEvent(new AddAnnotation(stamper, transform));
    PdfContentByte canvas = stamper.getOverContent(1);
    Font bold = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    Chunk chunk = new Chunk("The Best iText Questions on StackOverflow", bold);
    chunk.setGenericTag("http://pages.itextpdf.com/ebook-stackoverflow-questions.html");
    Phrase p = new Phrase("Download ");
    p.add(chunk);
    p.add(" and discover more than 200 questions and answers.");
    canvas.saveState();
    canvas.concatCTM(transform);
    ColumnText ct = new ColumnText(canvas);
    ct.setSimpleColumn(300, 0, 800, 400);
    ct.addText(p);
    ct.go();
    canvas.restoreState();
    stamper.close();
    reader.close();
}

In this example, we define a tranformation of 30 degrees (Math.PI / 6):

AffineTransform transform = AffineTransform.getRotateInstance(Math.PI / 6);

We use this transformation when rendering the column:

canvas.saveState();
canvas.concatCTM(transform);
// render column
canvas.restoreState();

This rotates the content, but we didn't add any annotation yet. Instead, we define a page event:

stamper.getWriter().setPageEvent(new AddAnnotation(stamper, transform));

and we introduced a generic tag:

chunk.setGenericTag("http://pages.itextpdf.com/ebook-stackoverflow-questions.html");

To add the annotation, we use some magic in the page event implementation:

public class AddAnnotation extends PdfPageEventHelper {
    protected PdfStamper stamper;
    protected AffineTransform transform;

    public AddAnnotation(PdfStamper stamper, AffineTransform transform) {
        this.stamper = stamper;
        this.transform = transform;
    }

    @Override
    public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
        float[] pts = {rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()};
        transform.transform(pts, 0, pts, 0, 2);
        float[] dstPts = {pts[0], pts[1], pts[2], pts[3]};
        rect = new Rectangle(dstPts[0], dstPts[1], dstPts[2], dstPts[3]);
        PdfAnnotation annot = PdfAnnotation.createLink(writer, rect, PdfAnnotation.HIGHLIGHT_INVERT, new PdfAction(text));
        stamper.addAnnotation(annot, 1);
    }
}

We create an annotation, but before we do so, we perform a transformation on the rectangle. This makes sure that the text fits the rectangle with the text that needs to be clickable, but... this may not be what you expect:

screen shot

You may have wanted the rectangle to be rotated, and that's possible, but it's more math. For instance: you could create a polygon that is a better fit: ITextShape Clickable Polygon or path

Fortunately, you don't need an angle of 30 degrees, you want to rotate the text with an angle of 90 degrees. In that case, you don't have the strange effect shown in the above screen shot.

Take a look at AddLinkAnnotation4

public class AddAnnotation extends PdfPageEventHelper {
    protected PdfStamper stamper;
    protected AffineTransform transform;

    public AddAnnotation(PdfStamper stamper, AffineTransform transform) {
        this.stamper = stamper;
        this.transform = transform;
    }

    @Override
    public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
        float[] pts = {rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()};
        transform.transform(pts, 0, pts, 0, 2);
        float[] dstPts = {pts[0], pts[1], pts[2], pts[3]};
        rect = new Rectangle(dstPts[0], dstPts[1], dstPts[2], dstPts[3]);
        PdfAnnotation annot = PdfAnnotation.createLink(writer, rect, PdfAnnotation.HIGHLIGHT_INVERT, new PdfAction(text));
        annot.setBorder(new PdfBorderArray(0, 0, 0));
        stamper.addAnnotation(annot, 1);
    }

}

As you can see, I've added a single line to remove the border (the border is there by default unless you redefine the PdfBorderArray).

The rest of the code is also almost identical. We now define an angle of Math.PI / 2 (90 degrees).

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    AffineTransform transform = AffineTransform.getRotateInstance(Math.PI / 2);
    stamper.getWriter().setPageEvent(new AddAnnotation(stamper, transform));
    PdfContentByte canvas = stamper.getOverContent(1);
    Font bold = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    Chunk chunk = new Chunk("The Best iText Questions on StackOverflow", bold);
    chunk.setGenericTag("http://pages.itextpdf.com/ebook-stackoverflow-questions.html");
    Phrase p = new Phrase("Download ");
    p.add(chunk);
    p.add(" and discover more than 200 questions and answers.");
    canvas.saveState();
    canvas.concatCTM(transform);
    ColumnText ct = new ColumnText(canvas);
    ct.setSimpleColumn(36, -559, 806, -36);
    ct.addText(p);
    ct.go();
    canvas.restoreState();
    stamper.close();
    reader.close();
}

Note that the lower left corner of the page is the pivot point, hence we need to adapt the coordinates where we add the column, otherwise you'll rotate all the content outside the visible area of the page.

Update 2:

In yet another comment, you are asking about the coordinates you need to use when adding text in a rotated coordinate system.

I made this drawing: enter image description here

In the top part, you add the word MIDDLE in the middle of a page, but that's not where it will appear: you are rotating everything by 90 degrees, hence the word MIDDLE will rotate outside your page (into the hatched area). The word will be in the PDF, but you'll never see it.

If you look at my code, you see that I use these coordinates:

ct.setSimpleColumn(36, -559, 806, -36);

This is outside the visible area (it's below the actual page dimensions), but as I rotate everything with 90 degrees, it rotates into the visible area.

If you look at my drawing, you can see that the page with coordinates (0, 0), (0, -595), (842, -598) and (842, 0) rotates by 90 degrees and thus gets the coincides with a page with coordinates (0, 0), (595, 0), (595, 842) and (0, 842). That's the type of Math we all learned in high school ;-)

You were adding text at position crop.getLeft(10), crop.getHeight() / 2 + crop.getBottom(). If you know that the text will be rotated by 90 degrees, you should use crop.getHeight() / 2 + crop.getBottom(), -crop.getLeft().

The best way to understand why, is to make a drawing.

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • Is there a way to apply rotation to setSimpleColumn? My overlay text is supposed to be vertically centered and at the leftmost portion of the page rotated 90 degrees. Thanks. – euler Feb 17 '15 at 09:54
  • That's not trivial as annotations aren't part of the content and hence they are rotated if you rotate the content. That doesn't mean it's not possible, though. If you're an iText customer, please create a ticket in the issue tracker for customers and your request will get priority. If you're not a customer, you'll have to wait until I have some time to make an example. – Bruno Lowagie Feb 17 '15 at 12:10
  • Thanks for the update on your answer Bruno. I'll accept this answer shortly. I have one last question though, regarding the setting of coordinates in setSimpleColumn. I have stated in my question that my overlay text is supposed to be centered vertically, its because I don't know in advance the actual page size of the source pdf. Why is it that I can't apply the `crop.getLeft(10), crop.getHeight() / 2 + crop.getBottom()` as my parameters in setSimpleColumn? I can't seem to center my text vertically. Thanks once again. – euler Feb 17 '15 at 15:18
  • I have discovered something in [link_annotation3.pdf](http://itextpdf.com/sites/default/files/link_annotation3.pdf) and [link_annotation4.pdf](http://itextpdf.com/sites/default/files/link_annotation4.pdf). Although the text **The Best iText Questions on StackOverflow** is clickable, it does not go to http://pages.itextpdf.com/ebook-stackoverflow-questions.html. Inspecting this with acrobat revealed that the action in the link properties is "Go to a page in this document" and not "Open a web link". – euler Feb 17 '15 at 16:10
  • 1
    I am a very busy man. I answered your question in-between two meetings. That's how I made a small error: I used `text` instead of `new PdfAction(text)`. I've corrected that in my answer, I'll now change the examples on the site. – Bruno Lowagie Feb 17 '15 at 18:16
  • Hello. Can I add background color of the overlay text? How should I do? – ABCman Nov 26 '20 at 07:20