FreeText Annotation Appearance Stream In Landscape PDF Using iText - annotations

This is my code to create appearance stream for a free text annotation.
cs.rectangle(bbox.getLeft() , bbox.getBottom(), bbox.getWidth(), bbox.getHeight());
cs.fill();
String[] text = new String[1];
text[0] = "BAC"
cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), pdfJSAnnotation.getFontSize());
cs.beginText();
cs.setLeading(fontSize + 1.75f);
cs.moveText(0, bbox.getHeight() - fontSize + .75f);
for (String s : text) {
if (s.equals("\n"))
cs.newlineText();
else
cs.showText(s);
}
cs.endText();
where cs is PdfAppearance, bbox is Rectangle. This works okay when pdf is portrait. however, im having problems when it is in landscape, say if page rotation is 270.
The text shown is vertical. and even if i use cs.transform() to rotate, it does not even rotate properly. I also tried to save the state, do a rotate then display text and then call cs.restoreState() after cs.endText() but the outcome is still not correct.
any ideas?
the rectangle is correct since the 1st 2 lines where it fills a rectangle shape is correctly displayed. it is the text i am having problems with.

The solution to this is:
- set appearance dimension to (height,width) since it is 270 degrees.
Then in the PdfAppearance object:
translate it to (height, 0);
rotate to 270
translate to (-height,-height);
(Tried to remove this post but there is no option available)

Related

2D Unity: expand UI element based on text to the bottom

I've got a game object (InfoBox) with a..
Vertical Layout Group (Padding 20 on all sides, Control Child Size Height active)
an image
a Content Size Fitter (Vertical Fit set to Preferred Size, Horizontal Unconstrained)
Inside this InfoBox is a Text-Element and every time I update the text, I want the InfoBox to expand or collapse, but to the bottom only. Right now my InfoBox always expands or collapses to both top and bottom, but I don't want that to happen. How can I achieve that? I added some screenshots to better visualise this.
These are my settings for the InfoBox:
And these are my settings for the text:
And this is what happens when I use for example less text, the box collapses from bottom and top, but I want it to stay fixed at the top (on the same line as the green box next to it) and only collapse on the bottom:
Any help is really appreciate!
You main issues looks like you are using a ContentSizeFitter also on the parent object. So it depends how this parent object is aligned with its according parent.
This sentence sounds strange I know but what you did is basically shifting up the alignment responsibility to the parent.
=> Make your UI element aligned to the top and grow downwards.
All you need to do for this is either set
Anchors Min y -> 1
Anchors Max y -> 1
Pivot y -> 1
or simply go to the RectTransform Inspector, open the alignment tool and hold Shift + Alt and click on the top alignment:
For the second instead of using the ContentSizeFitter I prefer to have my own script that only does what it should and nothing more.
You can get the preferredHeight which is exactly the value you are looking for.
The following script simply always applies the preferred height to the text rect. Using [ExecuteAlways] this also works in edit mode. Simply attach it on the same GameObject as the UI.Text component
[ExecuteAlways]
[RequireComponent(typeof(Text))]
[RequireComponent(typeof(RectTransform))]
public class TextHeightFitter : MonoBehaviour
{
[SerializeField] private RectTransform _rectTransform;
[SerializeField] private Text _text;
private void Update()
{
if (!_text) _text = GetComponent<Text>();
if (!_rectTransform) _rectTransform = GetComponent<RectTransform>();
var desiredHeight = _text.preferredHeight;
var size = _rectTransform.sizeDelta;
size.y = desiredHeight;
_rectTransform.sizeDelta = size;
}
}

Drag and drop with pinch zoom doesn't work as expected

In the zoomed mode for pinch-zoom the drag doesn't align properly with the mouse pointer.
I've detailed the problem here:https://stackblitz.com/edit/angular-t7hwqg
I expect the drag to work same way irrespective of the zoom.
I saw in version 8 of angular material they have added #Input('cdkDragConstrainPosition')
constrainPosition: (point: Point, dragRef: DragRef) => Point, which will solve my problem as in the zoomed mode I can write a custom logic to map the drag properly with pointer, but I can't upgrade to version 8 as there are other parts of the application with version 7.
So if someone can suggest what can be done? Either somehow the drag can be modified and take into account the current amount of zoom, or if I can take 'cdkDragConstrainPosition' from version 8 of material and integrate into my current packages.
I had to manually calculate the updated coordinates something like this:
Here imageHeight is the width/height of the DOM element and height is the actual image height that was loaded into the DOM element.
item is the DOM element to be moved around.
this.zoomFactorY = this.imageHeight / this.height;
this.zoomFactorX = this.imageWidth / this.width;
// to be called at every position update
const curTransform = this.item.nativeElement.style.transform.substring(12,
this.item.nativeElement.style.transform.length - 1).split(',');
const leftChange = parseFloat(curTransform[0]);
const topChange = parseFloat(curTransform[1]);
and then update the DOM item's location:
item.location.left = Math.trunc(
item.location.left + leftChange * (1 / this.zoomFactorX)
);
item.location.top = Math.trunc(
item.location.top + topChange * (1 / this.zoomFactorY)
);

Trying to align text in center of rectangle while drawing freeText annotation but text goes in top left corner

I am trying to free text Annotation string align in center of rectangle but always set in top left corner
PdfContentByte pcb = stamper.getOverContent(page);
PdfAnnotation annotation = PdfAnnotation.createFreeText(stamper.getWriter(), rectangle, "Mayank Pandey", pcb);
annotation.put(PdfName.Q, new PdfNumber(PdfFormField.Element.ALIGN_MIDDLE));
Text showing left top corner in pdf:
You set
annotation.put(PdfName.Q, new PdfNumber(PdfFormField.Element.ALIGN_MIDDLE));
The constant Element.ALIGN_MIDDLE is defined as
/**
* A possible value for vertical alignment.
*/
public static final int ALIGN_MIDDLE = 5;
But the value of Q in free text annotations is specified as:
Q
integer
(Optional; PDF 1.4) A code specifying the form of quadding (justification) that shall be used in displaying the annotation’s text:
0 Left-justified
1 Centered
2 Right-justified
Default value: 0 (left-justified).
Thus, value 5 you used is not a valid Quadding value at all!
Furthermore, FreeText Quadding does not even support what you want to achieve, to align in center of rectangle, it only allows to select horizontal alignment, not vertical alignment.
For your objective, therefore, you'll have to use a custom appearance (which takes precedence if present).

iText -- How do I get the rendered dimensions of text?

I would like to find out information about the layout of text in a PdfPCell. I'm aware of BaseFont.getWidthPointKerned(), but I'm looking for more detailed information like:
How many lines would a string need if rendered in a cell of a given width (say, 30pt)? What would the height in points of the PdfPCell be?
Give me the prefix or suffix of a string that fits in a cell of a given width and height. That is, if I have to render the text "Today is a good day to die" in a specific font in a PdfPCell of width 12pt and height 20pt, what portion of the string would fit in the available space?
Where does iText break a given string when asked to render it in a cell of a given width?
This is with regard to iText 2.1.6. Thanks.
iText uses the ColumnText class to render content to a cell. This is explained in my book on page 98-99. This means that, just like with ColumnText, you need to make the distinction between text mode and composite mode.
In any case, ColumnText measures the width of the characters and tests if they fit the available width. If not, the text is split. You can change the split behavior in different ways: by introducing hyphenation or by defining a custom split character.
I've written a small proof of concept to show how you could implement custom "truncation" behavior. See the TruncateTextInCell example.
Instead of adding the content to the cell, I have an empty cell for which I define a cell event. I pass the long text "D2 is a cell with more content than we can fit into the cell." to this event.
In the event, I use a fancy algorithm: I want the text to be truncated in the middle and insert "..." at the place where I truncated the text.
BaseFont bf = BaseFont.createFont();
Font font = new Font(bf, 12);
float availableWidth = position.getWidth();
int contentLength = content.length();
int leftChar = 0;
int rightChar = contentLength - 1;
availableWidth -= bf.getWidthPoint("...", 12);
while (leftChar < contentLength && rightChar != leftChar) {
availableWidth -= bf.getWidthPoint(content.charAt(leftChar), 12);
if (availableWidth > 0)
leftChar++;
else
break;
availableWidth -= bf.getWidthPoint(content.charAt(rightChar), 12);
if (availableWidth > 0)
rightChar--;
else
break;
}
String newContent = content.substring(0, leftChar) + "..." + content.substring(rightChar);
PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(position);
ct.addElement(new Paragraph(newContent, font));
ct.go();
As you can see, we get the available width from the position parameter and we check how many characters match, alternating between a character at the start and a character at the end of the content.
The result is shown in the resulting PDF: the content is truncated like this: "D2 is a c... the cell."
Your question about "how many lines" can be solved in a similar way. The ColumnText class has a getLinesWritten() method that gives you that information. You can find more info about positioning a ColumnText object in my answer to your other question: Can I tell iText how to clip text to fit in a cell

Add rectangle as inline-element with iText

How do I add a rectangle (or other graphical elements) as inline-elements to an iText PDF?
Example code of what I'm trying to achieve:
foreach (Row r in entrylist)
{
p = new Paragraph();
p.IndentationLeft = 10;
p.SpacingBefore = 10;
p.SpacingAfter = 10;
p.Add(new Rectangle(0, 0, 10, 10)); <<<<<<<<< THAT ONE FAILS
p.Add(new Paragraph(r.GetString("caption"), tahoma12b));
p.Add(new Paragraph(r.GetString("description"), tahoma12));
((Paragraph)p[1]).IndentationLeft = 10;
doc.Add(p);
}
It's something like a column of text-blocks, of which each of them have (only a printed) checkbox.
I've tried various things with DirectContent, but it requires me to provide absolute X and Y values. Which I simply don't have. The elements should be printed at the current position, wherever that may be.
Any clues?
You need a Chunk for which you've defined a generic tag. For instance, in this example listing a number of movies, a snippet of pellicule is drawn around the year a movie was produced and an ellipse was drawn in the background of the link to IMDB.
If you look at the MovieYears example, you'll find out how to use the PdfPageEvent interface and its onGenericTag() method. You're right that you can't add a Rectangle to a Paragraph (IMHO that wouldn't make much sense). As you indicate, you need to draw the rectangle to the direct content, and you get the coordinates of a Chunk by using the setGenericTag() method. As soon as the Chunk is drawn on the page, its coordinates will be passed to the onGenericTag() method.