简体   繁体   中英

How can I vertically clip a text anchor in iText (Java)

I have read both Can I tell iText how to clip text to fit in a cell and http://osdir.com/ml/java.lib.itext.general/2005-01/msg00112.html , and I'm still confused about how to do what I want. I want to clip the text but still have the anchor reference work. Putting an anchor inside a template is no good (as per the second link). Here's the code I was using (I understand why it doesn't work, just not what to do instead):

public static void drawTextClipped(PdfContentByte canvas, Rectangle rect, float clipHeight, Phrase p, int horizontalAlignment)
{
    PdfTemplate tmp = canvas.createTemplate(rect.getWidth(), clipHeight);
    drawColumnText(tmp, new Rectangle(0, clipHeight - rect.getHeight(), rect.getWidth(), clipHeight), p, horizontalAlignment, false);
    canvas.addTemplate(tmp, rect.getLeft(), rect.getTop() - clipHeight);
}

public static float drawColumnText(PdfContentByte parent, Rectangle rect, Phrase p, int horizontalAlignment, boolean simulate)
{
    try
    {
        ColumnText ct = new ColumnText(parent);
        ct.setLeading(0, 1);
        ct.setSimpleColumn(rect);
        ct.setText(p);
        ct.setAlignment(horizontalAlignment);
        ct.go(simulate);
        return ct.getYLine();
    }
    catch (DocumentException de)
    {
        throw new ExceptionConverter(de);
    }
}

Bear in mind that this displays correctly, but when Phrase p is an Anchor, it is unclickable. Thanks!

The PdfTemplate class can be used to create Form XObjects . These are reusable PDF content streams.

A link is never part of the content stream. A link is an annotation that is defined at the page level. You can never define a link at the level of a Form XObject. For the point of view of a PDF expert, it is a logical error to think that your code would work.

For your rectangle to be clickable, you need to add a method addLinkAnnotation() . You need to pass a PdfWriter and a Rectangle parameter to this method, and do something like this:

PdfAnnotation annotation = PdfAnnotation.createLink(
    writer, rect, PdfAnnotation.HIGHLIGHT_INVERT, new PdfAction("http://itextpdf.com"));
writer.addAnnotation(annotation);

This will make the rectangle clickable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM